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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1381  ! raeburn     4: # $Id: loncommon.pm,v 1.1380 2022/05/29 03:19:00 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.1280    raeburn    74: use LONCAPA::LWPReq;
1.1328    raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1241    raeburn    77: use DateTime::Locale;
1.1220    raeburn    78: use Encode();
1.1091    foxr       79: use Text::Aspell;
1.1094    raeburn    80: use Authen::Captcha;
                     81: use Captcha::reCAPTCHA;
1.1234    raeburn    82: use JSON::DWIW;
1.1174    raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   85: use MIME::Lite;
                     86: use MIME::Types;
1.1292    raeburn    87: use File::Copy();
1.1300    raeburn    88: use File::Path();
1.1309    raeburn    89: use String::CRC32();
                     90: use Short::URL();
1.117     www        91: 
1.517     raeburn    92: # ---------------------------------------------- Designs
                     93: use vars qw(%defaultdesign);
                     94: 
1.22      www        95: my $readit;
                     96: 
1.517     raeburn    97: 
1.157     matthew    98: ##
                     99: ## Global Variables
                    100: ##
1.46      matthew   101: 
1.643     foxr      102: 
                    103: # ----------------------------------------------- SSI with retries:
                    104: #
                    105: 
                    106: =pod
                    107: 
1.648     raeburn   108: =head1 Server Side include with retries:
1.643     foxr      109: 
                    110: =over 4
                    111: 
1.648     raeburn   112: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      113: 
                    114: Performs an ssi with some number of retries.  Retries continue either
                    115: until the result is ok or until the retry count supplied by the
                    116: caller is exhausted.  
                    117: 
                    118: Inputs:
1.648     raeburn   119: 
                    120: =over 4
                    121: 
1.643     foxr      122: resource   - Identifies the resource to insert.
1.648     raeburn   123: 
1.643     foxr      124: retries    - Count of the number of retries allowed.
1.648     raeburn   125: 
1.643     foxr      126: form       - Hash that identifies the rendering options.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: Returns:
                    131: 
                    132: =over 4
                    133: 
1.643     foxr      134: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   135: 
1.643     foxr      136: response   - The response from the last attempt (which may or may not have been successful.
                    137: 
1.648     raeburn   138: =back
                    139: 
                    140: =back
                    141: 
1.643     foxr      142: =cut
                    143: 
                    144: sub ssi_with_retries {
                    145:     my ($resource, $retries, %form) = @_;
                    146: 
                    147: 
                    148:     my $ok = 0;			# True if we got a good response.
                    149:     my $content;
                    150:     my $response;
                    151: 
                    152:     # Try to get the ssi done. within the retries count:
                    153: 
                    154:     do {
                    155: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    156: 	$ok      = $response->is_success;
1.650     www       157:         if (!$ok) {
                    158:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    159:         }
1.643     foxr      160: 	$retries--;
                    161:     } while (!$ok && ($retries > 0));
                    162: 
                    163:     if (!$ok) {
                    164: 	$content = '';		# On error return an empty content.
                    165:     }
                    166:     return ($content, $response);
                    167: 
                    168: }
                    169: 
                    170: 
                    171: 
1.20      www       172: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  173: my %language;
1.124     www       174: my %supported_language;
1.1088    foxr      175: my %supported_codes;
1.1048    foxr      176: my %latex_language;		# For choosing hyphenation in <transl..>
                    177: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  178: my %cprtag;
1.192     taceyjo1  179: my %scprtag;
1.351     www       180: my %fe; my %fd; my %fm;
1.41      ng        181: my %category_extensions;
1.12      harris41  182: 
1.46      matthew   183: # ---------------------------------------------- Thesaurus variables
1.144     matthew   184: #
                    185: # %Keywords:
                    186: #      A hash used by &keyword to determine if a word is considered a keyword.
                    187: # $thesaurus_db_file 
                    188: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   189: 
                    190: my %Keywords;
                    191: my $thesaurus_db_file;
                    192: 
1.144     matthew   193: #
                    194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    195: # thesaurus.tab, and filecategories.tab.
                    196: #
1.18      www       197: BEGIN {
1.46      matthew   198:     # Variable initialization
                    199:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    200:     #
1.22      www       201:     unless ($readit) {
1.12      harris41  202: # ------------------------------------------------------------------- languages
                    203:     {
1.158     raeburn   204:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    205:                                    '/language.tab';
1.1317    raeburn   206:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  207:             while (my $line = <$fh>) {
                    208:                 next if ($line=~/^\#/);
                    209:                 chomp($line);
1.1088    foxr      210:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   211:                 $language{$key}=$val.' - '.$enc;
                    212:                 if ($sup) {
                    213:                     $supported_language{$key}=$sup;
1.1088    foxr      214: 		    $supported_codes{$key}   = $code;
1.158     raeburn   215:                 }
1.1048    foxr      216: 		if ($latex) {
                    217: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      218: 		    $latex_language{$code} = $latex;
1.1048    foxr      219: 		}
1.158     raeburn   220:             }
                    221:             close($fh);
                    222:         }
1.12      harris41  223:     }
                    224: # ------------------------------------------------------------------ copyrights
                    225:     {
1.158     raeburn   226:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    227:                                   '/copyright.tab';
1.1317    raeburn   228:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  229:             while (my $line = <$fh>) {
                    230:                 next if ($line=~/^\#/);
                    231:                 chomp($line);
                    232:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   233:                 $cprtag{$key}=$val;
                    234:             }
                    235:             close($fh);
                    236:         }
1.12      harris41  237:     }
1.351     www       238: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  239:     {
                    240:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    241:                                   '/source_copyright.tab';
1.1317    raeburn   242:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  243:             while (my $line = <$fh>) {
                    244:                 next if ($line =~ /^\#/);
                    245:                 chomp($line);
                    246:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  247:                 $scprtag{$key}=$val;
                    248:             }
                    249:             close($fh);
                    250:         }
                    251:     }
1.63      www       252: 
1.517     raeburn   253: # -------------------------------------------------------------- default domain designs
1.63      www       254:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   255:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   256:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   257:         while (my $line = <$fh>) {
                    258:             next if ($line =~ /^\#/);
                    259:             chomp($line);
                    260:             my ($key,$val)=(split(/\=/,$line));
                    261:             if ($val) { $defaultdesign{$key}=$val; }
                    262:         }
                    263:         close($fh);
1.63      www       264:     }
                    265: 
1.15      harris41  266: # ------------------------------------------------------------- file categories
                    267:     {
1.158     raeburn   268:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                                   '/filecategories.tab';
1.1317    raeburn   270:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  271: 	    while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   275:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   276:             }
                    277:             close($fh);
                    278:         }
                    279: 
1.15      harris41  280:     }
1.12      harris41  281: # ------------------------------------------------------------------ file types
                    282:     {
1.158     raeburn   283:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    284:                '/filetypes.tab';
1.1317    raeburn   285:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  286:             while (my $line = <$fh>) {
                    287: 		next if ($line =~ /^\#/);
                    288: 		chomp($line);
                    289:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   290:                 if ($descr ne '') {
                    291:                     $fe{$ending}=lc($emb);
                    292:                     $fd{$ending}=$descr;
1.351     www       293:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   294:                 }
                    295:             }
                    296:             close($fh);
                    297:         }
1.12      harris41  298:     }
1.22      www       299:     &Apache::lonnet::logthis(
1.705     tempelho  300:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       301:     $readit=1;
1.46      matthew   302:     }  # end of unless($readit) 
1.32      matthew   303:     
                    304: }
1.112     bowersj2  305: 
1.42      matthew   306: ###############################################################
                    307: ##           HTML and Javascript Helper Functions            ##
                    308: ###############################################################
                    309: 
                    310: =pod 
                    311: 
1.112     bowersj2  312: =head1 HTML and Javascript Functions
1.42      matthew   313: 
1.112     bowersj2  314: =over 4
                    315: 
1.648     raeburn   316: =item * &browser_and_searcher_javascript()
1.112     bowersj2  317: 
                    318: X<browsing, javascript>X<searching, javascript>Returns a string
                    319: containing javascript with two functions, C<openbrowser> and
                    320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    321: tags.
1.42      matthew   322: 
1.648     raeburn   323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   324: 
                    325: inputs: formname, elementname, only, omit
                    326: 
                    327: formname and elementname indicate the name of the html form and name of
                    328: the element that the results of the browsing selection are to be placed in. 
                    329: 
                    330: Specifying 'only' will restrict the browser to displaying only files
1.185     www       331: with the given extension.  Can be a comma separated list.
1.42      matthew   332: 
                    333: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       334: with the given extension.  Can be a comma separated list.
1.42      matthew   335: 
1.648     raeburn   336: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   337: 
                    338: Inputs: formname, elementname
                    339: 
                    340: formname and elementname specify the name of the html form and the name
                    341: of the element the selection from the search results will be placed in.
1.542     raeburn   342: 
1.42      matthew   343: =cut
                    344: 
                    345: sub browser_and_searcher_javascript {
1.199     albertel  346:     my ($mode)=@_;
                    347:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  348:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   349:     return <<END;
1.219     albertel  350: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   351:     var editbrowser = null;
1.135     albertel  352:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       353:         var url = '$resurl/?';
1.42      matthew   354:         if (editbrowser == null) {
                    355:             url += 'launch=1&';
                    356:         }
                    357:         url += 'catalogmode=interactive&';
1.199     albertel  358:         url += 'mode=$mode&';
1.611     albertel  359:         url += 'inhibitmenu=yes&';
1.42      matthew   360:         url += 'form=' + formname + '&';
                    361:         if (only != null) {
                    362:             url += 'only=' + only + '&';
1.217     albertel  363:         } else {
                    364:             url += 'only=&';
                    365: 	}
1.42      matthew   366:         if (omit != null) {
                    367:             url += 'omit=' + omit + '&';
1.217     albertel  368:         } else {
                    369:             url += 'omit=&';
                    370: 	}
1.135     albertel  371:         if (titleelement != null) {
                    372:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  373:         } else {
                    374: 	    url += 'titleelement=&';
                    375: 	}
1.42      matthew   376:         url += 'element=' + elementname + '';
                    377:         var title = 'Browser';
1.435     albertel  378:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   379:         options += ',width=700,height=600';
                    380:         editbrowser = open(url,title,options,'1');
                    381:         editbrowser.focus();
                    382:     }
                    383:     var editsearcher;
1.135     albertel  384:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   385:         var url = '/adm/searchcat?';
                    386:         if (editsearcher == null) {
                    387:             url += 'launch=1&';
                    388:         }
                    389:         url += 'catalogmode=interactive&';
1.199     albertel  390:         url += 'mode=$mode&';
1.42      matthew   391:         url += 'form=' + formname + '&';
1.135     albertel  392:         if (titleelement != null) {
                    393:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  394:         } else {
                    395: 	    url += 'titleelement=&';
                    396: 	}
1.42      matthew   397:         url += 'element=' + elementname + '';
                    398:         var title = 'Search';
1.435     albertel  399:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   400:         options += ',width=700,height=600';
                    401:         editsearcher = open(url,title,options,'1');
                    402:         editsearcher.focus();
                    403:     }
1.219     albertel  404: // END LON-CAPA Internal -->
1.42      matthew   405: END
1.170     www       406: }
                    407: 
                    408: sub lastresurl {
1.258     albertel  409:     if ($env{'environment.lastresurl'}) {
                    410: 	return $env{'environment.lastresurl'}
1.170     www       411:     } else {
                    412: 	return '/res';
                    413:     }
                    414: }
                    415: 
                    416: sub storeresurl {
                    417:     my $resurl=&Apache::lonnet::clutter(shift);
                    418:     unless ($resurl=~/^\/res/) { return 0; }
                    419:     $resurl=~s/\/$//;
                    420:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   421:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       422:     return 1;
1.42      matthew   423: }
                    424: 
1.74      www       425: sub studentbrowser_javascript {
1.111     www       426:    unless (
1.258     albertel  427:             (($env{'request.course.id'}) && 
1.302     albertel  428:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    429: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    430: 					  '/'.$env{'request.course.sec'})
                    431: 	      ))
1.258     albertel  432:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       433:           ) { return ''; }  
1.74      www       434:    return (<<'ENDSTDBRW');
1.776     bisitz    435: <script type="text/javascript" language="Javascript">
1.824     bisitz    436: // <![CDATA[
1.74      www       437:     var stdeditbrowser;
1.1337    raeburn   438:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       439:         var url = '/adm/pickstudent?';
                    440:         var filter;
1.558     albertel  441: 	if (!ignorefilter) {
                    442: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    443: 	}
1.74      www       444:         if (filter != null) {
                    445:            if (filter != '') {
                    446:                url += 'filter='+filter+'&';
                    447: 	   }
                    448:         }
                    449:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       450:                                     '&udomelement='+udom+
                    451:                                     '&clicker='+clicker;
1.111     www       452: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   453:         if (courseadv == 'condition') {
                    454:             if (document.getElementById('courseadv')) {
                    455:                 courseadv = document.getElementById('courseadv').value;
                    456:             }
                    457:         }
                    458:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       459:         var title = 'Student_Browser';
1.74      www       460:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    461:         options += ',width=700,height=600';
                    462:         stdeditbrowser = open(url,title,options,'1');
                    463:         stdeditbrowser.focus();
                    464:     }
1.824     bisitz    465: // ]]>
1.74      www       466: </script>
                    467: ENDSTDBRW
                    468: }
1.42      matthew   469: 
1.1003    www       470: sub resourcebrowser_javascript {
                    471:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       472:    return (<<'ENDRESBRW');
1.1003    www       473: <script type="text/javascript" language="Javascript">
                    474: // <![CDATA[
                    475:     var reseditbrowser;
1.1004    www       476:     function openresbrowser(formname,reslink) {
1.1005    www       477:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       478:         var title = 'Resource_Browser';
                    479:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       480:         options += ',width=700,height=500';
1.1004    www       481:         reseditbrowser = open(url,title,options,'1');
                    482:         reseditbrowser.focus();
1.1003    www       483:     }
                    484: // ]]>
                    485: </script>
1.1004    www       486: ENDRESBRW
1.1003    www       487: }
                    488: 
1.74      www       489: sub selectstudent_link {
1.1337    raeburn   490:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       491:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    492:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    493:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  494:    if ($env{'request.course.id'}) {  
1.302     albertel  495:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    496: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    497: 					'/'.$env{'request.course.sec'})) {
1.111     www       498: 	   return '';
                    499:        }
1.999     www       500:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   501:        if ($courseadv eq 'only') {
                    502:            $callargs .= ",'',1,'$courseadv'";
                    503:        } elsif ($courseadv eq 'none') {
                    504:            $callargs .= ",'','','$courseadv'";
                    505:        } elsif ($courseadv eq 'condition') {
                    506:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   507:        }
                    508:        return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    510:               &mt('Select User').'</a></span>';
1.74      www       511:    }
1.258     albertel  512:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       513:        $callargs .= ",'',1"; 
1.793     raeburn   514:        return '<span class="LC_nobreak">'.
                    515:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    516:               &mt('Select User').'</a></span>';
1.111     www       517:    }
                    518:    return '';
1.91      www       519: }
                    520: 
1.1004    www       521: sub selectresource_link {
                    522:    my ($form,$reslink,$arg)=@_;
                    523:    
                    524:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    525:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    526:    unless ($env{'request.course.id'}) { return $arg; }
                    527:    return '<span class="LC_nobreak">'.
                    528:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    529:               $arg.'</a></span>';
                    530: }
                    531: 
                    532: 
                    533: 
1.653     raeburn   534: sub authorbrowser_javascript {
                    535:     return <<"ENDAUTHORBRW";
1.776     bisitz    536: <script type="text/javascript" language="JavaScript">
1.824     bisitz    537: // <![CDATA[
1.653     raeburn   538: var stdeditbrowser;
                    539: 
                    540: function openauthorbrowser(formname,udom) {
                    541:     var url = '/adm/pickauthor?';
                    542:     url += 'form='+formname+'&roledom='+udom;
                    543:     var title = 'Author_Browser';
                    544:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    545:     options += ',width=700,height=600';
                    546:     stdeditbrowser = open(url,title,options,'1');
                    547:     stdeditbrowser.focus();
                    548: }
                    549: 
1.824     bisitz    550: // ]]>
1.653     raeburn   551: </script>
                    552: ENDAUTHORBRW
                    553: }
                    554: 
1.91      www       555: sub coursebrowser_javascript {
1.1116    raeburn   556:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   557:         $credits_element,$instcode) = @_;
1.932     raeburn   558:     my $wintitle = 'Course_Browser';
1.931     raeburn   559:     if ($crstype eq 'Community') {
1.932     raeburn   560:         $wintitle = 'Community_Browser';
1.909     raeburn   561:     }
1.876     raeburn   562:     my $id_functions = &javascript_index_functions();
                    563:     my $output = '
1.776     bisitz    564: <script type="text/javascript" language="JavaScript">
1.824     bisitz    565: // <![CDATA[
1.468     raeburn   566:     var stdeditbrowser;'."\n";
1.876     raeburn   567: 
                    568:     $output .= <<"ENDSTDBRW";
1.909     raeburn   569:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       570:         var url = '/adm/pickcourse?';
1.895     raeburn   571:         var formid = getFormIdByName(formname);
1.876     raeburn   572:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  573:         if (domainfilter != null) {
                    574:            if (domainfilter != '') {
                    575:                url += 'domainfilter='+domainfilter+'&';
                    576: 	   }
                    577:         }
1.91      www       578:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  579: 	                            '&cdomelement='+udom+
                    580:                                     '&cnameelement='+desc;
1.468     raeburn   581:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   582:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   583:                 url += '&roleelement='+extra_element;
                    584:                 if (domainfilter == null || domainfilter == '') {
                    585:                     url += '&domainfilter='+extra_element;
                    586:                 }
1.234     raeburn   587:             }
1.468     raeburn   588:             else {
                    589:                 if (formname == 'portform') {
                    590:                     url += '&setroles='+extra_element;
1.800     raeburn   591:                 } else {
                    592:                     if (formname == 'rules') {
                    593:                         url += '&fixeddom='+extra_element; 
                    594:                     }
1.468     raeburn   595:                 }
                    596:             }     
1.230     raeburn   597:         }
1.909     raeburn   598:         if (type != null && type != '') {
                    599:             url += '&type='+type;
                    600:         }
                    601:         if (type_elem != null && type_elem != '') {
                    602:             url += '&typeelement='+type_elem;
                    603:         }
1.872     raeburn   604:         if (formname == 'ccrs') {
                    605:             var ownername = document.forms[formid].ccuname.value;
                    606:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   607:             url += '&cloner='+ownername+':'+ownerdom;
                    608:             if (type == 'Course') {
                    609:                 url += '&crscode='+document.forms[formid].crscode.value;
                    610:             }
1.1221    raeburn   611:         }
                    612:         if (formname == 'requestcrs') {
                    613:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   614:         }
1.293     raeburn   615:         if (multflag !=null && multflag != '') {
                    616:             url += '&multiple='+multflag;
                    617:         }
1.909     raeburn   618:         var title = '$wintitle';
1.91      www       619:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    620:         options += ',width=700,height=600';
                    621:         stdeditbrowser = open(url,title,options,'1');
                    622:         stdeditbrowser.focus();
                    623:     }
1.876     raeburn   624: $id_functions
                    625: ENDSTDBRW
1.1116    raeburn   626:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    627:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    628:                                       $credits_element);
1.876     raeburn   629:     }
                    630:     $output .= '
                    631: // ]]>
                    632: </script>';
                    633:     return $output;
                    634: }
                    635: 
                    636: sub javascript_index_functions {
                    637:     return <<"ENDJS";
                    638: 
                    639: function getFormIdByName(formname) {
                    640:     for (var i=0;i<document.forms.length;i++) {
                    641:         if (document.forms[i].name == formname) {
                    642:             return i;
                    643:         }
                    644:     }
                    645:     return -1;
                    646: }
                    647: 
                    648: function getIndexByName(formid,item) {
                    649:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    650:         if (document.forms[formid].elements[i].name == item) {
                    651:             return i;
                    652:         }
                    653:     }
                    654:     return -1;
                    655: }
1.468     raeburn   656: 
1.876     raeburn   657: function getDomainFromSelectbox(formname,udom) {
                    658:     var userdom;
                    659:     var formid = getFormIdByName(formname);
                    660:     if (formid > -1) {
                    661:         var domid = getIndexByName(formid,udom);
                    662:         if (domid > -1) {
                    663:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    664:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    665:             }
                    666:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    667:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   668:             }
                    669:         }
                    670:     }
1.876     raeburn   671:     return userdom;
                    672: }
                    673: 
                    674: ENDJS
1.468     raeburn   675: 
1.876     raeburn   676: }
                    677: 
1.1017    raeburn   678: sub javascript_array_indexof {
1.1018    raeburn   679:     return <<ENDJS;
1.1017    raeburn   680: <script type="text/javascript" language="JavaScript">
                    681: // <![CDATA[
                    682: 
                    683: if (!Array.prototype.indexOf) {
                    684:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    685:         "use strict";
                    686:         if (this === void 0 || this === null) {
                    687:             throw new TypeError();
                    688:         }
                    689:         var t = Object(this);
                    690:         var len = t.length >>> 0;
                    691:         if (len === 0) {
                    692:             return -1;
                    693:         }
                    694:         var n = 0;
                    695:         if (arguments.length > 0) {
                    696:             n = Number(arguments[1]);
1.1088    foxr      697:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   698:                 n = 0;
                    699:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    700:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    701:             }
                    702:         }
                    703:         if (n >= len) {
                    704:             return -1;
                    705:         }
                    706:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    707:         for (; k < len; k++) {
                    708:             if (k in t && t[k] === searchElement) {
                    709:                 return k;
                    710:             }
                    711:         }
                    712:         return -1;
                    713:     }
                    714: }
                    715: 
                    716: // ]]>
                    717: </script>
                    718: 
                    719: ENDJS
                    720: 
                    721: }
                    722: 
1.876     raeburn   723: sub userbrowser_javascript {
                    724:     my $id_functions = &javascript_index_functions();
                    725:     return <<"ENDUSERBRW";
                    726: 
1.888     raeburn   727: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   728:     var url = '/adm/pickuser?';
                    729:     var userdom = getDomainFromSelectbox(formname,udom);
                    730:     if (userdom != null) {
                    731:        if (userdom != '') {
                    732:            url += 'srchdom='+userdom+'&';
                    733:        }
                    734:     }
                    735:     url += 'form=' + formname + '&unameelement='+uname+
                    736:                                 '&udomelement='+udom+
                    737:                                 '&ulastelement='+ulast+
                    738:                                 '&ufirstelement='+ufirst+
                    739:                                 '&uemailelement='+uemail+
1.881     raeburn   740:                                 '&hideudomelement='+hideudom+
                    741:                                 '&coursedom='+crsdom;
1.888     raeburn   742:     if ((caller != null) && (caller != undefined)) {
                    743:         url += '&caller='+caller;
                    744:     }
1.876     raeburn   745:     var title = 'User_Browser';
                    746:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    747:     options += ',width=700,height=600';
                    748:     var stdeditbrowser = open(url,title,options,'1');
                    749:     stdeditbrowser.focus();
                    750: }
                    751: 
1.888     raeburn   752: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   753:     var formid = getFormIdByName(formname);
                    754:     if (formid > -1) {
1.888     raeburn   755:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   756:         var domid = getIndexByName(formid,udom);
                    757:         var hidedomid = getIndexByName(formid,origdom);
                    758:         if (hidedomid > -1) {
                    759:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   760:             var unameval = document.forms[formid].elements[unameid].value;
                    761:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    762:                 if (domid > -1) {
                    763:                     var slct = document.forms[formid].elements[domid];
                    764:                     if (slct.type == 'select-one') {
                    765:                         var i;
                    766:                         for (i=0;i<slct.length;i++) {
                    767:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    768:                         }
                    769:                     }
                    770:                     if (slct.type == 'hidden') {
                    771:                         slct.value = fixeddom;
1.876     raeburn   772:                     }
                    773:                 }
1.468     raeburn   774:             }
                    775:         }
                    776:     }
1.876     raeburn   777:     return;
                    778: }
                    779: 
                    780: $id_functions
                    781: ENDUSERBRW
1.468     raeburn   782: }
                    783: 
                    784: sub setsec_javascript {
1.1116    raeburn   785:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   786:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    787:         $communityrolestr);
                    788:     if ($role_element ne '') {
                    789:         my @allroles = ('st','ta','ep','in','ad');
                    790:         foreach my $crstype ('Course','Community') {
                    791:             if ($crstype eq 'Community') {
                    792:                 foreach my $role (@allroles) {
                    793:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    794:                 }
                    795:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    796:             } else {
                    797:                 foreach my $role (@allroles) {
                    798:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    799:                 }
                    800:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    801:             }
                    802:         }
                    803:         $rolestr = '"'.join('","',@allroles).'"';
                    804:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    805:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    806:     }
1.468     raeburn   807:     my $setsections = qq|
                    808: function setSect(sectionlist) {
1.629     raeburn   809:     var sectionsArray = new Array();
                    810:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    811:         sectionsArray = sectionlist.split(",");
                    812:     }
1.468     raeburn   813:     var numSections = sectionsArray.length;
                    814:     document.$formname.$sec_element.length = 0;
                    815:     if (numSections == 0) {
                    816:         document.$formname.$sec_element.multiple=false;
                    817:         document.$formname.$sec_element.size=1;
                    818:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    819:     } else {
                    820:         if (numSections == 1) {
                    821:             document.$formname.$sec_element.multiple=false;
                    822:             document.$formname.$sec_element.size=1;
                    823:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    824:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    825:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    826:         } else {
                    827:             for (var i=0; i<numSections; i++) {
                    828:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    829:             }
                    830:             document.$formname.$sec_element.multiple=true
                    831:             if (numSections < 3) {
                    832:                 document.$formname.$sec_element.size=numSections;
                    833:             } else {
                    834:                 document.$formname.$sec_element.size=3;
                    835:             }
                    836:             document.$formname.$sec_element.options[0].selected = false
                    837:         }
                    838:     }
1.91      www       839: }
1.905     raeburn   840: 
                    841: function setRole(crstype) {
1.468     raeburn   842: |;
1.905     raeburn   843:     if ($role_element eq '') {
                    844:         $setsections .= '    return;
                    845: }
                    846: ';
                    847:     } else {
                    848:         $setsections .= qq|
                    849:     var elementLength = document.$formname.$role_element.length;
                    850:     var allroles = Array($rolestr);
                    851:     var courserolenames = Array($courserolestr);
                    852:     var communityrolenames = Array($communityrolestr);
                    853:     if (elementLength != undefined) {
                    854:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    855:             if (crstype == 'Course') {
                    856:                 return;
                    857:             } else {
                    858:                 allroles[5] = 'co';
                    859:                 for (var i=0; i<6; i++) {
                    860:                     document.$formname.$role_element.options[i].value = allroles[i];
                    861:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    862:                 }
                    863:             }
                    864:         } else {
                    865:             if (crstype == 'Community') {
                    866:                 return;
                    867:             } else {
                    868:                 allroles[5] = 'cc';
                    869:                 for (var i=0; i<6; i++) {
                    870:                     document.$formname.$role_element.options[i].value = allroles[i];
                    871:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    872:                 }
                    873:             }
                    874:         }
                    875:     }
                    876:     return;
                    877: }
                    878: |;
                    879:     }
1.1116    raeburn   880:     if ($credits_element) {
                    881:         $setsections .= qq|
                    882: function setCredits(defaultcredits) {
                    883:     document.$formname.$credits_element.value = defaultcredits;
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.468     raeburn   888:     return $setsections;
                    889: }
                    890: 
1.91      www       891: sub selectcourse_link {
1.909     raeburn   892:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    893:        $typeelement) = @_;
                    894:    my $type = $selecttype;
1.871     raeburn   895:    my $linktext = &mt('Select Course');
                    896:    if ($selecttype eq 'Community') {
1.909     raeburn   897:        $linktext = &mt('Select Community');
1.1239    raeburn   898:    } elsif ($selecttype eq 'Placement') {
                    899:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   900:    } elsif ($selecttype eq 'Course/Community') {
                    901:        $linktext = &mt('Select Course/Community');
1.909     raeburn   902:        $type = '';
1.1019    raeburn   903:    } elsif ($selecttype eq 'Select') {
                    904:        $linktext = &mt('Select');
                    905:        $type = '';
1.871     raeburn   906:    }
1.787     bisitz    907:    return '<span class="LC_nobreak">'
                    908:          ."<a href='"
                    909:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    910:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   911:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   912:          ."'>".$linktext.'</a>'
1.787     bisitz    913:          .'</span>';
1.74      www       914: }
1.42      matthew   915: 
1.653     raeburn   916: sub selectauthor_link {
                    917:    my ($form,$udom)=@_;
                    918:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    919:           &mt('Select Author').'</a>';
                    920: }
                    921: 
1.876     raeburn   922: sub selectuser_link {
1.881     raeburn   923:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   924:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   925:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   926:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   927:            ');">'.$linktext.'</a>';
1.876     raeburn   928: }
                    929: 
1.273     raeburn   930: sub check_uncheck_jscript {
                    931:     my $jscript = <<"ENDSCRT";
                    932: function checkAll(field) {
                    933:     if (field.length > 0) {
                    934:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   935:             if (!field[i].disabled) { 
                    936:                 field[i].checked = true;
                    937:             }
1.273     raeburn   938:         }
                    939:     } else {
1.1093    raeburn   940:         if (!field.disabled) { 
                    941:             field.checked = true;
                    942:         }
1.273     raeburn   943:     }
                    944: }
                    945:  
                    946: function uncheckAll(field) {
                    947:     if (field.length > 0) {
                    948:         for (i = 0; i < field.length; i++) {
                    949:             field[i].checked = false ;
1.543     albertel  950:         }
                    951:     } else {
1.273     raeburn   952:         field.checked = false ;
                    953:     }
                    954: }
                    955: ENDSCRT
                    956:     return $jscript;
                    957: }
                    958: 
1.656     www       959: sub select_timezone {
1.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.1381  ! raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
1.1381  ! raeburn  1284: $links_target will optionally be set to a target (_top, _parent or _self).
        !          1285: 
1.44      bowersj2 1286: =cut
                   1287: 
                   1288: sub help_open_topic {
1.1381  ! raeburn  1289:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1290:     $text = "" if (not defined $text);
1.44      bowersj2 1291:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1292:     $width = 500 if (not defined $width);
1.44      bowersj2 1293:     $height = 400 if (not defined $height);
                   1294:     my $filename = $topic;
                   1295:     $filename =~ s/ /_/g;
                   1296: 
1.48      bowersj2 1297:     my $template = "";
                   1298:     my $link;
1.572     banghart 1299:     
1.159     www      1300:     $topic=~s/\W/\_/g;
1.44      bowersj2 1301: 
1.572     banghart 1302:     if (!$stayOnPage) {
1.1033    www      1303: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1304:     } elsif ($stayOnPage eq 'popup') {
                   1305:         $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 1306:     } else {
1.48      bowersj2 1307: 	$link = "/adm/help/${filename}.hlp";
                   1308:     }
                   1309: 
                   1310:     # Add the text
1.1314    raeburn  1311:     my $target = ' target="_top"';
1.1381  ! raeburn  1312:     if ($links_target) {
        !          1313:         $target = ' target="'.$links_target.'"';
        !          1314:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
        !          1315:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
        !          1316:         $target = '';
1.1378    raeburn  1317:     }
1.1380    raeburn  1318:     if ($text ne "") {
1.763     bisitz   1319: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1320:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1321:                   .$text.'</a>';
1.48      bowersj2 1322:     }
                   1323: 
1.763     bisitz   1324:     # (Always) Add the graphic
1.179     matthew  1325:     my $title = &mt('Online Help');
1.667     raeburn  1326:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1327:     if ($imgid ne '') {
                   1328:         $imgid = ' id="'.$imgid.'"';
                   1329:     }
1.1314    raeburn  1330:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1331:               .'<img src="'.$helpicon.'" border="0"'
                   1332:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1333:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1334:               .' /></a>';
                   1335:     if ($text ne "") {	
                   1336:         $template.='</span>';
                   1337:     }
1.44      bowersj2 1338:     return $template;
                   1339: 
1.106     bowersj2 1340: }
                   1341: 
                   1342: # This is a quicky function for Latex cheatsheet editing, since it 
                   1343: # appears in at least four places
                   1344: sub helpLatexCheatsheet {
1.1037    www      1345:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1346:     my $out;
1.106     bowersj2 1347:     my $addOther = '';
1.732     raeburn  1348:     if ($topic) {
1.1037    www      1349: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1350:     }
                   1351:     $out = '<span>' # Start cheatsheet
                   1352: 	  .$addOther
                   1353:           .'<span>'
1.1037    www      1354: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1355: 	  .'</span> <span>'
1.1037    www      1356: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1357: 	  .'</span>';
1.732     raeburn  1358:     unless ($not_author) {
1.1186    kruse    1359:         $out .= '<span>'
                   1360:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1361:                .'</span> <span>'
                   1362:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1363: 	       .'</span>';
1.732     raeburn  1364:     }
1.763     bisitz   1365:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1366:     return $out;
1.172     www      1367: }
                   1368: 
1.430     albertel 1369: sub general_help {
                   1370:     my $helptopic='Student_Intro';
                   1371:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1372: 	$helptopic='Authoring_Intro';
1.907     raeburn  1373:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1374: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1375:     } elsif ($env{'request.role'}=~/^dc/) {
                   1376:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1377:     }
                   1378:     return $helptopic;
                   1379: }
                   1380: 
                   1381: sub update_help_link {
                   1382:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1383:     my $origurl = $ENV{'REQUEST_URI'};
                   1384:     $origurl=~s|^/~|/priv/|;
                   1385:     my $timestamp = time;
                   1386:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1387:         $$datum = &escape($$datum);
                   1388:     }
                   1389: 
                   1390:     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";
                   1391:     my $output .= <<"ENDOUTPUT";
                   1392: <script type="text/javascript">
1.824     bisitz   1393: // <![CDATA[
1.430     albertel 1394: banner_link = '$banner_link';
1.824     bisitz   1395: // ]]>
1.430     albertel 1396: </script>
                   1397: ENDOUTPUT
                   1398:     return $output;
                   1399: }
                   1400: 
                   1401: # now just updates the help link and generates a blue icon
1.193     raeburn  1402: sub help_open_menu {
1.1381  ! raeburn  1403:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1404: 	= @_;    
1.949     droeschl 1405:     $stayOnPage = 1;
1.430     albertel 1406:     my $output;
                   1407:     if ($component_help) {
                   1408: 	if (!$text) {
                   1409: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381  ! raeburn  1410: 				       $width,$height,'',$links_target);
1.430     albertel 1411: 	} else {
                   1412: 	    my $help_text;
                   1413: 	    $help_text=&unescape($topic);
                   1414: 	    $output='<table><tr><td>'.
                   1415: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381  ! raeburn  1416: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1417: 	}
                   1418:     }
                   1419:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1420:     return $output.$banner_link;
                   1421: }
                   1422: 
                   1423: sub top_nav_help {
1.1369    raeburn  1424:     my ($text,$linkattr) = @_;
1.436     albertel 1425:     $text = &mt($text);
1.949     droeschl 1426:     my $stay_on_page = 1;
                   1427: 
1.1168    raeburn  1428:     my ($link,$banner_link);
                   1429:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1430:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1431: 	                         : "javascript:helpMenu('open')";
                   1432:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1433:     }
1.201     raeburn  1434:     my $title = &mt('Get help');
1.1168    raeburn  1435:     if ($link) {
                   1436:         return <<"END";
1.436     albertel 1437: $banner_link
1.1369    raeburn  1438: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1439: END
1.1168    raeburn  1440:     } else {
                   1441:         return '&nbsp;'.$text.'&nbsp;';
                   1442:     }
1.436     albertel 1443: }
                   1444: 
                   1445: sub help_menu_js {
1.1154    raeburn  1446:     my ($httphost) = @_;
1.949     droeschl 1447:     my $stayOnPage = 1;
1.436     albertel 1448:     my $width = 620;
                   1449:     my $height = 600;
1.430     albertel 1450:     my $helptopic=&general_help();
1.1154    raeburn  1451:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1452:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1453:     my $start_page =
                   1454:         &Apache::loncommon::start_page('Help Menu', undef,
                   1455: 				       {'frameset'    => 1,
                   1456: 					'js_ready'    => 1,
1.1154    raeburn  1457:                                         'use_absolute' => $httphost,
1.331     albertel 1458: 					'add_entries' => {
1.1168    raeburn  1459: 					    'border' => '0', 
1.579     raeburn  1460: 					    'rows'   => "110,*",},});
1.331     albertel 1461:     my $end_page =
                   1462:         &Apache::loncommon::end_page({'frameset' => 1,
                   1463: 				      'js_ready' => 1,});
                   1464: 
1.436     albertel 1465:     my $template .= <<"ENDTEMPLATE";
                   1466: <script type="text/javascript">
1.877     bisitz   1467: // <![CDATA[
1.253     albertel 1468: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1469: var banner_link = '';
1.243     raeburn  1470: function helpMenu(target) {
                   1471:     var caller = this;
                   1472:     if (target == 'open') {
                   1473:         var newWindow = null;
                   1474:         try {
1.262     albertel 1475:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1476:         }
                   1477:         catch(error) {
                   1478:             writeHelp(caller);
                   1479:             return;
                   1480:         }
                   1481:         if (newWindow) {
                   1482:             caller = newWindow;
                   1483:         }
1.193     raeburn  1484:     }
1.243     raeburn  1485:     writeHelp(caller);
                   1486:     return;
                   1487: }
                   1488: function writeHelp(caller) {
1.1168    raeburn  1489:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1490:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1491:     caller.document.close();
                   1492:     caller.focus();
1.193     raeburn  1493: }
1.877     bisitz   1494: // END LON-CAPA Internal -->
1.253     albertel 1495: // ]]>
1.436     albertel 1496: </script>
1.193     raeburn  1497: ENDTEMPLATE
                   1498:     return $template;
                   1499: }
                   1500: 
1.172     www      1501: sub help_open_bug {
                   1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1503:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1504:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1505:     $text = "" if (not defined $text);
                   1506: 	$stayOnPage=1;
1.184     albertel 1507:     $width = 600 if (not defined $width);
                   1508:     $height = 600 if (not defined $height);
1.172     www      1509: 
                   1510:     $topic=~s/\W+/\+/g;
                   1511:     my $link='';
                   1512:     my $template='';
1.379     albertel 1513:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1514: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1515:     if (!$stayOnPage)
                   1516:     {
                   1517: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1518:     }
                   1519:     else
                   1520:     {
                   1521: 	$link = $url;
                   1522:     }
1.1314    raeburn  1523: 
                   1524:     my $target = ' target="_top"';
                   1525:     if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
                   1526:         $target = '';
                   1527:     }
1.1378    raeburn  1528:     if (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   1529:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   1530:     }
1.172     www      1531:     # Add the text
                   1532:     if ($text ne "")
                   1533:     {
                   1534: 	$template .= 
                   1535:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1314    raeburn  1536:   "<td bgcolor='#FF5555'><a".$target." href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1537:     }
                   1538: 
                   1539:     # Add the graphic
1.179     matthew  1540:     my $title = &mt('Report a Bug');
1.215     albertel 1541:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1542:     $template .= <<"ENDTEMPLATE";
1.1314    raeburn  1543:  <a$target href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1544: ENDTEMPLATE
                   1545:     if ($text ne '') { $template.='</td></tr></table>' };
                   1546:     return $template;
                   1547: 
                   1548: }
                   1549: 
                   1550: sub help_open_faq {
                   1551:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1552:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1553:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1554:     $text = "" if (not defined $text);
                   1555: 	$stayOnPage=1;
                   1556:     $width = 350 if (not defined $width);
                   1557:     $height = 400 if (not defined $height);
                   1558: 
                   1559:     $topic=~s/\W+/\+/g;
                   1560:     my $link='';
                   1561:     my $template='';
                   1562:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1563:     if (!$stayOnPage)
                   1564:     {
                   1565: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1566:     }
                   1567:     else
                   1568:     {
                   1569: 	$link = $url;
                   1570:     }
                   1571: 
                   1572:     # Add the text
                   1573:     if ($text ne "")
                   1574:     {
                   1575: 	$template .= 
1.173     www      1576:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1577:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1578:     }
                   1579: 
                   1580:     # Add the graphic
1.179     matthew  1581:     my $title = &mt('View the FAQ');
1.215     albertel 1582:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1583:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1584:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1585: ENDTEMPLATE
                   1586:     if ($text ne '') { $template.='</td></tr></table>' };
                   1587:     return $template;
                   1588: 
1.44      bowersj2 1589: }
1.37      matthew  1590: 
1.180     matthew  1591: ###############################################################
                   1592: ###############################################################
                   1593: 
1.45      matthew  1594: =pod
                   1595: 
1.648     raeburn  1596: =item * &change_content_javascript():
1.256     matthew  1597: 
                   1598: This and the next function allow you to create small sections of an
                   1599: otherwise static HTML page that you can update on the fly with
                   1600: Javascript, even in Netscape 4.
                   1601: 
                   1602: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1603: must be written to the HTML page once. It will prove the Javascript
                   1604: function "change(name, content)". Calling the change function with the
                   1605: name of the section 
                   1606: you want to update, matching the name passed to C<changable_area>, and
                   1607: the new content you want to put in there, will put the content into
                   1608: that area.
                   1609: 
                   1610: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1611: to contain room for the original contents. You need to "make space"
                   1612: for whatever changes you wish to make, and be B<sure> to check your
                   1613: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1614: it's adequate for updating a one-line status display, but little more.
                   1615: This script will set the space to 100% width, so you only need to
                   1616: worry about height in Netscape 4.
                   1617: 
                   1618: Modern browsers are much less limiting, and if you can commit to the
                   1619: user not using Netscape 4, this feature may be used freely with
                   1620: pretty much any HTML.
                   1621: 
                   1622: =cut
                   1623: 
                   1624: sub change_content_javascript {
                   1625:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1626:     if ($env{'browser.type'} eq 'netscape' &&
                   1627: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1628: 	return (<<NETSCAPE4);
                   1629: 	function change(name, content) {
                   1630: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1631: 	    doc.open();
                   1632: 	    doc.write(content);
                   1633: 	    doc.close();
                   1634: 	}
                   1635: NETSCAPE4
                   1636:     } else {
                   1637: 	# Otherwise, we need to use semi-standards-compliant code
                   1638: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1639: 	# is really scary, and every useful browser supports it
                   1640: 	return (<<DOMBASED);
                   1641: 	function change(name, content) {
                   1642: 	    element = document.getElementById(name);
                   1643: 	    element.innerHTML = content;
                   1644: 	}
                   1645: DOMBASED
                   1646:     }
                   1647: }
                   1648: 
                   1649: =pod
                   1650: 
1.648     raeburn  1651: =item * &changable_area($name,$origContent):
1.256     matthew  1652: 
                   1653: This provides a "changable area" that can be modified on the fly via
                   1654: the Javascript code provided in C<change_content_javascript>. $name is
                   1655: the name you will use to reference the area later; do not repeat the
                   1656: same name on a given HTML page more then once. $origContent is what
                   1657: the area will originally contain, which can be left blank.
                   1658: 
                   1659: =cut
                   1660: 
                   1661: sub changable_area {
                   1662:     my ($name, $origContent) = @_;
                   1663: 
1.258     albertel 1664:     if ($env{'browser.type'} eq 'netscape' &&
                   1665: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1666: 	# If this is netscape 4, we need to use the Layer tag
                   1667: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1668:     } else {
                   1669: 	return "<span id='$name'>$origContent</span>";
                   1670:     }
                   1671: }
                   1672: 
                   1673: =pod
                   1674: 
1.648     raeburn  1675: =item * &viewport_geometry_js 
1.590     raeburn  1676: 
                   1677: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1678: 
                   1679: =cut
                   1680: 
                   1681: 
                   1682: sub viewport_geometry_js { 
                   1683:     return <<"GEOMETRY";
                   1684: var Geometry = {};
                   1685: function init_geometry() {
                   1686:     if (Geometry.init) { return };
                   1687:     Geometry.init=1;
                   1688:     if (window.innerHeight) {
                   1689:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1690:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1691:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1692:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1693:     }
                   1694:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1695:         Geometry.getViewportHeight =
                   1696:             function() { return document.documentElement.clientHeight; };
                   1697:         Geometry.getViewportWidth =
                   1698:             function() { return document.documentElement.clientWidth; };
                   1699: 
                   1700:         Geometry.getHorizontalScroll =
                   1701:             function() { return document.documentElement.scrollLeft; };
                   1702:         Geometry.getVerticalScroll =
                   1703:             function() { return document.documentElement.scrollTop; };
                   1704:     }
                   1705:     else if (document.body.clientHeight) {
                   1706:         Geometry.getViewportHeight =
                   1707:             function() { return document.body.clientHeight; };
                   1708:         Geometry.getViewportWidth =
                   1709:             function() { return document.body.clientWidth; };
                   1710:         Geometry.getHorizontalScroll =
                   1711:             function() { return document.body.scrollLeft; };
                   1712:         Geometry.getVerticalScroll =
                   1713:             function() { return document.body.scrollTop; };
                   1714:     }
                   1715: }
                   1716: 
                   1717: GEOMETRY
                   1718: }
                   1719: 
                   1720: =pod
                   1721: 
1.648     raeburn  1722: =item * &viewport_size_js()
1.590     raeburn  1723: 
                   1724: 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. 
                   1725: 
                   1726: =cut
                   1727: 
                   1728: sub viewport_size_js {
                   1729:     my $geometry = &viewport_geometry_js();
                   1730:     return <<"DIMS";
                   1731: 
                   1732: $geometry
                   1733: 
                   1734: function getViewportDims(width,height) {
                   1735:     init_geometry();
                   1736:     width.value = Geometry.getViewportWidth();
                   1737:     height.value = Geometry.getViewportHeight();
                   1738:     return;
                   1739: }
                   1740: 
                   1741: DIMS
                   1742: }
                   1743: 
                   1744: =pod
                   1745: 
1.648     raeburn  1746: =item * &resize_textarea_js()
1.565     albertel 1747: 
                   1748: emits the needed javascript to resize a textarea to be as big as possible
                   1749: 
                   1750: creates a function resize_textrea that takes two IDs first should be
                   1751: the id of the element to resize, second should be the id of a div that
                   1752: surrounds everything that comes after the textarea, this routine needs
                   1753: to be attached to the <body> for the onload and onresize events.
                   1754: 
1.648     raeburn  1755: =back
1.565     albertel 1756: 
                   1757: =cut
                   1758: 
                   1759: sub resize_textarea_js {
1.590     raeburn  1760:     my $geometry = &viewport_geometry_js();
1.565     albertel 1761:     return <<"RESIZE";
                   1762:     <script type="text/javascript">
1.824     bisitz   1763: // <![CDATA[
1.590     raeburn  1764: $geometry
1.565     albertel 1765: 
1.588     albertel 1766: function getX(element) {
                   1767:     var x = 0;
                   1768:     while (element) {
                   1769: 	x += element.offsetLeft;
                   1770: 	element = element.offsetParent;
                   1771:     }
                   1772:     return x;
                   1773: }
                   1774: function getY(element) {
                   1775:     var y = 0;
                   1776:     while (element) {
                   1777: 	y += element.offsetTop;
                   1778: 	element = element.offsetParent;
                   1779:     }
                   1780:     return y;
                   1781: }
                   1782: 
                   1783: 
1.565     albertel 1784: function resize_textarea(textarea_id,bottom_id) {
                   1785:     init_geometry();
                   1786:     var textarea        = document.getElementById(textarea_id);
                   1787:     //alert(textarea);
                   1788: 
1.588     albertel 1789:     var textarea_top    = getY(textarea);
1.565     albertel 1790:     var textarea_height = textarea.offsetHeight;
                   1791:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1792:     var bottom_top      = getY(bottom);
1.565     albertel 1793:     var bottom_height   = bottom.offsetHeight;
                   1794:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1795:     var fudge           = 23;
1.565     albertel 1796:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1797:     if (new_height < 300) {
                   1798: 	new_height = 300;
                   1799:     }
                   1800:     textarea.style.height=new_height+'px';
                   1801: }
1.824     bisitz   1802: // ]]>
1.565     albertel 1803: </script>
                   1804: RESIZE
                   1805: 
                   1806: }
                   1807: 
1.1205    golterma 1808: sub colorfuleditor_js {
1.1248    raeburn  1809:     my $browse_or_search;
                   1810:     my $respath;
                   1811:     my ($cnum,$cdom) = &crsauthor_url();
                   1812:     if ($cnum) {
                   1813:         $respath = "/res/$cdom/$cnum/";
                   1814:         my %js_lt = &Apache::lonlocal::texthash(
                   1815:             sunm => 'Sub-directory name',
                   1816:             save => 'Save page to make this permanent',
                   1817:         );
                   1818:         &js_escape(\%js_lt);
                   1819:         $browse_or_search = <<"END";
                   1820: 
                   1821:     function toggleChooser(form,element,titleid,only,search) {
                   1822:         var disp = 'none';
                   1823:         if (document.getElementById('chooser_'+element)) {
                   1824:             var curr = document.getElementById('chooser_'+element).style.display;
                   1825:             if (curr == 'none') {
                   1826:                 disp='inline';
                   1827:                 if (form.elements['chooser_'+element].length) {
                   1828:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1829:                         form.elements['chooser_'+element][i].checked = false;
                   1830:                     }
                   1831:                 }
                   1832:                 toggleResImport(form,element);
                   1833:             }
                   1834:             document.getElementById('chooser_'+element).style.display = disp;
                   1835:         }
                   1836:     }
                   1837: 
                   1838:     function toggleCrsFile(form,element,numdirs) {
                   1839:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1840:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1841:             if (curr == 'none') {
                   1842:                 if (numdirs) {
                   1843:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1844:                     if (numdirs > 1) {
                   1845:                         window['select1'+element+'_changed']();
                   1846:                     }
                   1847:                 }
                   1848:             } 
                   1849:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1850:             
                   1851:         }
                   1852:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1853:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1854:             if (document.getElementById('uploadcrsres_'+element)) {
                   1855:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1856:             }
                   1857:         }
                   1858:         return;
                   1859:     }
                   1860: 
                   1861:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1862:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1863:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1864:         }
                   1865:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1866:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1867:             if (curr == 'none') {
                   1868:                 if (numcrsdirs) {
                   1869:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1870:                    form.elements['newsubdir_'+element][0].checked = true;
                   1871:                    toggleNewsubdir(form,element);
                   1872:                 }
                   1873:             }
                   1874:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1875:         }
                   1876:         return;
                   1877:     }
                   1878: 
                   1879:     function toggleResImport(form,element) {
                   1880:         var choices = new Array('crsres','upload');
                   1881:         for (var i=0; i<choices.length; i++) {
                   1882:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1883:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1884:             }
                   1885:         }
                   1886:     }
                   1887: 
                   1888:     function toggleNewsubdir(form,element) {
                   1889:         var newsub = form.elements['newsubdir_'+element];
                   1890:         if (newsub) {
                   1891:             if (newsub.length) {
                   1892:                 for (var j=0; j<newsub.length; j++) {
                   1893:                     if (newsub[j].checked) {
                   1894:                         if (document.getElementById('newsubdirname_'+element)) {
                   1895:                             if (newsub[j].value == '1') {
                   1896:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1897:                                 if (document.getElementById('newsubdir_'+element)) {
                   1898:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1899:                                 }
                   1900:                             } else {
                   1901:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1902:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1903:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1904:                             }
                   1905:                         }
                   1906:                         break; 
                   1907:                     }
                   1908:                 }
                   1909:             }
                   1910:         }
                   1911:     }
                   1912: 
                   1913:     function updateCrsFile(form,element) {
                   1914:         var directory = form.elements['coursepath_'+element];
                   1915:         var filename = form.elements['coursefile_'+element];
                   1916:         var path = directory.options[directory.selectedIndex].value;
                   1917:         var file = filename.options[filename.selectedIndex].value;
                   1918:         form.elements[element].value = '$respath';
                   1919:         if (path == '/') {
                   1920:             form.elements[element].value += file;
                   1921:         } else {
                   1922:             form.elements[element].value += path+'/'+file;
                   1923:         }
                   1924:         unClean();
                   1925:         if (document.getElementById('previewimg_'+element)) {
                   1926:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1927:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1928:         }
                   1929:         if (document.getElementById('showimg_'+element)) {
                   1930:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1931:         }
                   1932:         toggleChooser(form,element);
                   1933:         return;
                   1934:     }
                   1935: 
                   1936:     function uploadDone(suffix,name) {
                   1937:         if (name) {
                   1938: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1939:             unClean();
                   1940:             toggleChooser(document.forms["lonhomework"],suffix);
                   1941:         }
                   1942:     }
                   1943: 
                   1944: \$(document).ready(function(){
                   1945: 
                   1946:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1947:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1948:             var buttonId = this.id;
                   1949:             var suffix = buttonId.toString();
                   1950:             suffix = suffix.replace(/^crsupload_/,'');
                   1951:             event.preventDefault();
                   1952:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1953:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1954:             \$(this.form).submit();
                   1955:             document.lonhomework.target = '';
                   1956:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1957:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1958:             }
                   1959:             return false;
                   1960:         }
                   1961:     });
                   1962: });
                   1963: END
                   1964:     }
1.1205    golterma 1965:     return <<"COLORFULEDIT"
                   1966: <script type="text/javascript">
                   1967: // <![CDATA[>
                   1968:     function fold_box(curDepth, lastresource){
                   1969: 
                   1970:     // we need a list because there can be several blocks you need to fold in one tag
                   1971:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1972:     // but there is only one folding button per tag
                   1973:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1974: 
                   1975:         if(block.item(0).style.display == 'none'){
                   1976: 
                   1977:             foldbutton.value = '@{[&mt("Hide")]}';
                   1978:             for (i = 0; i < block.length; i++){
                   1979:                 block.item(i).style.display = '';
                   1980:             }
                   1981:         }else{
                   1982: 
                   1983:             foldbutton.value = '@{[&mt("Show")]}';
                   1984:             for (i = 0; i < block.length; i++){
                   1985:                 // block.item(i).style.visibility = 'collapse';
                   1986:                 block.item(i).style.display = 'none';
                   1987:             }
                   1988:         };
                   1989:         saveState(lastresource);
                   1990:     }
                   1991: 
                   1992:     function saveState (lastresource) {
                   1993: 
                   1994:         var tag_list = getTagList();
                   1995:         if(tag_list != null){
                   1996:             var timestamp = new Date().getTime();
                   1997:             var key = lastresource;
                   1998: 
                   1999:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2000:             // starting with timestamp
                   2001:             var value = timestamp+';';
                   2002: 
                   2003:             // building the list of key-value pairs
                   2004:             for(var i = 0; i < tag_list.length; i++){
                   2005:                 value += tag_list[i]+',';
                   2006:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2007:             }
                   2008: 
                   2009:             // only iterate whole storage if nothing to override
                   2010:             if(localStorage.getItem(key) == null){        
                   2011: 
                   2012:                 // prevent storage from growing large
                   2013:                 if(localStorage.length > 50){
                   2014:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2015:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2016:                     var oldest_key;
                   2017:                     
                   2018:                     for(var i = 1; i < localStorage.length; i++){
                   2019:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2020:                             oldest_key = localStorage.key(i);
                   2021:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2022:                         }
                   2023:                     }
                   2024:                     localStorage.removeItem(oldest_key);
                   2025:                 }
                   2026:             }
                   2027:             localStorage.setItem(key,value);
                   2028:         }
                   2029:     }
                   2030: 
                   2031:     // restore folding status of blocks (on page load)
                   2032:     function restoreState (lastresource) {
                   2033:         if(localStorage.getItem(lastresource) != null){
                   2034:             var key = lastresource;
                   2035:             var value = localStorage.getItem(key);
                   2036:             var regex_delTimestamp = /^\d+;/;
                   2037: 
                   2038:             value.replace(regex_delTimestamp, '');
                   2039: 
                   2040:             var valueArr = value.split(';');
                   2041:             var pairs;
                   2042:             var elements;
                   2043:             for (var i = 0; i < valueArr.length; i++){
                   2044:                 pairs = valueArr[i].split(',');
                   2045:                 elements = document.getElementsByName(pairs[0]);
                   2046: 
                   2047:                 for (var j = 0; j < elements.length; j++){  
                   2048:                     elements[j].style.display = pairs[1];
                   2049:                     if (pairs[1] == "none"){
                   2050:                         var regex_id = /([_\\d]+)\$/;
                   2051:                         regex_id.exec(pairs[0]);
                   2052:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2053:                     }
                   2054:                 }
                   2055:             }
                   2056:         }
                   2057:     }
                   2058: 
                   2059:     function getTagList () {
                   2060:         
                   2061:         var stringToSearch = document.lonhomework.innerHTML;
                   2062: 
                   2063:         var ret = new Array();
                   2064:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2065:         var tag_list = stringToSearch.match(regex_findBlock);
                   2066: 
                   2067:         if(tag_list != null){
                   2068:             for(var i = 0; i < tag_list.length; i++){            
                   2069:                 ret.push(tag_list[i].replace(/"/, ''));
                   2070:             }
                   2071:         }
                   2072:         return ret;
                   2073:     }
                   2074: 
                   2075:     function saveScrollPosition (resource) {
                   2076:         var tag_list = getTagList();
                   2077: 
                   2078:         // we dont always want to jump to the first block
                   2079:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2080:         if(\$(window).scrollTop() > 170){
                   2081:             if(tag_list != null){
                   2082:                 var result;
                   2083:                 for(var i = 0; i < tag_list.length; i++){
                   2084:                     if(isElementInViewport(tag_list[i])){
                   2085:                         result += tag_list[i]+';';
                   2086:                     }
                   2087:                 }
                   2088:                 sessionStorage.setItem('anchor_'+resource, result);
                   2089:             }
                   2090:         } else {
                   2091:             // we dont need to save zero, just delete the item to leave everything tidy
                   2092:             sessionStorage.removeItem('anchor_'+resource);
                   2093:         }
                   2094:     }
                   2095: 
                   2096:     function restoreScrollPosition(resource){
                   2097: 
                   2098:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2099:         if(elem != null){
                   2100:             var tag_list = elem.split(';');
                   2101:             var elem_list;
                   2102: 
                   2103:             for(var i = 0; i < tag_list.length; i++){
                   2104:                 elem_list = document.getElementsByName(tag_list[i]);
                   2105:                 
                   2106:                 if(elem_list.length > 0){
                   2107:                     elem = elem_list[0];
                   2108:                     break;
                   2109:                 }
                   2110:             }
                   2111:             elem.scrollIntoView();
                   2112:         }
                   2113:     }
                   2114: 
                   2115:     function isElementInViewport(el) {
                   2116: 
                   2117:         // change to last element instead of first
                   2118:         var elem = document.getElementsByName(el);
                   2119:         var rect = elem[0].getBoundingClientRect();
                   2120: 
                   2121:         return (
                   2122:             rect.top >= 0 &&
                   2123:             rect.left >= 0 &&
                   2124:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2125:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2126:         );
                   2127:     }
                   2128:     
                   2129:     function autosize(depth){
                   2130:         var cmInst = window['cm'+depth];
                   2131:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2132: 
                   2133:         // is fixed size, switching to dynamic
                   2134:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2135:             cmInst.setSize("","auto");
                   2136:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2137:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2138: 
                   2139:         // is dynamic size, switching to fixed
                   2140:         } else {
                   2141:             cmInst.setSize("","300px");
                   2142:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2143:             sessionStorage.removeItem("autosized_"+depth);
                   2144:         }
                   2145:     }
                   2146: 
1.1248    raeburn  2147: $browse_or_search
1.1205    golterma 2148: 
                   2149: // ]]>
                   2150: </script>
                   2151: COLORFULEDIT
                   2152: }
                   2153: 
                   2154: sub xmleditor_js {
                   2155:     return <<XMLEDIT
                   2156: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2157: <script type="text/javascript">
                   2158: // <![CDATA[>
                   2159: 
                   2160:     function saveScrollPosition (resource) {
                   2161: 
                   2162:         var scrollPos = \$(window).scrollTop();
                   2163:         sessionStorage.setItem(resource,scrollPos);
                   2164:     }
                   2165: 
                   2166:     function restoreScrollPosition(resource){
                   2167: 
                   2168:         var scrollPos = sessionStorage.getItem(resource);
                   2169:         \$(window).scrollTop(scrollPos);
                   2170:     }
                   2171: 
                   2172:     // unless internet explorer
                   2173:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2174: 
                   2175:         \$(document).ready(function() {
                   2176:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2177:         });
                   2178:     }
                   2179: 
                   2180:     // inserts text at cursor position into codemirror (xml editor only)
                   2181:     function insertText(text){
                   2182:         cm.focus();
                   2183:         var curPos = cm.getCursor();
                   2184:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2185:     }
                   2186: // ]]>
                   2187: </script>
                   2188: XMLEDIT
                   2189: }
                   2190: 
                   2191: sub insert_folding_button {
                   2192:     my $curDepth = $Apache::lonxml::curdepth;
                   2193:     my $lastresource = $env{'request.ambiguous'};
                   2194: 
                   2195:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2196:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2197: }
                   2198: 
1.1248    raeburn  2199: sub crsauthor_url {
                   2200:     my ($url) = @_;
                   2201:     if ($url eq '') {
                   2202:         $url = $ENV{'REQUEST_URI'};
                   2203:     }
                   2204:     my ($cnum,$cdom);
                   2205:     if ($env{'request.course.id'}) {
                   2206:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2207:         if ($audom ne '' && $auname ne '') {
                   2208:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2209:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2210:                 $cnum = $auname;
                   2211:                 $cdom = $audom;
                   2212:             }
                   2213:         }
                   2214:     }
                   2215:     return ($cnum,$cdom);
                   2216: }
                   2217: 
                   2218: sub import_crsauthor_form {
1.1265    raeburn  2219:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2220:     return (0) unless ($env{'request.course.id'});
                   2221:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2222:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2223:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2224:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2225:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2226:     my @ids=&Apache::lonnet::current_machine_ids();
                   2227:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2228:     
                   2229:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2230:         $is_home = 1;
                   2231:     }
                   2232:     $relpath = "/priv/$cdom/$cnum";
                   2233:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2234:     my %lt = &Apache::lonlocal::texthash (
                   2235:         fnam => 'Filename',
                   2236:         dire => 'Directory',
                   2237:     );
                   2238:     my $numdirs = scalar(keys(%files));
                   2239:     my (%possexts,$singledir,@singledirfiles);
                   2240:     if ($only) {
                   2241:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2242:     }
                   2243:     my (%nonemptydirs,$possdirs);
                   2244:     if ($numdirs > 1) {
                   2245:         my @order;
                   2246:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2247:             if (ref($files{$key}) eq 'HASH') {
                   2248:                 my $shown = $key;
                   2249:                 if ($key eq '') {
                   2250:                     $shown = '/';
                   2251:                 }
                   2252:                 my @ordered = ();
                   2253:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2254:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2255:                     if ($only) {
                   2256:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2257:                         unless ($possexts{lc($ext)}) {
                   2258:                             next;
                   2259:                         }
                   2260:                     }
                   2261:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2262:                     push(@ordered,$file);
                   2263:                 }
                   2264:                 if (@ordered) {
                   2265:                     push(@order,$key);
                   2266:                     $nonemptydirs{$key} = 1;
                   2267:                     $selimport_menus{$key}->{'text'} = $shown;
                   2268:                     $selimport_menus{$key}->{'default'} = '';
                   2269:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2270:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2271:                 }
                   2272:             }
                   2273:         }
                   2274:         $possdirs = scalar(keys(%nonemptydirs));
                   2275:         if ($possdirs > 1) {
                   2276:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2277:             $output = $lt{'dire'}.
                   2278:                       &linked_select_forms($form,'<br />'.
                   2279:                                            $lt{'fnam'},'',
                   2280:                                            $firstselectname,$secondselectname,
                   2281:                                            \%selimport_menus,\@order,
                   2282:                                            $onchangefirst,'',$suffix).'<br />';
                   2283:         } elsif ($possdirs == 1) {
                   2284:             $singledir = (keys(%nonemptydirs))[0];
                   2285:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2286:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2287:             }
                   2288:             delete($selimport_menus{$singledir});
                   2289:         }
                   2290:     } elsif ($numdirs == 1) {
                   2291:         $singledir = (keys(%files))[0];
                   2292:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2293:             if ($only) {
                   2294:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2295:                 unless ($possexts{lc($ext)}) {
                   2296:                     next;
                   2297:                 }
1.1315    raeburn  2298:             } else {
                   2299:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2300:             }
                   2301:             push(@singledirfiles,$file);
                   2302:         }
                   2303:         if (@singledirfiles) {
1.1315    raeburn  2304:             $possdirs = 1;
1.1248    raeburn  2305:         }
                   2306:     }
                   2307:     if (($possdirs == 1) && (@singledirfiles)) {
                   2308:         my $showdir = $singledir;
                   2309:         if ($singledir eq '') {
                   2310:             $showdir = '/';
                   2311:         }
                   2312:         $output = $lt{'dire'}.
                   2313:                   '<select name="'.$firstselectname.'">'.
                   2314:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2315:                   '</select><br />'.
                   2316:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2317:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2318:         foreach my $file (@singledirfiles) {
                   2319:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2320:         }
                   2321:         $output .= '</select><br />'."\n";
                   2322:     }
                   2323:     return ($possdirs,$output);
                   2324: }
                   2325: 
1.565     albertel 2326: =pod
                   2327: 
1.256     matthew  2328: =head1 Excel and CSV file utility routines
                   2329: 
                   2330: =cut
                   2331: 
                   2332: ###############################################################
                   2333: ###############################################################
                   2334: 
                   2335: =pod
                   2336: 
1.1162    raeburn  2337: =over 4
                   2338: 
1.648     raeburn  2339: =item * &csv_translate($text) 
1.37      matthew  2340: 
1.185     www      2341: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2342: format.
                   2343: 
                   2344: =cut
                   2345: 
1.180     matthew  2346: ###############################################################
                   2347: ###############################################################
1.37      matthew  2348: sub csv_translate {
                   2349:     my $text = shift;
                   2350:     $text =~ s/\"/\"\"/g;
1.209     albertel 2351:     $text =~ s/\n/ /g;
1.37      matthew  2352:     return $text;
                   2353: }
1.180     matthew  2354: 
                   2355: ###############################################################
                   2356: ###############################################################
                   2357: 
                   2358: =pod
                   2359: 
1.648     raeburn  2360: =item * &define_excel_formats()
1.180     matthew  2361: 
                   2362: Define some commonly used Excel cell formats.
                   2363: 
                   2364: Currently supported formats:
                   2365: 
                   2366: =over 4
                   2367: 
                   2368: =item header
                   2369: 
                   2370: =item bold
                   2371: 
                   2372: =item h1
                   2373: 
                   2374: =item h2
                   2375: 
                   2376: =item h3
                   2377: 
1.256     matthew  2378: =item h4
                   2379: 
                   2380: =item i
                   2381: 
1.180     matthew  2382: =item date
                   2383: 
                   2384: =back
                   2385: 
                   2386: Inputs: $workbook
                   2387: 
                   2388: Returns: $format, a hash reference.
                   2389: 
1.1057    foxr     2390: 
1.180     matthew  2391: =cut
                   2392: 
                   2393: ###############################################################
                   2394: ###############################################################
                   2395: sub define_excel_formats {
                   2396:     my ($workbook) = @_;
                   2397:     my $format;
                   2398:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2399:                                                 bottom    => 1,
                   2400:                                                 align     => 'center');
                   2401:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2402:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2403:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2404:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2405:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2406:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2407:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2408:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2409:     return $format;
                   2410: }
                   2411: 
                   2412: ###############################################################
                   2413: ###############################################################
1.113     bowersj2 2414: 
                   2415: =pod
                   2416: 
1.648     raeburn  2417: =item * &create_workbook()
1.255     matthew  2418: 
                   2419: Create an Excel worksheet.  If it fails, output message on the
                   2420: request object and return undefs.
                   2421: 
                   2422: Inputs: Apache request object
                   2423: 
                   2424: Returns (undef) on failure, 
                   2425:     Excel worksheet object, scalar with filename, and formats 
                   2426:     from &Apache::loncommon::define_excel_formats on success
                   2427: 
                   2428: =cut
                   2429: 
                   2430: ###############################################################
                   2431: ###############################################################
                   2432: sub create_workbook {
                   2433:     my ($r) = @_;
                   2434:         #
                   2435:     # Create the excel spreadsheet
                   2436:     my $filename = '/prtspool/'.
1.258     albertel 2437:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2438:         time.'_'.rand(1000000000).'.xls';
                   2439:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2440:     if (! defined($workbook)) {
                   2441:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2442:         $r->print(
                   2443:             '<p class="LC_error">'
                   2444:            .&mt('Problems occurred in creating the new Excel file.')
                   2445:            .' '.&mt('This error has been logged.')
                   2446:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2447:            .'</p>'
                   2448:         );
1.255     matthew  2449:         return (undef);
                   2450:     }
                   2451:     #
1.1014    foxr     2452:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2453:     #
                   2454:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2455:     return ($workbook,$filename,$format);
                   2456: }
                   2457: 
                   2458: ###############################################################
                   2459: ###############################################################
                   2460: 
                   2461: =pod
                   2462: 
1.648     raeburn  2463: =item * &create_text_file()
1.113     bowersj2 2464: 
1.542     raeburn  2465: Create a file to write to and eventually make available to the user.
1.256     matthew  2466: If file creation fails, outputs an error message on the request object and 
                   2467: return undefs.
1.113     bowersj2 2468: 
1.256     matthew  2469: Inputs: Apache request object, and file suffix
1.113     bowersj2 2470: 
1.256     matthew  2471: Returns (undef) on failure, 
                   2472:     Filehandle and filename on success.
1.113     bowersj2 2473: 
                   2474: =cut
                   2475: 
1.256     matthew  2476: ###############################################################
                   2477: ###############################################################
                   2478: sub create_text_file {
                   2479:     my ($r,$suffix) = @_;
                   2480:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2481:     my $fh;
                   2482:     my $filename = '/prtspool/'.
1.258     albertel 2483:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2484:         time.'_'.rand(1000000000).'.'.$suffix;
                   2485:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2486:     if (! defined($fh)) {
                   2487:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2488:         $r->print(
                   2489:             '<p class="LC_error">'
                   2490:            .&mt('Problems occurred in creating the output file.')
                   2491:            .' '.&mt('This error has been logged.')
                   2492:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2493:            .'</p>'
                   2494:         );
1.113     bowersj2 2495:     }
1.256     matthew  2496:     return ($fh,$filename)
1.113     bowersj2 2497: }
                   2498: 
                   2499: 
1.256     matthew  2500: =pod 
1.113     bowersj2 2501: 
                   2502: =back
                   2503: 
                   2504: =cut
1.37      matthew  2505: 
                   2506: ###############################################################
1.33      matthew  2507: ##        Home server <option> list generating code          ##
                   2508: ###############################################################
1.35      matthew  2509: 
1.169     www      2510: # ------------------------------------------
                   2511: 
                   2512: sub domain_select {
1.1289    raeburn  2513:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2514:     my @possdoms;
                   2515:     if (ref($incdoms) eq 'ARRAY') {
                   2516:         @possdoms = @{$incdoms};
                   2517:     } else {
                   2518:         @possdoms = &Apache::lonnet::all_domains();
                   2519:     }
                   2520: 
1.169     www      2521:     my %domains=map { 
1.514     albertel 2522: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2523:     } @possdoms;
                   2524: 
                   2525:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2526:         foreach my $dom (@{$excdoms}) {
                   2527:             delete($domains{$dom});
                   2528:         }
                   2529:     }
                   2530: 
1.169     www      2531:     if ($multiple) {
                   2532: 	$domains{''}=&mt('Any domain');
1.550     albertel 2533: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2534: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2535:     } else {
1.550     albertel 2536: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2537: 	return &select_form($name,$value,\%domains);
1.169     www      2538:     }
                   2539: }
                   2540: 
1.282     albertel 2541: #-------------------------------------------
                   2542: 
                   2543: =pod
                   2544: 
1.519     raeburn  2545: =head1 Routines for form select boxes
                   2546: 
                   2547: =over 4
                   2548: 
1.648     raeburn  2549: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2550: 
                   2551: Returns a string containing a <select> element int multiple mode
                   2552: 
                   2553: 
                   2554: Args:
                   2555:   $name - name of the <select> element
1.506     raeburn  2556:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2557:   $size - number of rows long the select element is
1.283     albertel 2558:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2559:           (shown text should already have been &mt())
1.506     raeburn  2560:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2561: 
1.282     albertel 2562: =cut
                   2563: 
                   2564: #-------------------------------------------
1.169     www      2565: sub multiple_select_form {
1.284     albertel 2566:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2567:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2568:     my $output='';
1.191     matthew  2569:     if (! defined($size)) {
                   2570:         $size = 4;
1.283     albertel 2571:         if (scalar(keys(%$hash))<4) {
                   2572:             $size = scalar(keys(%$hash));
1.191     matthew  2573:         }
                   2574:     }
1.734     bisitz   2575:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2576:     my @order;
1.506     raeburn  2577:     if (ref($order) eq 'ARRAY')  {
                   2578:         @order = @{$order};
                   2579:     } else {
                   2580:         @order = sort(keys(%$hash));
1.501     banghart 2581:     }
                   2582:     if (exists($$hash{'select_form_order'})) {
                   2583:         @order = @{$$hash{'select_form_order'}};
                   2584:     }
                   2585:         
1.284     albertel 2586:     foreach my $key (@order) {
1.356     albertel 2587:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2588:         $output.='selected="selected" ' if ($selected{$key});
                   2589:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2590:     }
                   2591:     $output.="</select>\n";
                   2592:     return $output;
                   2593: }
                   2594: 
1.88      www      2595: #-------------------------------------------
                   2596: 
                   2597: =pod
                   2598: 
1.1254    raeburn  2599: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2600: 
                   2601: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2602: allow a user to select options from a ref to a hash containing:
                   2603: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2604: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2605: An optional arg -- $readonly -- if true will cause the select form
                   2606: to be disabled, e.g., for the case where an instructor has a section-
                   2607: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2608: 
1.88      www      2609: See lonrights.pm for an example invocation and use.
                   2610: 
                   2611: =cut
                   2612: 
                   2613: #-------------------------------------------
                   2614: sub select_form {
1.1228    raeburn  2615:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2616:     return unless (ref($hashref) eq 'HASH');
                   2617:     if ($onchange) {
                   2618:         $onchange = ' onchange="'.$onchange.'"';
                   2619:     }
1.1228    raeburn  2620:     my $disabled;
                   2621:     if ($readonly) {
                   2622:         $disabled = ' disabled="disabled"';
                   2623:     }
                   2624:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2625:     my @keys;
1.970     raeburn  2626:     if (exists($hashref->{'select_form_order'})) {
                   2627: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2628:     } else {
1.970     raeburn  2629: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2630:     }
1.356     albertel 2631:     foreach my $key (@keys) {
                   2632:         $selectform.=
                   2633: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2634:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2635:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2636:     }
                   2637:     $selectform.="</select>";
                   2638:     return $selectform;
                   2639: }
                   2640: 
1.475     www      2641: # For display filters
                   2642: 
                   2643: sub display_filter {
1.1074    raeburn  2644:     my ($context) = @_;
1.475     www      2645:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2646:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2647:     my $phraseinput = 'hidden';
                   2648:     my $includeinput = 'hidden';
                   2649:     my ($checked,$includetypestext);
                   2650:     if ($env{'form.displayfilter'} eq 'containing') {
                   2651:         $phraseinput = 'text'; 
                   2652:         if ($context eq 'parmslog') {
                   2653:             $includeinput = 'checkbox';
                   2654:             if ($env{'form.includetypes'}) {
                   2655:                 $checked = ' checked="checked"';
                   2656:             }
                   2657:             $includetypestext = &mt('Include parameter types');
                   2658:         }
                   2659:     } else {
                   2660:         $includetypestext = '&nbsp;';
                   2661:     }
                   2662:     my ($additional,$secondid,$thirdid);
                   2663:     if ($context eq 'parmslog') {
                   2664:         $additional = 
                   2665:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2666:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2667:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2668:             '</label>';
                   2669:         $secondid = 'includetypes';
                   2670:         $thirdid = 'includetypestext';
                   2671:     }
                   2672:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2673:                                                     '$secondid','$thirdid')";
                   2674:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2675: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2676: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2677: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2678:            &mt('Filter: [_1]',
1.477     www      2679: 	   &select_form($env{'form.displayfilter'},
                   2680: 			'displayfilter',
1.970     raeburn  2681: 			{'currentfolder' => 'Current folder/page',
1.477     www      2682: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2683: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2684: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2685:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2686:                          '" />'.$additional;
                   2687: }
                   2688: 
                   2689: sub display_filter_js {
                   2690:     my $includetext = &mt('Include parameter types');
                   2691:     return <<"ENDJS";
                   2692:   
                   2693: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2694:     var firstType = 'hidden';
                   2695:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2696:         firstType = 'text';
                   2697:     }
                   2698:     firstObject = document.getElementById(firstid);
                   2699:     if (typeof(firstObject) == 'object') {
                   2700:         if (firstObject.type != firstType) {
                   2701:             changeInputType(firstObject,firstType);
                   2702:         }
                   2703:     }
                   2704:     if (context == 'parmslog') {
                   2705:         var secondType = 'hidden';
                   2706:         if (firstType == 'text') {
                   2707:             secondType = 'checkbox';
                   2708:         }
                   2709:         secondObject = document.getElementById(secondid);  
                   2710:         if (typeof(secondObject) == 'object') {
                   2711:             if (secondObject.type != secondType) {
                   2712:                 changeInputType(secondObject,secondType);
                   2713:             }
                   2714:         }
                   2715:         var textItem = document.getElementById(thirdid);
                   2716:         var currtext = textItem.innerHTML;
                   2717:         var newtext;
                   2718:         if (firstType == 'text') {
                   2719:             newtext = '$includetext';
                   2720:         } else {
                   2721:             newtext = '&nbsp;';
                   2722:         }
                   2723:         if (currtext != newtext) {
                   2724:             textItem.innerHTML = newtext;
                   2725:         }
                   2726:     }
                   2727:     return;
                   2728: }
                   2729: 
                   2730: function changeInputType(oldObject,newType) {
                   2731:     var newObject = document.createElement('input');
                   2732:     newObject.type = newType;
                   2733:     if (oldObject.size) {
                   2734:         newObject.size = oldObject.size;
                   2735:     }
                   2736:     if (oldObject.value) {
                   2737:         newObject.value = oldObject.value;
                   2738:     }
                   2739:     if (oldObject.name) {
                   2740:         newObject.name = oldObject.name;
                   2741:     }
                   2742:     if (oldObject.id) {
                   2743:         newObject.id = oldObject.id;
                   2744:     }
                   2745:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2746:     return;
                   2747: }
                   2748: 
                   2749: ENDJS
1.475     www      2750: }
                   2751: 
1.167     www      2752: sub gradeleveldescription {
                   2753:     my $gradelevel=shift;
                   2754:     my %gradelevels=(0 => 'Not specified',
                   2755: 		     1 => 'Grade 1',
                   2756: 		     2 => 'Grade 2',
                   2757: 		     3 => 'Grade 3',
                   2758: 		     4 => 'Grade 4',
                   2759: 		     5 => 'Grade 5',
                   2760: 		     6 => 'Grade 6',
                   2761: 		     7 => 'Grade 7',
                   2762: 		     8 => 'Grade 8',
                   2763: 		     9 => 'Grade 9',
                   2764: 		     10 => 'Grade 10',
                   2765: 		     11 => 'Grade 11',
                   2766: 		     12 => 'Grade 12',
                   2767: 		     13 => 'Grade 13',
                   2768: 		     14 => '100 Level',
                   2769: 		     15 => '200 Level',
                   2770: 		     16 => '300 Level',
                   2771: 		     17 => '400 Level',
                   2772: 		     18 => 'Graduate Level');
                   2773:     return &mt($gradelevels{$gradelevel});
                   2774: }
                   2775: 
1.163     www      2776: sub select_level_form {
                   2777:     my ($deflevel,$name)=@_;
                   2778:     unless ($deflevel) { $deflevel=0; }
1.167     www      2779:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2780:     for (my $i=0; $i<=18; $i++) {
                   2781:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2782:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2783:                 ">".&gradeleveldescription($i)."</option>\n";
                   2784:     }
                   2785:     $selectform.="</select>";
                   2786:     return $selectform;
1.163     www      2787: }
1.167     www      2788: 
1.35      matthew  2789: #-------------------------------------------
                   2790: 
1.45      matthew  2791: =pod
                   2792: 
1.1256    raeburn  2793: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2794: 
                   2795: Returns a string containing a <select name='$name' size='1'> form to 
                   2796: allow a user to select the domain to preform an operation in.  
                   2797: See loncreateuser.pm for an example invocation and use.
                   2798: 
1.90      www      2799: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2800: selected");
                   2801: 
1.743     raeburn  2802: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2803: 
1.910     raeburn  2804: 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.
                   2805: 
1.1121    raeburn  2806: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2807: 
                   2808: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2809: 
1.1256    raeburn  2810: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2811: 
1.35      matthew  2812: =cut
                   2813: 
                   2814: #-------------------------------------------
1.34      matthew  2815: sub select_dom_form {
1.1256    raeburn  2816:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2817:     if ($onchange) {
1.874     raeburn  2818:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2819:     }
1.1256    raeburn  2820:     if ($disabled) {
                   2821:         $disabled = ' disabled="disabled"';
                   2822:     }
1.1121    raeburn  2823:     my (@domains,%exclude);
1.910     raeburn  2824:     if (ref($incdoms) eq 'ARRAY') {
                   2825:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2826:     } else {
                   2827:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2828:     }
1.90      www      2829:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2830:     if (ref($excdoms) eq 'ARRAY') {
                   2831:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2832:     }
1.1256    raeburn  2833:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2834:     foreach my $dom (@domains) {
1.1121    raeburn  2835:         next if ($exclude{$dom});
1.356     albertel 2836:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2837:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2838:         if ($showdomdesc) {
                   2839:             if ($dom ne '') {
                   2840:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2841:                 if ($domdesc ne '') {
                   2842:                     $selectdomain .= ' ('.$domdesc.')';
                   2843:                 }
                   2844:             } 
                   2845:         }
                   2846:         $selectdomain .= "</option>\n";
1.34      matthew  2847:     }
                   2848:     $selectdomain.="</select>";
                   2849:     return $selectdomain;
                   2850: }
                   2851: 
1.35      matthew  2852: #-------------------------------------------
                   2853: 
1.45      matthew  2854: =pod
                   2855: 
1.648     raeburn  2856: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2857: 
1.586     raeburn  2858: input: 4 arguments (two required, two optional) - 
                   2859:     $domain - domain of new user
                   2860:     $name - name of form element
                   2861:     $default - Value of 'default' causes a default item to be first 
                   2862:                             option, and selected by default. 
                   2863:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2864:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2865: output: returns 2 items: 
1.586     raeburn  2866: (a) form element which contains either:
                   2867:    (i) <select name="$name">
                   2868:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2869:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2870:        </select>
                   2871:        form item if there are multiple library servers in $domain, or
                   2872:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2873:        if there is only one library server in $domain.
                   2874: 
                   2875: (b) number of library servers found.
                   2876: 
                   2877: See loncreateuser.pm for example of use.
1.35      matthew  2878: 
                   2879: =cut
                   2880: 
                   2881: #-------------------------------------------
1.586     raeburn  2882: sub home_server_form_item {
                   2883:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2884:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2885:     my $result;
                   2886:     my $numlib = keys(%servers);
                   2887:     if ($numlib > 1) {
                   2888:         $result .= '<select name="'.$name.'" />'."\n";
                   2889:         if ($default) {
1.804     bisitz   2890:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2891:                        '</option>'."\n";
                   2892:         }
                   2893:         foreach my $hostid (sort(keys(%servers))) {
                   2894:             $result.= '<option value="'.$hostid.'">'.
                   2895: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2896:         }
                   2897:         $result .= '</select>'."\n";
                   2898:     } elsif ($numlib == 1) {
                   2899:         my $hostid;
                   2900:         foreach my $item (keys(%servers)) {
                   2901:             $hostid = $item;
                   2902:         }
                   2903:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2904:                    $hostid.'" />';
                   2905:                    if (!$hide) {
                   2906:                        $result .= $hostid.' '.$servers{$hostid};
                   2907:                    }
                   2908:                    $result .= "\n";
                   2909:     } elsif ($default) {
                   2910:         $result .= '<input type="hidden" name="'.$name.
                   2911:                    '" value="default" />';
                   2912:                    if (!$hide) {
                   2913:                        $result .= &mt('default');
                   2914:                    }
                   2915:                    $result .= "\n";
1.33      matthew  2916:     }
1.586     raeburn  2917:     return ($result,$numlib);
1.33      matthew  2918: }
1.112     bowersj2 2919: 
                   2920: =pod
                   2921: 
1.534     albertel 2922: =back 
                   2923: 
1.112     bowersj2 2924: =cut
1.87      matthew  2925: 
                   2926: ###############################################################
1.112     bowersj2 2927: ##                  Decoding User Agent                      ##
1.87      matthew  2928: ###############################################################
                   2929: 
                   2930: =pod
                   2931: 
1.112     bowersj2 2932: =head1 Decoding the User Agent
                   2933: 
                   2934: =over 4
                   2935: 
                   2936: =item * &decode_user_agent()
1.87      matthew  2937: 
                   2938: Inputs: $r
                   2939: 
                   2940: Outputs:
                   2941: 
                   2942: =over 4
                   2943: 
1.112     bowersj2 2944: =item * $httpbrowser
1.87      matthew  2945: 
1.112     bowersj2 2946: =item * $clientbrowser
1.87      matthew  2947: 
1.112     bowersj2 2948: =item * $clientversion
1.87      matthew  2949: 
1.112     bowersj2 2950: =item * $clientmathml
1.87      matthew  2951: 
1.112     bowersj2 2952: =item * $clientunicode
1.87      matthew  2953: 
1.112     bowersj2 2954: =item * $clientos
1.87      matthew  2955: 
1.1137    raeburn  2956: =item * $clientmobile
                   2957: 
1.1141    raeburn  2958: =item * $clientinfo
                   2959: 
1.1194    raeburn  2960: =item * $clientosversion
                   2961: 
1.87      matthew  2962: =back
                   2963: 
1.157     matthew  2964: =back 
                   2965: 
1.87      matthew  2966: =cut
                   2967: 
                   2968: ###############################################################
                   2969: ###############################################################
                   2970: sub decode_user_agent {
1.247     albertel 2971:     my ($r)=@_;
1.87      matthew  2972:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2973:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2974:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2975:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2976:     my $clientbrowser='unknown';
                   2977:     my $clientversion='0';
                   2978:     my $clientmathml='';
                   2979:     my $clientunicode='0';
1.1137    raeburn  2980:     my $clientmobile=0;
1.1194    raeburn  2981:     my $clientosversion='';
1.87      matthew  2982:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2983:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2984: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2985: 	    $clientbrowser=$bname;
                   2986:             $httpbrowser=~/$vreg/i;
                   2987: 	    $clientversion=$1;
                   2988:             $clientmathml=($clientversion>=$minv);
                   2989:             $clientunicode=($clientversion>=$univ);
                   2990: 	}
                   2991:     }
                   2992:     my $clientos='unknown';
1.1141    raeburn  2993:     my $clientinfo;
1.87      matthew  2994:     if (($httpbrowser=~/linux/i) ||
                   2995:         ($httpbrowser=~/unix/i) ||
                   2996:         ($httpbrowser=~/ux/i) ||
                   2997:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2998:     if (($httpbrowser=~/vax/i) ||
                   2999:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3000:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3001:     if (($httpbrowser=~/mac/i) ||
                   3002:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3003:     if ($httpbrowser=~/win/i) {
                   3004:         $clientos='win';
                   3005:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3006:             $clientosversion = $1;
                   3007:         }
                   3008:     }
1.87      matthew  3009:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3010:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3011:         $clientmobile=lc($1);
                   3012:     }
1.1141    raeburn  3013:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3014:         $clientinfo = 'firefox-'.$1;
                   3015:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3016:         $clientinfo = 'chromeframe-'.$1;
                   3017:     }
1.87      matthew  3018:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3019:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3020:             $clientosversion);
1.87      matthew  3021: }
                   3022: 
1.32      matthew  3023: ###############################################################
                   3024: ##    Authentication changing form generation subroutines    ##
                   3025: ###############################################################
                   3026: ##
                   3027: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3028: ## hash, and have reasonable default values.
                   3029: ##
                   3030: ##    formname = the name given in the <form> tag.
1.35      matthew  3031: #-------------------------------------------
                   3032: 
1.45      matthew  3033: =pod
                   3034: 
1.112     bowersj2 3035: =head1 Authentication Routines
                   3036: 
                   3037: =over 4
                   3038: 
1.648     raeburn  3039: =item * &authform_xxxxxx()
1.35      matthew  3040: 
                   3041: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3042: handle some of the conveniences required for authentication forms.  
                   3043: This is not an optimal method, but it works.  
                   3044: 
                   3045: =over 4
                   3046: 
1.112     bowersj2 3047: =item * authform_header
1.35      matthew  3048: 
1.112     bowersj2 3049: =item * authform_authorwarning
1.35      matthew  3050: 
1.112     bowersj2 3051: =item * authform_nochange
1.35      matthew  3052: 
1.112     bowersj2 3053: =item * authform_kerberos
1.35      matthew  3054: 
1.112     bowersj2 3055: =item * authform_internal
1.35      matthew  3056: 
1.112     bowersj2 3057: =item * authform_filesystem
1.35      matthew  3058: 
1.1310    raeburn  3059: =item * authform_lti
                   3060: 
1.35      matthew  3061: =back
                   3062: 
1.648     raeburn  3063: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3064: 
1.35      matthew  3065: =cut
                   3066: 
                   3067: #-------------------------------------------
1.32      matthew  3068: sub authform_header{  
                   3069:     my %in = (
                   3070:         formname => 'cu',
1.80      albertel 3071:         kerb_def_dom => '',
1.32      matthew  3072:         @_,
                   3073:     );
                   3074:     $in{'formname'} = 'document.' . $in{'formname'};
                   3075:     my $result='';
1.80      albertel 3076: 
                   3077: #---------------------------------------------- Code for upper case translation
                   3078:     my $Javascript_toUpperCase;
                   3079:     unless ($in{kerb_def_dom}) {
                   3080:         $Javascript_toUpperCase =<<"END";
                   3081:         switch (choice) {
                   3082:            case 'krb': currentform.elements[choicearg].value =
                   3083:                currentform.elements[choicearg].value.toUpperCase();
                   3084:                break;
                   3085:            default:
                   3086:         }
                   3087: END
                   3088:     } else {
                   3089:         $Javascript_toUpperCase = "";
                   3090:     }
                   3091: 
1.165     raeburn  3092:     my $radioval = "'nochange'";
1.591     raeburn  3093:     if (defined($in{'curr_authtype'})) {
                   3094:         if ($in{'curr_authtype'} ne '') {
                   3095:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3096:         }
1.174     matthew  3097:     }
1.165     raeburn  3098:     my $argfield = 'null';
1.591     raeburn  3099:     if (defined($in{'mode'})) {
1.165     raeburn  3100:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3101:             if (defined($in{'curr_autharg'})) {
                   3102:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3103:                     $argfield = "'$in{'curr_autharg'}'";
                   3104:                 }
                   3105:             }
                   3106:         }
                   3107:     }
                   3108: 
1.32      matthew  3109:     $result.=<<"END";
                   3110: var current = new Object();
1.165     raeburn  3111: current.radiovalue = $radioval;
                   3112: current.argfield = $argfield;
1.32      matthew  3113: 
                   3114: function changed_radio(choice,currentform) {
                   3115:     var choicearg = choice + 'arg';
                   3116:     // If a radio button in changed, we need to change the argfield
                   3117:     if (current.radiovalue != choice) {
                   3118:         current.radiovalue = choice;
                   3119:         if (current.argfield != null) {
                   3120:             currentform.elements[current.argfield].value = '';
                   3121:         }
                   3122:         if (choice == 'nochange') {
                   3123:             current.argfield = null;
                   3124:         } else {
                   3125:             current.argfield = choicearg;
                   3126:             switch(choice) {
                   3127:                 case 'krb': 
                   3128:                     currentform.elements[current.argfield].value = 
                   3129:                         "$in{'kerb_def_dom'}";
                   3130:                 break;
                   3131:               default:
                   3132:                 break;
                   3133:             }
                   3134:         }
                   3135:     }
                   3136:     return;
                   3137: }
1.22      www      3138: 
1.32      matthew  3139: function changed_text(choice,currentform) {
                   3140:     var choicearg = choice + 'arg';
                   3141:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3142:         $Javascript_toUpperCase
1.32      matthew  3143:         // clear old field
                   3144:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3145:             currentform.elements[current.argfield].value = '';
                   3146:         }
                   3147:         current.argfield = choicearg;
                   3148:     }
                   3149:     set_auth_radio_buttons(choice,currentform);
                   3150:     return;
1.20      www      3151: }
1.32      matthew  3152: 
                   3153: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3154:     var numauthchoices = currentform.login.length;
                   3155:     if (typeof numauthchoices  == "undefined") {
                   3156:         return;
                   3157:     } 
1.32      matthew  3158:     var i=0;
1.986     raeburn  3159:     while (i < numauthchoices) {
1.32      matthew  3160:         if (currentform.login[i].value == newvalue) { break; }
                   3161:         i++;
                   3162:     }
1.986     raeburn  3163:     if (i == numauthchoices) {
1.32      matthew  3164:         return;
                   3165:     }
                   3166:     current.radiovalue = newvalue;
                   3167:     currentform.login[i].checked = true;
                   3168:     return;
                   3169: }
                   3170: END
                   3171:     return $result;
                   3172: }
                   3173: 
1.1106    raeburn  3174: sub authform_authorwarning {
1.32      matthew  3175:     my $result='';
1.144     matthew  3176:     $result='<i>'.
                   3177:         &mt('As a general rule, only authors or co-authors should be '.
                   3178:             'filesystem authenticated '.
                   3179:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3180:     return $result;
                   3181: }
                   3182: 
1.1106    raeburn  3183: sub authform_nochange {
1.32      matthew  3184:     my %in = (
                   3185:               formname => 'document.cu',
                   3186:               kerb_def_dom => 'MSU.EDU',
                   3187:               @_,
                   3188:           );
1.1106    raeburn  3189:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3190:     my $result;
1.1104    raeburn  3191:     if (!$authnum) {
1.1105    raeburn  3192:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3193:     } else {
                   3194:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3195:                   '<input type="radio" name="login" value="nochange" '.
                   3196:                   'checked="checked" onclick="'.
1.281     albertel 3197:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3198: 	    '</label>';
1.586     raeburn  3199:     }
1.32      matthew  3200:     return $result;
                   3201: }
                   3202: 
1.591     raeburn  3203: sub authform_kerberos {
1.32      matthew  3204:     my %in = (
                   3205:               formname => 'document.cu',
                   3206:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3207:               kerb_def_auth => 'krb4',
1.32      matthew  3208:               @_,
                   3209:               );
1.586     raeburn  3210:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3211:         $autharg,$jscall,$disabled);
1.1106    raeburn  3212:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3213:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3214:        $check5 = ' checked="checked"';
1.80      albertel 3215:     } else {
1.772     bisitz   3216:        $check4 = ' checked="checked"';
1.80      albertel 3217:     }
1.1259    raeburn  3218:     if ($in{'readonly'}) {
                   3219:         $disabled = ' disabled="disabled"';
                   3220:     }
1.165     raeburn  3221:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3222:     if (defined($in{'curr_authtype'})) {
                   3223:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3224:             $krbcheck = ' checked="checked"';
1.623     raeburn  3225:             if (defined($in{'mode'})) {
                   3226:                 if ($in{'mode'} eq 'modifyuser') {
                   3227:                     $krbcheck = '';
                   3228:                 }
                   3229:             }
1.591     raeburn  3230:             if (defined($in{'curr_kerb_ver'})) {
                   3231:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3232:                     $check5 = ' checked="checked"';
1.591     raeburn  3233:                     $check4 = '';
                   3234:                 } else {
1.772     bisitz   3235:                     $check4 = ' checked="checked"';
1.591     raeburn  3236:                     $check5 = '';
                   3237:                 }
1.586     raeburn  3238:             }
1.591     raeburn  3239:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3240:                 $krbarg = $in{'curr_autharg'};
                   3241:             }
1.586     raeburn  3242:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3243:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3244:                     $result = 
                   3245:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3246:         $in{'curr_autharg'},$krbver);
                   3247:                 } else {
                   3248:                     $result =
                   3249:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3250:                 }
                   3251:                 return $result; 
                   3252:             }
                   3253:         }
                   3254:     } else {
                   3255:         if ($authnum == 1) {
1.784     bisitz   3256:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3257:         }
                   3258:     }
1.586     raeburn  3259:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3260:         return;
1.587     raeburn  3261:     } elsif ($authtype eq '') {
1.591     raeburn  3262:         if (defined($in{'mode'})) {
1.587     raeburn  3263:             if ($in{'mode'} eq 'modifycourse') {
                   3264:                 if ($authnum == 1) {
1.1259    raeburn  3265:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3266:                 }
                   3267:             }
                   3268:         }
1.586     raeburn  3269:     }
                   3270:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3271:     if ($authtype eq '') {
                   3272:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3273:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3274:                     $krbcheck.$disabled.' />';
1.586     raeburn  3275:     }
                   3276:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3277:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3278:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3279:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3280:          $in{'curr_authtype'} eq 'krb4')) {
                   3281:         $result .= &mt
1.144     matthew  3282:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3283:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3284:          '<label>'.$authtype,
1.281     albertel 3285:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3286:              'value="'.$krbarg.'" '.
1.1259    raeburn  3287:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3288:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3289:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3290: 	 '</label>');
1.586     raeburn  3291:     } elsif ($can_assign{'krb4'}) {
                   3292:         $result .= &mt
                   3293:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3294:          '[_3] Version 4 [_4]',
                   3295:          '<label>'.$authtype,
                   3296:          '</label><input type="text" size="10" name="krbarg" '.
                   3297:              'value="'.$krbarg.'" '.
1.1259    raeburn  3298:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3299:          '<label><input type="hidden" name="krbver" value="4" />',
                   3300:          '</label>');
                   3301:     } elsif ($can_assign{'krb5'}) {
                   3302:         $result .= &mt
                   3303:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3304:          '[_3] Version 5 [_4]',
                   3305:          '<label>'.$authtype,
                   3306:          '</label><input type="text" size="10" name="krbarg" '.
                   3307:              'value="'.$krbarg.'" '.
1.1259    raeburn  3308:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3309:          '<label><input type="hidden" name="krbver" value="5" />',
                   3310:          '</label>');
                   3311:     }
1.32      matthew  3312:     return $result;
                   3313: }
                   3314: 
1.1106    raeburn  3315: sub authform_internal {
1.586     raeburn  3316:     my %in = (
1.32      matthew  3317:                 formname => 'document.cu',
                   3318:                 kerb_def_dom => 'MSU.EDU',
                   3319:                 @_,
                   3320:                 );
1.1259    raeburn  3321:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3322:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3323:     if ($in{'readonly'}) {
                   3324:         $disabled = ' disabled="disabled"';
                   3325:     }
1.591     raeburn  3326:     if (defined($in{'curr_authtype'})) {
                   3327:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3328:             if ($can_assign{'int'}) {
1.772     bisitz   3329:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3330:                 if (defined($in{'mode'})) {
                   3331:                     if ($in{'mode'} eq 'modifyuser') {
                   3332:                         $intcheck = '';
                   3333:                     }
                   3334:                 }
1.591     raeburn  3335:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3336:                     $intarg = $in{'curr_autharg'};
                   3337:                 }
                   3338:             } else {
                   3339:                 $result = &mt('Currently internally authenticated.');
                   3340:                 return $result;
1.165     raeburn  3341:             }
                   3342:         }
1.586     raeburn  3343:     } else {
                   3344:         if ($authnum == 1) {
1.784     bisitz   3345:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3346:         }
                   3347:     }
                   3348:     if (!$can_assign{'int'}) {
                   3349:         return;
1.587     raeburn  3350:     } elsif ($authtype eq '') {
1.591     raeburn  3351:         if (defined($in{'mode'})) {
1.587     raeburn  3352:             if ($in{'mode'} eq 'modifycourse') {
                   3353:                 if ($authnum == 1) {
1.1259    raeburn  3354:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3355:                 }
                   3356:             }
                   3357:         }
1.165     raeburn  3358:     }
1.586     raeburn  3359:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3360:     if ($authtype eq '') {
                   3361:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3362:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3363:     }
1.605     bisitz   3364:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3365:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3366:     $result = &mt
1.144     matthew  3367:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3368:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3369:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3370:     return $result;
                   3371: }
                   3372: 
1.1104    raeburn  3373: sub authform_local {
1.32      matthew  3374:     my %in = (
                   3375:               formname => 'document.cu',
                   3376:               kerb_def_dom => 'MSU.EDU',
                   3377:               @_,
                   3378:               );
1.1259    raeburn  3379:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3380:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3381:     if ($in{'readonly'}) {
                   3382:         $disabled = ' disabled="disabled"';
                   3383:     } 
1.591     raeburn  3384:     if (defined($in{'curr_authtype'})) {
                   3385:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3386:             if ($can_assign{'loc'}) {
1.772     bisitz   3387:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3388:                 if (defined($in{'mode'})) {
                   3389:                     if ($in{'mode'} eq 'modifyuser') {
                   3390:                         $loccheck = '';
                   3391:                     }
                   3392:                 }
1.591     raeburn  3393:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3394:                     $locarg = $in{'curr_autharg'};
                   3395:                 }
                   3396:             } else {
                   3397:                 $result = &mt('Currently using local (institutional) authentication.');
                   3398:                 return $result;
1.165     raeburn  3399:             }
                   3400:         }
1.586     raeburn  3401:     } else {
                   3402:         if ($authnum == 1) {
1.784     bisitz   3403:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3404:         }
                   3405:     }
                   3406:     if (!$can_assign{'loc'}) {
                   3407:         return;
1.587     raeburn  3408:     } elsif ($authtype eq '') {
1.591     raeburn  3409:         if (defined($in{'mode'})) {
1.587     raeburn  3410:             if ($in{'mode'} eq 'modifycourse') {
                   3411:                 if ($authnum == 1) {
1.1259    raeburn  3412:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3413:                 }
                   3414:             }
                   3415:         }
1.165     raeburn  3416:     }
1.586     raeburn  3417:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3418:     if ($authtype eq '') {
                   3419:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3420:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3421:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3422:     }
                   3423:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3424:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3425:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3426:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3427:     return $result;
                   3428: }
                   3429: 
1.1106    raeburn  3430: sub authform_filesystem {
1.32      matthew  3431:     my %in = (
                   3432:               formname => 'document.cu',
                   3433:               kerb_def_dom => 'MSU.EDU',
                   3434:               @_,
                   3435:               );
1.1259    raeburn  3436:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3437:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3438:     if ($in{'readonly'}) {
                   3439:         $disabled = ' disabled="disabled"';
                   3440:     }
1.591     raeburn  3441:     if (defined($in{'curr_authtype'})) {
                   3442:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3443:             if ($can_assign{'fsys'}) {
1.772     bisitz   3444:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3445:                 if (defined($in{'mode'})) {
                   3446:                     if ($in{'mode'} eq 'modifyuser') {
                   3447:                         $fsyscheck = '';
                   3448:                     }
                   3449:                 }
1.586     raeburn  3450:             } else {
                   3451:                 $result = &mt('Currently Filesystem Authenticated.');
                   3452:                 return $result;
1.1259    raeburn  3453:             }
1.586     raeburn  3454:         }
                   3455:     } else {
                   3456:         if ($authnum == 1) {
1.784     bisitz   3457:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3458:         }
                   3459:     }
                   3460:     if (!$can_assign{'fsys'}) {
                   3461:         return;
1.587     raeburn  3462:     } elsif ($authtype eq '') {
1.591     raeburn  3463:         if (defined($in{'mode'})) {
1.587     raeburn  3464:             if ($in{'mode'} eq 'modifycourse') {
                   3465:                 if ($authnum == 1) {
1.1259    raeburn  3466:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3467:                 }
                   3468:             }
                   3469:         }
1.586     raeburn  3470:     }
                   3471:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3472:     if ($authtype eq '') {
                   3473:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3474:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3475:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3476:     }
1.1310    raeburn  3477:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3478:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3479:     $result = &mt
1.144     matthew  3480:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3481:          '<label>'.$authtype,'</label>'.$autharg);
                   3482:     return $result;
                   3483: }
                   3484: 
                   3485: sub authform_lti {
                   3486:     my %in = (
                   3487:               formname => 'document.cu',
                   3488:               kerb_def_dom => 'MSU.EDU',
                   3489:               @_,
                   3490:               );
                   3491:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3492:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3493:     if ($in{'readonly'}) {
                   3494:         $disabled = ' disabled="disabled"';
                   3495:     }
                   3496:     if (defined($in{'curr_authtype'})) {
                   3497:         if ($in{'curr_authtype'} eq 'lti') {
                   3498:             if ($can_assign{'lti'}) {
                   3499:                 $lticheck = 'checked="checked" ';
                   3500:                 if (defined($in{'mode'})) {
                   3501:                     if ($in{'mode'} eq 'modifyuser') {
                   3502:                         $lticheck = '';
                   3503:                     }
                   3504:                 }
                   3505:             } else {
                   3506:                 $result = &mt('Currently LTI Authenticated.');
                   3507:                 return $result;
                   3508:             }
                   3509:         }
                   3510:     } else {
                   3511:         if ($authnum == 1) {
                   3512:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3513:         }
                   3514:     }
                   3515:     if (!$can_assign{'lti'}) {
                   3516:         return;
                   3517:     } elsif ($authtype eq '') {
                   3518:         if (defined($in{'mode'})) {
                   3519:             if ($in{'mode'} eq 'modifycourse') {
                   3520:                 if ($authnum == 1) {
                   3521:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3522:                 }
                   3523:             }
                   3524:         }
                   3525:     }
                   3526:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3527:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3528:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3529:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3530:                     $jscall.'"'.$disabled.' />';
                   3531:     }
                   3532:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3533:     if ($authtype) {
                   3534:         $result = &mt('[_1] LTI Authenticated',
                   3535:                       '<label>'.$authtype.'</label>'.$autharg);
                   3536:     } else {
                   3537:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3538:                   $autharg;
                   3539:     }
1.32      matthew  3540:     return $result;
                   3541: }
                   3542: 
1.586     raeburn  3543: sub get_assignable_auth {
                   3544:     my ($dom) = @_;
                   3545:     if ($dom eq '') {
                   3546:         $dom = $env{'request.role.domain'};
                   3547:     }
                   3548:     my %can_assign = (
                   3549:                           krb4 => 1,
                   3550:                           krb5 => 1,
                   3551:                           int  => 1,
                   3552:                           loc  => 1,
1.1310    raeburn  3553:                           lti  => 1,
1.586     raeburn  3554:                      );
                   3555:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3556:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3557:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3558:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3559:             my $context;
                   3560:             if ($env{'request.role'} =~ /^au/) {
                   3561:                 $context = 'author';
1.1259    raeburn  3562:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3563:                 $context = 'domain';
                   3564:             } elsif ($env{'request.course.id'}) {
                   3565:                 $context = 'course';
                   3566:             }
                   3567:             if ($context) {
                   3568:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3569:                    %can_assign = %{$authhash->{$context}}; 
                   3570:                 }
                   3571:             }
                   3572:         }
                   3573:     }
                   3574:     my $authnum = 0;
                   3575:     foreach my $key (keys(%can_assign)) {
                   3576:         if ($can_assign{$key}) {
                   3577:             $authnum ++;
                   3578:         }
                   3579:     }
                   3580:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3581:         $authnum --;
                   3582:     }
                   3583:     return ($authnum,%can_assign);
                   3584: }
                   3585: 
1.1331    raeburn  3586: sub check_passwd_rules {
                   3587:     my ($domain,$plainpass) = @_;
                   3588:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3589:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3590:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3591:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3592:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3593:             if ($passwdconf{'min'} > $min) {
                   3594:                 $min = $passwdconf{'min'};
                   3595:             }
1.1331    raeburn  3596:         }
                   3597:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3598:             $max = $passwdconf{'max'};
                   3599:         }
                   3600:         @chars = @{$passwdconf{'chars'}};
                   3601:     }
                   3602:     if (($min) && (length($plainpass) < $min)) {
                   3603:         push(@brokerule,'min');
                   3604:     }
                   3605:     if (($max) && (length($plainpass) > $max)) {
                   3606:         push(@brokerule,'max');
                   3607:     }
                   3608:     if (@chars) {
                   3609:         my %rules;
                   3610:         map { $rules{$_} = 1; } @chars;
                   3611:         if ($rules{'uc'}) {
                   3612:             unless ($plainpass =~ /[A-Z]/) {
                   3613:                 push(@brokerule,'uc');
                   3614:             }
                   3615:         }
                   3616:         if ($rules{'lc'}) {
1.1332    raeburn  3617:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3618:                 push(@brokerule,'lc');
                   3619:             }
                   3620:         }
                   3621:         if ($rules{'num'}) {
                   3622:             unless ($plainpass =~ /\d/) {
                   3623:                 push(@brokerule,'num');
                   3624:             }
                   3625:         }
                   3626:         if ($rules{'spec'}) {
                   3627:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3628:                 push(@brokerule,'spec');
                   3629:             }
                   3630:         }
                   3631:     }
                   3632:     if (@brokerule) {
                   3633:         my %rulenames = &Apache::lonlocal::texthash(
                   3634:             uc   => 'At least one upper case letter',
                   3635:             lc   => 'At least one lower case letter',
                   3636:             num  => 'At least one number',
                   3637:             spec => 'At least one non-alphanumeric',
                   3638:         );
                   3639:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3640:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3641:         $rulenames{'num'} .= ': 0123456789';
                   3642:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3643:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3644:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3645:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3646:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3647:             if (grep(/^$rule$/,@brokerule)) {
                   3648:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3649:             }
                   3650:         }
                   3651:         $warning .= '</ul>';
                   3652:     }
1.1332    raeburn  3653:     if (wantarray) {
                   3654:         return @brokerule;
                   3655:     }
1.1331    raeburn  3656:     return $warning;
                   3657: }
                   3658: 
1.1376    raeburn  3659: sub passwd_validation_js {
1.1377    raeburn  3660:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3661:     my (%passwdconf,$alertmsg);
                   3662:     if ($context eq 'linkprot') {
                   3663:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3664:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3665:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3666:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3667:             }
                   3668:         }
                   3669:         if ($id eq 'add') {
                   3670:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3671:         } elsif ($id =~ /^\d+$/) {
                   3672:             my $pos = $id+1;
                   3673:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3674:         } else {
                   3675:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3676:         }
                   3677:     } else {
                   3678:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3679:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3680:     }
1.1376    raeburn  3681:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3682:     $numrules = 0;
                   3683:     $min = $Apache::lonnet::passwdmin;
                   3684:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3685:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3686:             if ($passwdconf{'min'} > $min) {
                   3687:                 $min = $passwdconf{'min'};
                   3688:             }
                   3689:         }
                   3690:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3691:             $max = $passwdconf{'max'};
                   3692:             $numrules ++;
                   3693:         }
                   3694:         @chars = @{$passwdconf{'chars'}};
                   3695:         if (@chars) {
                   3696:             $numrules ++;
                   3697:         }
                   3698:     }
                   3699:     if ($min > 0) {
                   3700:         $numrules ++;
                   3701:     }
                   3702:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3703:         if ($min) {
                   3704:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3705:         }
                   3706:         if ($max) {
                   3707:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3708:         }
                   3709:         my (@charalerts,@charrules);
                   3710:         if (@chars) {
                   3711:             if (grep(/^uc$/,@chars)) {
                   3712:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3713:                 push(@charrules,'uc');
                   3714:             }
                   3715:             if (grep(/^lc$/,@chars)) {
                   3716:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3717:                 push(@charrules,'lc');
                   3718:             }
                   3719:             if (grep(/^num$/,@chars)) {
                   3720:                 push(@charalerts,&mt('contain at least one number'));
                   3721:                 push(@charrules,'num');
                   3722:             }
                   3723:             if (grep(/^spec$/,@chars)) {
                   3724:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3725:                 push(@charrules,'spec');
                   3726:             }
                   3727:         }
                   3728:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3729:                     qq|            var currpwval = $currpasswdval;\n|;
                   3730:             if ($min) {
                   3731:                 $intargjs .= qq|
                   3732:             if (currpwval.length < $min) {
                   3733:                 rulesmsg += ' - $alert{min}';
                   3734:             }
                   3735: |;
                   3736:             }
                   3737:             if ($max) {
                   3738:                 $intargjs .= qq|
                   3739:             if (currpwval.length > $max) {
                   3740:                 rulesmsg += ' - $alert{max}';
                   3741:             }
                   3742: |;
                   3743:             }
                   3744:             if (@chars > 0) {
                   3745:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3746:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3747:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3748:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3749:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3750:                 my %rules;
                   3751:                 map { $rules{$_} = 1; } @chars;
                   3752:                 if ($rules{'uc'}) {
                   3753:                     $intargjs .= qq|
                   3754:             var ucRegExp = /[A-Z]/;
                   3755:             if (!ucRegExp.test(currpwval)) {
                   3756:                 brokerules.push('uc');
                   3757:             }
                   3758: |;
                   3759:                 }
                   3760:                 if ($rules{'lc'}) {
                   3761:                     $intargjs .= qq|
                   3762:             var lcRegExp = /[a-z]/;
                   3763:             if (!lcRegExp.test(currpwval)) {
                   3764:                 brokerules.push('lc');
                   3765:             }
                   3766: |;
                   3767:                 }
                   3768:                 if ($rules{'num'}) {
                   3769:                      $intargjs .= qq|
                   3770:             var numRegExp = /[0-9]/;
                   3771:             if (!numRegExp.test(currpwval)) {
                   3772:                 brokerules.push('num');
                   3773:             }
                   3774: |;
                   3775:                 }
                   3776:                 if ($rules{'spec'}) {
                   3777:                      $intargjs .= q|
                   3778:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3779:             if (!specRegExp.test(currpwval)) {
                   3780:                 brokerules.push('spec');
                   3781:             }
                   3782: |;
                   3783:                 }
                   3784:                 $intargjs .= qq|
                   3785:             if (brokerules.length > 0) {
                   3786:                 for (var i=0; i<brokerules.length; i++) {
                   3787:                     for (var j=0; j<charrules.length; j++) {
                   3788:                         if (brokerules[i] == charrules[j]) {
                   3789:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3790:                             break;
                   3791:                         }
                   3792:                     }
                   3793:                 }
                   3794:             }
                   3795: |;
                   3796:             }
                   3797:             $intargjs .= qq|
                   3798:             if (rulesmsg != '') {
                   3799:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3800:                 alert(rulesmsg);
                   3801:                 return false;
                   3802:             }
                   3803: |;
                   3804:     }
                   3805:     return ($numrules,$intargjs);
                   3806: }
                   3807: 
1.80      albertel 3808: ###############################################################
                   3809: ##    Get Kerberos Defaults for Domain                 ##
                   3810: ###############################################################
                   3811: ##
                   3812: ## Returns default kerberos version and an associated argument
                   3813: ## as listed in file domain.tab. If not listed, provides
                   3814: ## appropriate default domain and kerberos version.
                   3815: ##
                   3816: #-------------------------------------------
                   3817: 
                   3818: =pod
                   3819: 
1.648     raeburn  3820: =item * &get_kerberos_defaults()
1.80      albertel 3821: 
                   3822: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3823: version and domain. If not found, it defaults to version 4 and the 
                   3824: domain of the server.
1.80      albertel 3825: 
1.648     raeburn  3826: =over 4
                   3827: 
1.80      albertel 3828: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3829: 
1.648     raeburn  3830: =back
                   3831: 
                   3832: =back
                   3833: 
1.80      albertel 3834: =cut
                   3835: 
                   3836: #-------------------------------------------
                   3837: sub get_kerberos_defaults {
                   3838:     my $domain=shift;
1.641     raeburn  3839:     my ($krbdef,$krbdefdom);
                   3840:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3841:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3842:         $krbdef = $domdefaults{'auth_def'};
                   3843:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3844:     } else {
1.80      albertel 3845:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3846:         my $krbdefdom=$1;
                   3847:         $krbdefdom=~tr/a-z/A-Z/;
                   3848:         $krbdef = "krb4";
                   3849:     }
                   3850:     return ($krbdef,$krbdefdom);
                   3851: }
1.112     bowersj2 3852: 
1.32      matthew  3853: 
1.46      matthew  3854: ###############################################################
                   3855: ##                Thesaurus Functions                        ##
                   3856: ###############################################################
1.20      www      3857: 
1.46      matthew  3858: =pod
1.20      www      3859: 
1.112     bowersj2 3860: =head1 Thesaurus Functions
                   3861: 
                   3862: =over 4
                   3863: 
1.648     raeburn  3864: =item * &initialize_keywords()
1.46      matthew  3865: 
                   3866: Initializes the package variable %Keywords if it is empty.  Uses the
                   3867: package variable $thesaurus_db_file.
                   3868: 
                   3869: =cut
                   3870: 
                   3871: ###################################################
                   3872: 
                   3873: sub initialize_keywords {
                   3874:     return 1 if (scalar keys(%Keywords));
                   3875:     # If we are here, %Keywords is empty, so fill it up
                   3876:     #   Make sure the file we need exists...
                   3877:     if (! -e $thesaurus_db_file) {
                   3878:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3879:                                  " failed because it does not exist");
                   3880:         return 0;
                   3881:     }
                   3882:     #   Set up the hash as a database
                   3883:     my %thesaurus_db;
                   3884:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3885:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3886:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3887:                                  $thesaurus_db_file);
                   3888:         return 0;
                   3889:     } 
                   3890:     #  Get the average number of appearances of a word.
                   3891:     my $avecount = $thesaurus_db{'average.count'};
                   3892:     #  Put keywords (those that appear > average) into %Keywords
                   3893:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3894:         my ($count,undef) = split /:/,$data;
                   3895:         $Keywords{$word}++ if ($count > $avecount);
                   3896:     }
                   3897:     untie %thesaurus_db;
                   3898:     # Remove special values from %Keywords.
1.356     albertel 3899:     foreach my $value ('total.count','average.count') {
                   3900:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3901:   }
1.46      matthew  3902:     return 1;
                   3903: }
                   3904: 
                   3905: ###################################################
                   3906: 
                   3907: =pod
                   3908: 
1.648     raeburn  3909: =item * &keyword($word)
1.46      matthew  3910: 
                   3911: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3912: than the average number of times in the thesaurus database.  Calls 
                   3913: &initialize_keywords
                   3914: 
                   3915: =cut
                   3916: 
                   3917: ###################################################
1.20      www      3918: 
                   3919: sub keyword {
1.46      matthew  3920:     return if (!&initialize_keywords());
                   3921:     my $word=lc(shift());
                   3922:     $word=~s/\W//g;
                   3923:     return exists($Keywords{$word});
1.20      www      3924: }
1.46      matthew  3925: 
                   3926: ###############################################################
                   3927: 
                   3928: =pod 
1.20      www      3929: 
1.648     raeburn  3930: =item * &get_related_words()
1.46      matthew  3931: 
1.160     matthew  3932: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3933: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3934: will be returned.  The order of the words returned is determined by the
                   3935: database which holds them.
                   3936: 
                   3937: Uses global $thesaurus_db_file.
                   3938: 
1.1057    foxr     3939: 
1.46      matthew  3940: =cut
                   3941: 
                   3942: ###############################################################
                   3943: sub get_related_words {
                   3944:     my $keyword = shift;
                   3945:     my %thesaurus_db;
                   3946:     if (! -e $thesaurus_db_file) {
                   3947:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3948:                                  "failed because the file does not exist");
                   3949:         return ();
                   3950:     }
                   3951:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3952:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3953:         return ();
                   3954:     } 
                   3955:     my @Words=();
1.429     www      3956:     my $count=0;
1.46      matthew  3957:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3958: 	# The first element is the number of times
                   3959: 	# the word appears.  We do not need it now.
1.429     www      3960: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3961: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3962: 	my $threshold=$mostfrequentcount/10;
                   3963:         foreach my $possibleword (@RelatedWords) {
                   3964:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3965:             if ($wordcount>$threshold) {
                   3966: 		push(@Words,$word);
                   3967:                 $count++;
                   3968:                 if ($count>10) { last; }
                   3969: 	    }
1.20      www      3970:         }
                   3971:     }
1.46      matthew  3972:     untie %thesaurus_db;
                   3973:     return @Words;
1.14      harris41 3974: }
1.1090    foxr     3975: ###############################################################
                   3976: #
                   3977: #  Spell checking
                   3978: #
                   3979: 
                   3980: =pod
                   3981: 
1.1142    raeburn  3982: =back
                   3983: 
1.1090    foxr     3984: =head1 Spell checking
                   3985: 
                   3986: =over 4
                   3987: 
                   3988: =item * &check_spelling($wordlist $language)
                   3989: 
                   3990: Takes a string containing words and feeds it to an external
                   3991: spellcheck program via a pipeline. Returns a string containing
                   3992: them mis-spelled words.
                   3993: 
                   3994: Parameters:
                   3995: 
                   3996: =over 4
                   3997: 
                   3998: =item - $wordlist
                   3999: 
                   4000: String that will be fed into the spellcheck program.
                   4001: 
                   4002: =item - $language
                   4003: 
                   4004: Language string that specifies the language for which the spell
                   4005: check will be performed.
                   4006: 
                   4007: =back
                   4008: 
                   4009: =back
                   4010: 
                   4011: Note: This sub assumes that aspell is installed.
                   4012: 
                   4013: 
                   4014: =cut
                   4015: 
1.46      matthew  4016: 
1.1090    foxr     4017: sub check_spelling {
                   4018:     my ($wordlist, $language) = @_;
1.1091    foxr     4019:     my @misspellings;
                   4020:     
                   4021:     # Generate the speller and set the langauge.
                   4022:     # if explicitly selected:
1.1090    foxr     4023: 
1.1091    foxr     4024:     my $speller = Text::Aspell->new;
1.1090    foxr     4025:     if ($language) {
1.1091    foxr     4026: 	$speller->set_option('lang', $language);
1.1090    foxr     4027:     }
                   4028: 
1.1091    foxr     4029:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4030: 
1.1091    foxr     4031:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4032: 
1.1091    foxr     4033:     foreach my $word (@words) {
                   4034: 	if(! $speller->check($word)) {
                   4035: 	    push(@misspellings, $word);
1.1090    foxr     4036: 	}
                   4037:     }
1.1091    foxr     4038:     return join(' ', @misspellings);
                   4039:     
1.1090    foxr     4040: }
                   4041: 
1.61      www      4042: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4043: =pod
                   4044: 
1.112     bowersj2 4045: =head1 User Name Functions
                   4046: 
                   4047: =over 4
                   4048: 
1.648     raeburn  4049: =item * &plainname($uname,$udom,$first)
1.81      albertel 4050: 
1.112     bowersj2 4051: Takes a users logon name and returns it as a string in
1.226     albertel 4052: "first middle last generation" form 
                   4053: if $first is set to 'lastname' then it returns it as
                   4054: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4055: 
                   4056: =cut
1.61      www      4057: 
1.295     www      4058: 
1.81      albertel 4059: ###############################################################
1.61      www      4060: sub plainname {
1.226     albertel 4061:     my ($uname,$udom,$first)=@_;
1.537     albertel 4062:     return if (!defined($uname) || !defined($udom));
1.295     www      4063:     my %names=&getnames($uname,$udom);
1.226     albertel 4064:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4065: 					  $names{'middlename'},
                   4066: 					  $names{'lastname'},
                   4067: 					  $names{'generation'},$first);
                   4068:     $name=~s/^\s+//;
1.62      www      4069:     $name=~s/\s+$//;
                   4070:     $name=~s/\s+/ /g;
1.353     albertel 4071:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4072:     return $name;
1.61      www      4073: }
1.66      www      4074: 
                   4075: # -------------------------------------------------------------------- Nickname
1.81      albertel 4076: =pod
                   4077: 
1.648     raeburn  4078: =item * &nickname($uname,$udom)
1.81      albertel 4079: 
                   4080: Gets a users name and returns it as a string as
                   4081: 
                   4082: "&quot;nickname&quot;"
1.66      www      4083: 
1.81      albertel 4084: if the user has a nickname or
                   4085: 
                   4086: "first middle last generation"
                   4087: 
                   4088: if the user does not
                   4089: 
                   4090: =cut
1.66      www      4091: 
                   4092: sub nickname {
                   4093:     my ($uname,$udom)=@_;
1.537     albertel 4094:     return if (!defined($uname) || !defined($udom));
1.295     www      4095:     my %names=&getnames($uname,$udom);
1.68      albertel 4096:     my $name=$names{'nickname'};
1.66      www      4097:     if ($name) {
                   4098:        $name='&quot;'.$name.'&quot;'; 
                   4099:     } else {
                   4100:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4101: 	     $names{'lastname'}.' '.$names{'generation'};
                   4102:        $name=~s/\s+$//;
                   4103:        $name=~s/\s+/ /g;
                   4104:     }
                   4105:     return $name;
                   4106: }
                   4107: 
1.295     www      4108: sub getnames {
                   4109:     my ($uname,$udom)=@_;
1.537     albertel 4110:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4111:     if ($udom eq 'public' && $uname eq 'public') {
                   4112: 	return ('lastname' => &mt('Public'));
                   4113:     }
1.295     www      4114:     my $id=$uname.':'.$udom;
                   4115:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4116:     if ($cached) {
                   4117: 	return %{$names};
                   4118:     } else {
                   4119: 	my %loadnames=&Apache::lonnet::get('environment',
                   4120:                     ['firstname','middlename','lastname','generation','nickname'],
                   4121: 					 $udom,$uname);
                   4122: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4123: 	return %loadnames;
                   4124:     }
                   4125: }
1.61      www      4126: 
1.542     raeburn  4127: # -------------------------------------------------------------------- getemails
1.648     raeburn  4128: 
1.542     raeburn  4129: =pod
                   4130: 
1.648     raeburn  4131: =item * &getemails($uname,$udom)
1.542     raeburn  4132: 
                   4133: Gets a user's email information and returns it as a hash with keys:
                   4134: notification, critnotification, permanentemail
                   4135: 
                   4136: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4137: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4138:  
1.648     raeburn  4139: 
1.542     raeburn  4140: =cut
                   4141: 
1.648     raeburn  4142: 
1.466     albertel 4143: sub getemails {
                   4144:     my ($uname,$udom)=@_;
                   4145:     if ($udom eq 'public' && $uname eq 'public') {
                   4146: 	return;
                   4147:     }
1.467     www      4148:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4149:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4150:     my $id=$uname.':'.$udom;
                   4151:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4152:     if ($cached) {
                   4153: 	return %{$names};
                   4154:     } else {
                   4155: 	my %loadnames=&Apache::lonnet::get('environment',
                   4156:                     			   ['notification','critnotification',
                   4157: 					    'permanentemail'],
                   4158: 					   $udom,$uname);
                   4159: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4160: 	return %loadnames;
                   4161:     }
                   4162: }
                   4163: 
1.551     albertel 4164: sub flush_email_cache {
                   4165:     my ($uname,$udom)=@_;
                   4166:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4167:     if (!$uname) { $uname=$env{'user.name'};   }
                   4168:     return if ($udom eq 'public' && $uname eq 'public');
                   4169:     my $id=$uname.':'.$udom;
                   4170:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4171: }
                   4172: 
1.728     raeburn  4173: # -------------------------------------------------------------------- getlangs
                   4174: 
                   4175: =pod
                   4176: 
                   4177: =item * &getlangs($uname,$udom)
                   4178: 
                   4179: Gets a user's language preference and returns it as a hash with key:
                   4180: language.
                   4181: 
                   4182: =cut
                   4183: 
                   4184: 
                   4185: sub getlangs {
                   4186:     my ($uname,$udom) = @_;
                   4187:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4188:     if (!$uname) { $uname=$env{'user.name'};   }
                   4189:     my $id=$uname.':'.$udom;
                   4190:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4191:     if ($cached) {
                   4192:         return %{$langs};
                   4193:     } else {
                   4194:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4195:                                            $udom,$uname);
                   4196:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4197:         return %loadlangs;
                   4198:     }
                   4199: }
                   4200: 
                   4201: sub flush_langs_cache {
                   4202:     my ($uname,$udom)=@_;
                   4203:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4204:     if (!$uname) { $uname=$env{'user.name'};   }
                   4205:     return if ($udom eq 'public' && $uname eq 'public');
                   4206:     my $id=$uname.':'.$udom;
                   4207:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4208: }
                   4209: 
1.61      www      4210: # ------------------------------------------------------------------ Screenname
1.81      albertel 4211: 
                   4212: =pod
                   4213: 
1.648     raeburn  4214: =item * &screenname($uname,$udom)
1.81      albertel 4215: 
                   4216: Gets a users screenname and returns it as a string
                   4217: 
                   4218: =cut
1.61      www      4219: 
                   4220: sub screenname {
                   4221:     my ($uname,$udom)=@_;
1.258     albertel 4222:     if ($uname eq $env{'user.name'} &&
                   4223: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4224:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4225:     return $names{'screenname'};
1.62      www      4226: }
                   4227: 
1.212     albertel 4228: 
1.802     bisitz   4229: # ------------------------------------------------------------- Confirm Wrapper
                   4230: =pod
                   4231: 
1.1142    raeburn  4232: =item * &confirmwrapper($message)
1.802     bisitz   4233: 
                   4234: Wrap messages about completion of operation in box
                   4235: 
                   4236: =cut
                   4237: 
                   4238: sub confirmwrapper {
                   4239:     my ($message)=@_;
                   4240:     if ($message) {
                   4241:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4242:                .$message."\n"
                   4243:                .'</div>'."\n";
                   4244:     } else {
                   4245:         return $message;
                   4246:     }
                   4247: }
                   4248: 
1.62      www      4249: # ------------------------------------------------------------- Message Wrapper
                   4250: 
                   4251: sub messagewrapper {
1.369     www      4252:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4253:     return 
1.441     albertel 4254:         '<a href="/adm/email?compose=individual&amp;'.
                   4255:         'recname='.$username.'&amp;recdom='.$domain.
                   4256: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4257:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4258: }
1.802     bisitz   4259: 
1.74      www      4260: # --------------------------------------------------------------- Notes Wrapper
                   4261: 
                   4262: sub noteswrapper {
                   4263:     my ($link,$un,$do)=@_;
                   4264:     return 
1.896     amueller 4265: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4266: }
1.802     bisitz   4267: 
1.62      www      4268: # ------------------------------------------------------------- Aboutme Wrapper
                   4269: 
                   4270: sub aboutmewrapper {
1.1070    raeburn  4271:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4272:     if (!defined($username)  && !defined($domain)) {
                   4273:         return;
                   4274:     }
1.1096    raeburn  4275:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4276: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4277: }
                   4278: 
                   4279: # ------------------------------------------------------------ Syllabus Wrapper
                   4280: 
                   4281: sub syllabuswrapper {
1.707     bisitz   4282:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4283:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4284: }
1.14      harris41 4285: 
1.802     bisitz   4286: # -----------------------------------------------------------------------------
                   4287: 
1.208     matthew  4288: sub track_student_link {
1.887     raeburn  4289:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4290:     my $link ="/adm/trackstudent?";
1.208     matthew  4291:     my $title = 'View recent activity';
                   4292:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4293:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4294:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4295:         $title .= ' of this student';
1.268     albertel 4296:     } 
1.208     matthew  4297:     if (defined($target) && $target !~ /^\s*$/) {
                   4298:         $target = qq{target="$target"};
                   4299:     } else {
                   4300:         $target = '';
                   4301:     }
1.268     albertel 4302:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4303:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4304:     $title = &mt($title);
                   4305:     $linktext = &mt($linktext);
1.448     albertel 4306:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4307: 	&help_open_topic('View_recent_activity');
1.208     matthew  4308: }
                   4309: 
1.781     raeburn  4310: sub slot_reservations_link {
                   4311:     my ($linktext,$sname,$sdom,$target) = @_;
                   4312:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4313:     my $title = 'View slot reservation history';
                   4314:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4315:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4316:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4317:         $title .= ' of this student';
                   4318:     }
                   4319:     if (defined($target) && $target !~ /^\s*$/) {
                   4320:         $target = qq{target="$target"};
                   4321:     } else {
                   4322:         $target = '';
                   4323:     }
                   4324:     $title = &mt($title);
                   4325:     $linktext = &mt($linktext);
                   4326:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4327: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4328: 
                   4329: }
                   4330: 
1.508     www      4331: # ===================================================== Display a student photo
                   4332: 
                   4333: 
1.509     albertel 4334: sub student_image_tag {
1.508     www      4335:     my ($domain,$user)=@_;
                   4336:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4337:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4338: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4339:     } else {
                   4340: 	return '';
                   4341:     }
                   4342: }
                   4343: 
1.112     bowersj2 4344: =pod
                   4345: 
                   4346: =back
                   4347: 
                   4348: =head1 Access .tab File Data
                   4349: 
                   4350: =over 4
                   4351: 
1.648     raeburn  4352: =item * &languageids() 
1.112     bowersj2 4353: 
                   4354: returns list of all language ids
                   4355: 
                   4356: =cut
                   4357: 
1.14      harris41 4358: sub languageids {
1.16      harris41 4359:     return sort(keys(%language));
1.14      harris41 4360: }
                   4361: 
1.112     bowersj2 4362: =pod
                   4363: 
1.648     raeburn  4364: =item * &languagedescription() 
1.112     bowersj2 4365: 
                   4366: returns description of a specified language id
                   4367: 
                   4368: =cut
                   4369: 
1.14      harris41 4370: sub languagedescription {
1.125     www      4371:     my $code=shift;
                   4372:     return  ($supported_language{$code}?'* ':'').
                   4373:             $language{$code}.
1.126     www      4374: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4375: }
                   4376: 
1.1048    foxr     4377: =pod
                   4378: 
                   4379: =item * &plainlanguagedescription
                   4380: 
                   4381: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4382: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4383: 
                   4384: =cut
                   4385: 
1.145     www      4386: sub plainlanguagedescription {
                   4387:     my $code=shift;
                   4388:     return $language{$code};
                   4389: }
                   4390: 
1.1048    foxr     4391: =pod
                   4392: 
                   4393: =item * &supportedlanguagecode
                   4394: 
                   4395: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4396: code.
                   4397: 
                   4398: =cut
                   4399: 
1.145     www      4400: sub supportedlanguagecode {
                   4401:     my $code=shift;
                   4402:     return $supported_language{$code};
1.97      www      4403: }
                   4404: 
1.112     bowersj2 4405: =pod
                   4406: 
1.1048    foxr     4407: =item * &latexlanguage()
                   4408: 
                   4409: Given a language key code returns the correspondnig language to use
                   4410: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4411: is no supported hyphenation for the language code.
                   4412: 
                   4413: =cut
                   4414: 
                   4415: sub latexlanguage {
                   4416:     my $code = shift;
                   4417:     return $latex_language{$code};
                   4418: }
                   4419: 
                   4420: =pod
                   4421: 
                   4422: =item * &latexhyphenation()
                   4423: 
                   4424: Same as above but what's supplied is the language as it might be stored
                   4425: in the metadata.
                   4426: 
                   4427: =cut
                   4428: 
                   4429: sub latexhyphenation {
                   4430:     my $key = shift;
                   4431:     return $latex_language_bykey{$key};
                   4432: }
                   4433: 
                   4434: =pod
                   4435: 
1.648     raeburn  4436: =item * &copyrightids() 
1.112     bowersj2 4437: 
                   4438: returns list of all copyrights
                   4439: 
                   4440: =cut
                   4441: 
                   4442: sub copyrightids {
                   4443:     return sort(keys(%cprtag));
                   4444: }
                   4445: 
                   4446: =pod
                   4447: 
1.648     raeburn  4448: =item * &copyrightdescription() 
1.112     bowersj2 4449: 
                   4450: returns description of a specified copyright id
                   4451: 
                   4452: =cut
                   4453: 
                   4454: sub copyrightdescription {
1.166     www      4455:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4456: }
1.197     matthew  4457: 
                   4458: =pod
                   4459: 
1.648     raeburn  4460: =item * &source_copyrightids() 
1.192     taceyjo1 4461: 
                   4462: returns list of all source copyrights
                   4463: 
                   4464: =cut
                   4465: 
                   4466: sub source_copyrightids {
                   4467:     return sort(keys(%scprtag));
                   4468: }
                   4469: 
                   4470: =pod
                   4471: 
1.648     raeburn  4472: =item * &source_copyrightdescription() 
1.192     taceyjo1 4473: 
                   4474: returns description of a specified source copyright id
                   4475: 
                   4476: =cut
                   4477: 
                   4478: sub source_copyrightdescription {
                   4479:     return &mt($scprtag{shift(@_)});
                   4480: }
1.112     bowersj2 4481: 
                   4482: =pod
                   4483: 
1.648     raeburn  4484: =item * &filecategories() 
1.112     bowersj2 4485: 
                   4486: returns list of all file categories
                   4487: 
                   4488: =cut
                   4489: 
                   4490: sub filecategories {
                   4491:     return sort(keys(%category_extensions));
                   4492: }
                   4493: 
                   4494: =pod
                   4495: 
1.648     raeburn  4496: =item * &filecategorytypes() 
1.112     bowersj2 4497: 
                   4498: returns list of file types belonging to a given file
                   4499: category
                   4500: 
                   4501: =cut
                   4502: 
                   4503: sub filecategorytypes {
1.356     albertel 4504:     my ($cat) = @_;
1.1248    raeburn  4505:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4506:         return @{$category_extensions{lc($cat)}};
                   4507:     } else {
                   4508:         return ();
                   4509:     }
1.112     bowersj2 4510: }
                   4511: 
                   4512: =pod
                   4513: 
1.648     raeburn  4514: =item * &fileembstyle() 
1.112     bowersj2 4515: 
                   4516: returns embedding style for a specified file type
                   4517: 
                   4518: =cut
                   4519: 
                   4520: sub fileembstyle {
                   4521:     return $fe{lc(shift(@_))};
1.169     www      4522: }
                   4523: 
1.351     www      4524: sub filemimetype {
                   4525:     return $fm{lc(shift(@_))};
                   4526: }
                   4527: 
1.169     www      4528: 
                   4529: sub filecategoryselect {
                   4530:     my ($name,$value)=@_;
1.189     matthew  4531:     return &select_form($value,$name,
1.970     raeburn  4532:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4533: }
                   4534: 
                   4535: =pod
                   4536: 
1.648     raeburn  4537: =item * &filedescription() 
1.112     bowersj2 4538: 
                   4539: returns description for a specified file type
                   4540: 
                   4541: =cut
                   4542: 
                   4543: sub filedescription {
1.188     matthew  4544:     my $file_description = $fd{lc(shift())};
                   4545:     $file_description =~ s:([\[\]]):~$1:g;
                   4546:     return &mt($file_description);
1.112     bowersj2 4547: }
                   4548: 
                   4549: =pod
                   4550: 
1.648     raeburn  4551: =item * &filedescriptionex() 
1.112     bowersj2 4552: 
                   4553: returns description for a specified file type with
                   4554: extra formatting
                   4555: 
                   4556: =cut
                   4557: 
                   4558: sub filedescriptionex {
                   4559:     my $ex=shift;
1.188     matthew  4560:     my $file_description = $fd{lc($ex)};
                   4561:     $file_description =~ s:([\[\]]):~$1:g;
                   4562:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4563: }
                   4564: 
                   4565: # End of .tab access
                   4566: =pod
                   4567: 
                   4568: =back
                   4569: 
                   4570: =cut
                   4571: 
                   4572: # ------------------------------------------------------------------ File Types
                   4573: sub fileextensions {
                   4574:     return sort(keys(%fe));
                   4575: }
                   4576: 
1.97      www      4577: # ----------------------------------------------------------- Display Languages
                   4578: # returns a hash with all desired display languages
                   4579: #
                   4580: 
                   4581: sub display_languages {
                   4582:     my %languages=();
1.695     raeburn  4583:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4584: 	$languages{$lang}=1;
1.97      www      4585:     }
                   4586:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4587:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4588: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4589: 	    $languages{$lang}=1;
1.97      www      4590:         }
                   4591:     }
                   4592:     return %languages;
1.14      harris41 4593: }
                   4594: 
1.582     albertel 4595: sub languages {
                   4596:     my ($possible_langs) = @_;
1.695     raeburn  4597:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4598:     if (!ref($possible_langs)) {
                   4599: 	if( wantarray ) {
                   4600: 	    return @preferred_langs;
                   4601: 	} else {
                   4602: 	    return $preferred_langs[0];
                   4603: 	}
                   4604:     }
                   4605:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4606:     my @preferred_possibilities;
                   4607:     foreach my $preferred_lang (@preferred_langs) {
                   4608: 	if (exists($possibilities{$preferred_lang})) {
                   4609: 	    push(@preferred_possibilities, $preferred_lang);
                   4610: 	}
                   4611:     }
                   4612:     if( wantarray ) {
                   4613: 	return @preferred_possibilities;
                   4614:     }
                   4615:     return $preferred_possibilities[0];
                   4616: }
                   4617: 
1.742     raeburn  4618: sub user_lang {
                   4619:     my ($touname,$toudom,$fromcid) = @_;
                   4620:     my @userlangs;
                   4621:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4622:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4623:                     $env{'course.'.$fromcid.'.languages'}));
                   4624:     } else {
                   4625:         my %langhash = &getlangs($touname,$toudom);
                   4626:         if ($langhash{'languages'} ne '') {
                   4627:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4628:         } else {
                   4629:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4630:             if ($domdefs{'lang_def'} ne '') {
                   4631:                 @userlangs = ($domdefs{'lang_def'});
                   4632:             }
                   4633:         }
                   4634:     }
                   4635:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4636:     my $user_lh = Apache::localize->get_handle(@languages);
                   4637:     return $user_lh;
                   4638: }
                   4639: 
                   4640: 
1.112     bowersj2 4641: ###############################################################
                   4642: ##               Student Answer Attempts                     ##
                   4643: ###############################################################
                   4644: 
                   4645: =pod
                   4646: 
                   4647: =head1 Alternate Problem Views
                   4648: 
                   4649: =over 4
                   4650: 
1.648     raeburn  4651: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4652:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4653: 
                   4654: Return string with previous attempt on problem. Arguments:
                   4655: 
                   4656: =over 4
                   4657: 
                   4658: =item * $symb: Problem, including path
                   4659: 
                   4660: =item * $username: username of the desired student
                   4661: 
                   4662: =item * $domain: domain of the desired student
1.14      harris41 4663: 
1.112     bowersj2 4664: =item * $course: Course ID
1.14      harris41 4665: 
1.112     bowersj2 4666: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4667:     something
1.14      harris41 4668: 
1.112     bowersj2 4669: =item * $regexp: if string matches this regexp, the string will be
                   4670:     sent to $gradesub
1.14      harris41 4671: 
1.112     bowersj2 4672: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4673: 
1.1199    raeburn  4674: =item * $usec: section of the desired student
                   4675: 
                   4676: =item * $identifier: counter for student (multiple students one problem) or 
                   4677:     problem (one student; whole sequence).
                   4678: 
1.112     bowersj2 4679: =back
1.14      harris41 4680: 
1.112     bowersj2 4681: The output string is a table containing all desired attempts, if any.
1.16      harris41 4682: 
1.112     bowersj2 4683: =cut
1.1       albertel 4684: 
                   4685: sub get_previous_attempt {
1.1199    raeburn  4686:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4687:   my $prevattempts='';
1.43      ng       4688:   no strict 'refs';
1.1       albertel 4689:   if ($symb) {
1.3       albertel 4690:     my (%returnhash)=
                   4691:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4692:     if ($returnhash{'version'}) {
                   4693:       my %lasthash=();
                   4694:       my $version;
                   4695:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4696:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4697:             if ($key =~ /\.rawrndseed$/) {
                   4698:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4699:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4700:             } else {
                   4701:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4702:             }
1.19      harris41 4703:         }
1.1       albertel 4704:       }
1.596     albertel 4705:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4706:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4707:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4708:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4709:       foreach my $key (sort(keys(%lasthash))) {
                   4710: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4711: 	if ($#parts > 0) {
1.31      albertel 4712: 	  my $data=$parts[-1];
1.989     raeburn  4713:           next if ($data eq 'foilorder');
1.31      albertel 4714: 	  pop(@parts);
1.1010    www      4715:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4716:           if ($data eq 'type') {
                   4717:               unless ($showsurv) {
                   4718:                   my $id = join(',',@parts);
                   4719:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4720:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4721:                       $lasthidden{$ign.'.'.$id} = 1;
                   4722:                   }
1.945     raeburn  4723:               }
1.1199    raeburn  4724:               if ($identifier ne '') {
                   4725:                   my $id = join(',',@parts);
                   4726:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4727:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4728:                       $hidestatus{$ign.'.'.$id} = 1;
                   4729:                   }
                   4730:               }
                   4731:           } elsif ($data eq 'regrader') {
                   4732:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4733:                   my $id = join(',',@parts);
                   4734:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4735:               }
1.1010    www      4736:           } 
1.31      albertel 4737: 	} else {
1.41      ng       4738: 	  if ($#parts == 0) {
                   4739: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4740: 	  } else {
                   4741: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4742: 	  }
1.31      albertel 4743: 	}
1.16      harris41 4744:       }
1.596     albertel 4745:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4746:       if ($getattempt eq '') {
1.1199    raeburn  4747:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4748:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4749:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4750:                 foreach my $id (keys(%regraded)) {
                   4751:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4752:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4753:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4754:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4755:                     }
                   4756:                 }
                   4757:             }
1.1200    raeburn  4758:         }
                   4759: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4760:             my (@hidden,@unsolved);
1.945     raeburn  4761:             if (%typeparts) {
                   4762:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4763:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4764:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4765:                         push(@hidden,$id);
1.1199    raeburn  4766:                     } elsif ($identifier ne '') {
                   4767:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4768:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4769:                                 ($hidestatus{$id})) {
1.1200    raeburn  4770:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4771:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4772:                                 push(@{$solved{$id}},$version);
                   4773:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4774:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4775:                                 my $skip;
                   4776:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4777:                                     foreach my $reset (@{$resets{$id}}) {
                   4778:                                         if ($reset > $solved{$id}[-1]) {
                   4779:                                             $skip=1;
                   4780:                                             last;
                   4781:                                         }
                   4782:                                     }
                   4783:                                 }
                   4784:                                 unless ($skip) {
                   4785:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4786:                                     push(@unsolved,$partslist);
                   4787:                                 }
                   4788:                             }
                   4789:                         }
1.945     raeburn  4790:                     }
                   4791:                 }
                   4792:             }
                   4793:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4794:                            '<td>'.&mt('Transaction [_1]',$version);
                   4795:             if (@unsolved) {
                   4796:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4797:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4798:                                  &mt('Hide').'</label></span>';
                   4799:             }
                   4800:             $prevattempts .= '</td>';
1.945     raeburn  4801:             if (@hidden) {
                   4802:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4803:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4804:                     my $hide;
                   4805:                     foreach my $id (@hidden) {
                   4806:                         if ($key =~ /^\Q$id\E/) {
                   4807:                             $hide = 1;
                   4808:                             last;
                   4809:                         }
                   4810:                     }
                   4811:                     if ($hide) {
                   4812:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4813:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4814:                             my $value = &format_previous_attempt_value($key,
                   4815:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4816:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4817:                         } else {
                   4818:                             $prevattempts.='<td>&nbsp;</td>';
                   4819:                         }
                   4820:                     } else {
                   4821:                         if ($key =~ /\./) {
1.1212    raeburn  4822:                             my $value = $returnhash{$version.':'.$key};
                   4823:                             if ($key =~ /\.rndseed$/) {
                   4824:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4825:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4826:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4827:                                 }
                   4828:                             }
                   4829:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4830:                                            '&nbsp;</td>';
1.945     raeburn  4831:                         } else {
                   4832:                             $prevattempts.='<td>&nbsp;</td>';
                   4833:                         }
                   4834:                     }
                   4835:                 }
                   4836:             } else {
                   4837: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4838:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4839:                     my $value = $returnhash{$version.':'.$key};
                   4840:                     if ($key =~ /\.rndseed$/) {
                   4841:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4842:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4843:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4844:                         }
                   4845:                     }
                   4846:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4847:                                    '&nbsp;</td>';
1.945     raeburn  4848: 	        }
                   4849:             }
                   4850: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4851: 	 }
1.1       albertel 4852:       }
1.945     raeburn  4853:       my @currhidden = keys(%lasthidden);
1.596     albertel 4854:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4855:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4856:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4857:           if (%typeparts) {
                   4858:               my $hidden;
                   4859:               foreach my $id (@currhidden) {
                   4860:                   if ($key =~ /^\Q$id\E/) {
                   4861:                       $hidden = 1;
                   4862:                       last;
                   4863:                   }
                   4864:               }
                   4865:               if ($hidden) {
                   4866:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4867:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4868:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4869:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4870:                           $value = &$gradesub($value);
                   4871:                       }
1.1173    kruse    4872:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4873:                   } else {
                   4874:                       $prevattempts.='<td>&nbsp;</td>';
                   4875:                   }
                   4876:               } else {
                   4877:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4878:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4879:                       $value = &$gradesub($value);
                   4880:                   }
1.1173    kruse    4881:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4882:               }
                   4883:           } else {
                   4884: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4885: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4886:                   $value = &$gradesub($value);
                   4887:               }
1.1173    kruse    4888: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4889:           }
1.16      harris41 4890:       }
1.596     albertel 4891:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4892:     } else {
1.1305    raeburn  4893:       my $msg;
                   4894:       if ($symb =~ /ext\.tool$/) {
                   4895:           $msg = &mt('No grade passed back.');
                   4896:       } else {
                   4897:           $msg = &mt('Nothing submitted - no attempts.');
                   4898:       }
1.596     albertel 4899:       $prevattempts=
                   4900: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4901: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4902: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4903:     }
                   4904:   } else {
1.596     albertel 4905:     $prevattempts=
                   4906: 	  &start_data_table().&start_data_table_row().
                   4907: 	  '<td>'.&mt('No data.').'</td>'.
                   4908: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4909:   }
1.10      albertel 4910: }
                   4911: 
1.581     albertel 4912: sub format_previous_attempt_value {
                   4913:     my ($key,$value) = @_;
1.1011    www      4914:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4915:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4916:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4917:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4918:     } elsif ($key =~ /answerstring$/) {
                   4919:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4920:         my @answer = %answers;
                   4921:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4922:         my @anskeys = sort(keys(%answers));
                   4923:         if (@anskeys == 1) {
                   4924:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4925:             if ($answer =~ m{\0}) {
                   4926:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4927:             }
                   4928:             my $tag_internal_answer_name = 'INTERNAL';
                   4929:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4930:                 $value = $answer; 
                   4931:             } else {
                   4932:                 $value = $anskeys[0].'='.$answer;
                   4933:             }
                   4934:         } else {
                   4935:             foreach my $ans (@anskeys) {
                   4936:                 my $answer = $answers{$ans};
1.1001    raeburn  4937:                 if ($answer =~ m{\0}) {
                   4938:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4939:                 }
                   4940:                 $value .=  $ans.'='.$answer.'<br />';;
                   4941:             } 
                   4942:         }
1.581     albertel 4943:     } else {
1.1173    kruse    4944:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4945:     }
                   4946:     return $value;
                   4947: }
                   4948: 
                   4949: 
1.107     albertel 4950: sub relative_to_absolute {
                   4951:     my ($url,$output)=@_;
                   4952:     my $parser=HTML::TokeParser->new(\$output);
                   4953:     my $token;
                   4954:     my $thisdir=$url;
                   4955:     my @rlinks=();
                   4956:     while ($token=$parser->get_token) {
                   4957: 	if ($token->[0] eq 'S') {
                   4958: 	    if ($token->[1] eq 'a') {
                   4959: 		if ($token->[2]->{'href'}) {
                   4960: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4961: 		}
                   4962: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4963: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4964: 	    } elsif ($token->[1] eq 'base') {
                   4965: 		$thisdir=$token->[2]->{'href'};
                   4966: 	    }
                   4967: 	}
                   4968:     }
                   4969:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4970:     foreach my $link (@rlinks) {
1.726     raeburn  4971: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4972: 		($link=~/^\//) ||
                   4973: 		($link=~/^javascript:/i) ||
                   4974: 		($link=~/^mailto:/i) ||
                   4975: 		($link=~/^\#/)) {
                   4976: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4977: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4978: 	}
                   4979:     }
                   4980: # -------------------------------------------------- Deal with Applet codebases
                   4981:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4982:     return $output;
                   4983: }
                   4984: 
1.112     bowersj2 4985: =pod
                   4986: 
1.648     raeburn  4987: =item * &get_student_view()
1.112     bowersj2 4988: 
                   4989: show a snapshot of what student was looking at
                   4990: 
                   4991: =cut
                   4992: 
1.10      albertel 4993: sub get_student_view {
1.186     albertel 4994:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4995:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4996:   my (%form);
1.10      albertel 4997:   my @elements=('symb','courseid','domain','username');
                   4998:   foreach my $element (@elements) {
1.186     albertel 4999:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5000:   }
1.186     albertel 5001:   if (defined($moreenv)) {
                   5002:       %form=(%form,%{$moreenv});
                   5003:   }
1.236     albertel 5004:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5005:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5006:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5007:       $feedurl =~ s{^/adm/wrapper}{};
                   5008:   }
1.650     www      5009:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5010:   $userview=~s/\<body[^\>]*\>//gi;
                   5011:   $userview=~s/\<\/body\>//gi;
                   5012:   $userview=~s/\<html\>//gi;
                   5013:   $userview=~s/\<\/html\>//gi;
                   5014:   $userview=~s/\<head\>//gi;
                   5015:   $userview=~s/\<\/head\>//gi;
                   5016:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5017:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5018:   if (wantarray) {
                   5019:      return ($userview,$response);
                   5020:   } else {
                   5021:      return $userview;
                   5022:   }
                   5023: }
                   5024: 
                   5025: sub get_student_view_with_retries {
                   5026:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5027: 
                   5028:     my $ok = 0;                 # True if we got a good response.
                   5029:     my $content;
                   5030:     my $response;
                   5031: 
                   5032:     # Try to get the student_view done. within the retries count:
                   5033:     
                   5034:     do {
                   5035:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5036:          $ok      = $response->is_success;
                   5037:          if (!$ok) {
                   5038:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5039:          }
                   5040:          $retries--;
                   5041:     } while (!$ok && ($retries > 0));
                   5042:     
                   5043:     if (!$ok) {
                   5044:        $content = '';          # On error return an empty content.
                   5045:     }
1.651     www      5046:     if (wantarray) {
                   5047:        return ($content, $response);
                   5048:     } else {
                   5049:        return $content;
                   5050:     }
1.11      albertel 5051: }
                   5052: 
1.1349    raeburn  5053: sub css_links {
                   5054:     my ($currsymb,$level) = @_;
                   5055:     my ($links,@symbs,%cssrefs,%httpref);
                   5056:     if ($level eq 'map') {
                   5057:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5058:         if (ref($navmap)) {
                   5059:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5060:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5061:             foreach my $res (@resources) {
                   5062:                 if (ref($res) && $res->symb()) {
                   5063:                     push(@symbs,$res->symb());
                   5064:                 }
                   5065:             }
                   5066:         }
                   5067:     } else {
                   5068:         @symbs = ($currsymb);
                   5069:     }
                   5070:     foreach my $symb (@symbs) {
                   5071:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5072:         if ($css_href =~ /\S/) {
                   5073:             unless ($css_href =~ m{https?://}) {
                   5074:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5075:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5076:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5077:                 unless ($css_href =~ m{^/}) {
                   5078:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5079:                 }
                   5080:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5081:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5082:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5083:                         my $thisurl = $proburl;
                   5084:                         if ($env{'httpref.'.$proburl}) {
                   5085:                             $thisurl = $env{'httpref.'.$proburl};
                   5086:                         }
                   5087:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5088:                     }
                   5089:                 }
                   5090:             }
                   5091:             $cssrefs{$css_href} = 1;
                   5092:         }
                   5093:     }
                   5094:     if (keys(%httpref)) {
                   5095:         &Apache::lonnet::appenv(\%httpref);
                   5096:     }
                   5097:     if (keys(%cssrefs)) {
                   5098:         foreach my $css_href (keys(%cssrefs)) {
                   5099:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5100:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5101:         }
                   5102:     }
                   5103:     return $links;
                   5104: }
                   5105: 
1.112     bowersj2 5106: =pod
                   5107: 
1.648     raeburn  5108: =item * &get_student_answers() 
1.112     bowersj2 5109: 
                   5110: show a snapshot of how student was answering problem
                   5111: 
                   5112: =cut
                   5113: 
1.11      albertel 5114: sub get_student_answers {
1.100     sakharuk 5115:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5116:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5117:   my (%moreenv);
1.11      albertel 5118:   my @elements=('symb','courseid','domain','username');
                   5119:   foreach my $element (@elements) {
1.186     albertel 5120:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5121:   }
1.186     albertel 5122:   $moreenv{'grade_target'}='answer';
                   5123:   %moreenv=(%form,%moreenv);
1.497     raeburn  5124:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5125:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5126:   return $userview;
1.1       albertel 5127: }
1.116     albertel 5128: 
                   5129: =pod
                   5130: 
                   5131: =item * &submlink()
                   5132: 
1.242     albertel 5133: Inputs: $text $uname $udom $symb $target
1.116     albertel 5134: 
                   5135: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5136: 
                   5137: =cut
                   5138: 
                   5139: ###############################################
                   5140: sub submlink {
1.242     albertel 5141:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5142:     if (!($uname && $udom)) {
                   5143: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5144: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5145: 	if (!$symb) { $symb=$cursymb; }
                   5146:     }
1.254     matthew  5147:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5148:     $symb=&escape($symb);
1.960     bisitz   5149:     if ($target) { $target=" target=\"$target\""; }
                   5150:     return
                   5151:         '<a href="/adm/grades?command=submission'.
                   5152:         '&amp;symb='.$symb.
                   5153:         '&amp;student='.$uname.
                   5154:         '&amp;userdom='.$udom.'"'.
                   5155:         $target.'>'.$text.'</a>';
1.242     albertel 5156: }
                   5157: ##############################################
                   5158: 
                   5159: =pod
                   5160: 
                   5161: =item * &pgrdlink()
                   5162: 
                   5163: Inputs: $text $uname $udom $symb $target
                   5164: 
                   5165: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5166: 
                   5167: =cut
                   5168: 
                   5169: ###############################################
                   5170: sub pgrdlink {
                   5171:     my $link=&submlink(@_);
                   5172:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5173:     return $link;
                   5174: }
                   5175: ##############################################
                   5176: 
                   5177: =pod
                   5178: 
                   5179: =item * &pprmlink()
                   5180: 
                   5181: Inputs: $text $uname $udom $symb $target
                   5182: 
                   5183: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5184: student and a specific resource
1.242     albertel 5185: 
                   5186: =cut
                   5187: 
                   5188: ###############################################
                   5189: sub pprmlink {
                   5190:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5191:     if (!($uname && $udom)) {
                   5192: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5193: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5194: 	if (!$symb) { $symb=$cursymb; }
                   5195:     }
1.254     matthew  5196:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5197:     $symb=&escape($symb);
1.242     albertel 5198:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5199:     return '<a href="/adm/parmset?command=set&amp;'.
                   5200: 	'symb='.$symb.'&amp;uname='.$uname.
                   5201: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5202: }
                   5203: ##############################################
1.37      matthew  5204: 
1.112     bowersj2 5205: =pod
                   5206: 
                   5207: =back
                   5208: 
                   5209: =cut
                   5210: 
1.37      matthew  5211: ###############################################
1.51      www      5212: 
                   5213: 
                   5214: sub timehash {
1.687     raeburn  5215:     my ($thistime) = @_;
                   5216:     my $timezone = &Apache::lonlocal::gettimezone();
                   5217:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5218:                      ->set_time_zone($timezone);
                   5219:     my $wday = $dt->day_of_week();
                   5220:     if ($wday == 7) { $wday = 0; }
                   5221:     return ( 'second' => $dt->second(),
                   5222:              'minute' => $dt->minute(),
                   5223:              'hour'   => $dt->hour(),
                   5224:              'day'     => $dt->day_of_month(),
                   5225:              'month'   => $dt->month(),
                   5226:              'year'    => $dt->year(),
                   5227:              'weekday' => $wday,
                   5228:              'dayyear' => $dt->day_of_year(),
                   5229:              'dlsav'   => $dt->is_dst() );
1.51      www      5230: }
                   5231: 
1.370     www      5232: sub utc_string {
                   5233:     my ($date)=@_;
1.371     www      5234:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5235: }
                   5236: 
1.51      www      5237: sub maketime {
                   5238:     my %th=@_;
1.687     raeburn  5239:     my ($epoch_time,$timezone,$dt);
                   5240:     $timezone = &Apache::lonlocal::gettimezone();
                   5241:     eval {
                   5242:         $dt = DateTime->new( year   => $th{'year'},
                   5243:                              month  => $th{'month'},
                   5244:                              day    => $th{'day'},
                   5245:                              hour   => $th{'hour'},
                   5246:                              minute => $th{'minute'},
                   5247:                              second => $th{'second'},
                   5248:                              time_zone => $timezone,
                   5249:                          );
                   5250:     };
                   5251:     if (!$@) {
                   5252:         $epoch_time = $dt->epoch;
                   5253:         if ($epoch_time) {
                   5254:             return $epoch_time;
                   5255:         }
                   5256:     }
1.51      www      5257:     return POSIX::mktime(
                   5258:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5259:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5260: }
                   5261: 
                   5262: #########################################
1.51      www      5263: 
                   5264: sub findallcourses {
1.482     raeburn  5265:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5266:     my %roles;
                   5267:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5268:     my %courses;
1.51      www      5269:     my $now=time;
1.482     raeburn  5270:     if (!defined($uname)) {
                   5271:         $uname = $env{'user.name'};
                   5272:     }
                   5273:     if (!defined($udom)) {
                   5274:         $udom = $env{'user.domain'};
                   5275:     }
                   5276:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5277:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5278:         if (!%roles) {
                   5279:             %roles = (
                   5280:                        cc => 1,
1.907     raeburn  5281:                        co => 1,
1.482     raeburn  5282:                        in => 1,
                   5283:                        ep => 1,
                   5284:                        ta => 1,
                   5285:                        cr => 1,
                   5286:                        st => 1,
                   5287:              );
                   5288:         }
                   5289:         foreach my $entry (keys(%roleshash)) {
                   5290:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5291:             if ($trole =~ /^cr/) { 
                   5292:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5293:             } else {
                   5294:                 next if (!exists($roles{$trole}));
                   5295:             }
                   5296:             if ($tend) {
                   5297:                 next if ($tend < $now);
                   5298:             }
                   5299:             if ($tstart) {
                   5300:                 next if ($tstart > $now);
                   5301:             }
1.1058    raeburn  5302:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5303:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5304:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5305:             if ($secpart eq '') {
                   5306:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5307:                 $sec = 'none';
1.1058    raeburn  5308:                 $value .= $cnum.'/';
1.482     raeburn  5309:             } else {
                   5310:                 $cnum = $cnumpart;
                   5311:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5312:                 $value .= $cnum.'/'.$sec;
                   5313:             }
                   5314:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5315:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5316:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5317:                 }
                   5318:             } else {
                   5319:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5320:             }
1.482     raeburn  5321:         }
                   5322:     } else {
                   5323:         foreach my $key (keys(%env)) {
1.483     albertel 5324: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5325:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5326: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5327: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5328: 	        next if (%roles && !exists($roles{$role}));
                   5329: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5330:                 my $active=1;
                   5331:                 if ($starttime) {
                   5332: 		    if ($now<$starttime) { $active=0; }
                   5333:                 }
                   5334:                 if ($endtime) {
                   5335:                     if ($now>$endtime) { $active=0; }
                   5336:                 }
                   5337:                 if ($active) {
1.1058    raeburn  5338:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5339:                     if ($sec eq '') {
                   5340:                         $sec = 'none';
1.1058    raeburn  5341:                     } else {
                   5342:                         $value .= $sec;
                   5343:                     }
                   5344:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5345:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5346:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5347:                         }
                   5348:                     } else {
                   5349:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5350:                     }
1.474     raeburn  5351:                 }
                   5352:             }
1.51      www      5353:         }
                   5354:     }
1.474     raeburn  5355:     return %courses;
1.51      www      5356: }
1.37      matthew  5357: 
1.54      www      5358: ###############################################
1.474     raeburn  5359: 
                   5360: sub blockcheck {
1.1372    raeburn  5361:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5362:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5363:         my ($has_evb,$check_ipaccess);
                   5364:         my $dom = $env{'user.domain'};
                   5365:         if ($env{'request.course.id'}) {
                   5366:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5367:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5368:             my $checkrole = "cm./$cdom/$cnum";
                   5369:             my $sec = $env{'request.course.sec'};
                   5370:             if ($sec ne '') {
                   5371:                 $checkrole .= "/$sec";
                   5372:             }
                   5373:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5374:                 ($env{'request.role'} !~ /^st/)) {
                   5375:                 $has_evb = 1;
                   5376:             }
                   5377:             unless ($has_evb) {
                   5378:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5379:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5380:                     if ($udom eq $cdom) {
                   5381:                         $check_ipaccess = 1;
                   5382:                     }
                   5383:                 }
                   5384:             }
1.1375    raeburn  5385:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5386:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5387:             my $checkrole;
                   5388:             if ($env{'request.role.domain'} eq '') {
                   5389:                 $checkrole = "cm./$env{'user.domain'}/";
                   5390:             } else {
                   5391:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5392:             }
                   5393:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5394:                 $has_evb = 1;
                   5395:             }
1.1372    raeburn  5396:         }
                   5397:         unless ($has_evb || $check_ipaccess) {
                   5398:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5399:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5400:                 $dom = $udom;
                   5401:             }
                   5402:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5403:                 $check_ipaccess = 1;
                   5404:             } else {
                   5405:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5406:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5407:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5408:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5409:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5410:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5411:                         $check_ipaccess = 1;
                   5412:                     }
                   5413:                 }
                   5414:             }
                   5415:         }
                   5416:         if ($check_ipaccess) {
                   5417:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5418:             unless (defined($cached)) {
                   5419:                 my %domconfig =
                   5420:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5421:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5422:             }
                   5423:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5424:                 foreach my $id (keys(%{$ipaccessref})) {
                   5425:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5426:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5427:                         if ($range) {
                   5428:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5429:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5430:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5431:                                         return ('','','',$id,$dom);
                   5432:                                         last;
                   5433:                                     }
                   5434:                                 }
                   5435:                             }
                   5436:                         }
                   5437:                     }
                   5438:                 }
                   5439:             }
                   5440:         }
1.1373    raeburn  5441:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5442:             return ();
                   5443:         }
1.1372    raeburn  5444:     }
1.1189    raeburn  5445:     if (defined($udom) && defined($uname)) {
                   5446:         # If uname and udom are for a course, check for blocks in the course.
                   5447:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5448:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5449:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5450:             return ($startblock,$endblock,$triggerblock);
                   5451:         }
                   5452:     } else {
1.490     raeburn  5453:         $udom = $env{'user.domain'};
                   5454:         $uname = $env{'user.name'};
                   5455:     }
                   5456: 
1.502     raeburn  5457:     my $startblock = 0;
                   5458:     my $endblock = 0;
1.1062    raeburn  5459:     my $triggerblock = '';
1.1373    raeburn  5460:     my %live_courses;
                   5461:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5462:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5463:     }
1.474     raeburn  5464: 
1.490     raeburn  5465:     # If uname is for a user, and activity is course-specific, i.e.,
                   5466:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5467: 
1.490     raeburn  5468:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5469:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5470:          $activity eq 'search' || $activity eq 'reinit' ||
                   5471:          $activity eq 'alert') &&
1.1189    raeburn  5472:         ($env{'request.course.id'})) {
1.490     raeburn  5473:         foreach my $key (keys(%live_courses)) {
                   5474:             if ($key ne $env{'request.course.id'}) {
                   5475:                 delete($live_courses{$key});
                   5476:             }
                   5477:         }
                   5478:     }
                   5479: 
                   5480:     my $otheruser = 0;
                   5481:     my %own_courses;
                   5482:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5483:         # Resource belongs to user other than current user.
                   5484:         $otheruser = 1;
                   5485:         # Gather courses for current user
                   5486:         %own_courses = 
                   5487:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5488:     }
                   5489: 
                   5490:     # Gather active course roles - course coordinator, instructor, 
                   5491:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5492: 
                   5493:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5494:         my ($cdom,$cnum);
                   5495:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5496:             $cdom = $env{'course.'.$course.'.domain'};
                   5497:             $cnum = $env{'course.'.$course.'.num'};
                   5498:         } else {
1.490     raeburn  5499:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5500:         }
                   5501:         my $no_ownblock = 0;
                   5502:         my $no_userblock = 0;
1.533     raeburn  5503:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5504:             # Check if current user has 'evb' priv for this
                   5505:             if (defined($own_courses{$course})) {
                   5506:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5507:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5508:                     if ($sec ne 'none') {
                   5509:                         $checkrole .= '/'.$sec;
                   5510:                     }
                   5511:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5512:                         $no_ownblock = 1;
                   5513:                         last;
                   5514:                     }
                   5515:                 }
                   5516:             }
                   5517:             # if they have 'evb' priv and are currently not playing student
                   5518:             next if (($no_ownblock) &&
                   5519:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5520:         }
1.474     raeburn  5521:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5522:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5523:             if ($sec ne 'none') {
1.482     raeburn  5524:                 $checkrole .= '/'.$sec;
1.474     raeburn  5525:             }
1.490     raeburn  5526:             if ($otheruser) {
                   5527:                 # Resource belongs to user other than current user.
                   5528:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5529:                 my (%allroles,%userroles);
                   5530:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5531:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5532:                         my ($trole,$tdom,$tnum,$tsec);
                   5533:                         if ($entry =~ /^cr/) {
                   5534:                             ($trole,$tdom,$tnum,$tsec) = 
                   5535:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5536:                         } else {
                   5537:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5538:                         }
                   5539:                         my ($spec,$area,$trest);
                   5540:                         $area = '/'.$tdom.'/'.$tnum;
                   5541:                         $trest = $tnum;
                   5542:                         if ($tsec ne '') {
                   5543:                             $area .= '/'.$tsec;
                   5544:                             $trest .= '/'.$tsec;
                   5545:                         }
                   5546:                         $spec = $trole.'.'.$area;
                   5547:                         if ($trole =~ /^cr/) {
                   5548:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5549:                                                               $tdom,$spec,$trest,$area);
                   5550:                         } else {
                   5551:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5552:                                                                 $tdom,$spec,$trest,$area);
                   5553:                         }
                   5554:                     }
1.1276    raeburn  5555:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5556:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5557:                         if ($1) {
                   5558:                             $no_userblock = 1;
                   5559:                             last;
                   5560:                         }
1.486     raeburn  5561:                     }
                   5562:                 }
1.490     raeburn  5563:             } else {
                   5564:                 # Resource belongs to current user
                   5565:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5566:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5567:                     $no_ownblock = 1;
                   5568:                     last;
                   5569:                 }
1.474     raeburn  5570:             }
                   5571:         }
                   5572:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5573:         next if (($no_ownblock) &&
1.491     albertel 5574:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5575:         next if ($no_userblock);
1.474     raeburn  5576: 
1.1303    raeburn  5577:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5578:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5579: 
1.1062    raeburn  5580:         my ($start,$end,$trigger) = 
1.1347    raeburn  5581:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5582:         if (($start != 0) && 
                   5583:             (($startblock == 0) || ($startblock > $start))) {
                   5584:             $startblock = $start;
1.1062    raeburn  5585:             if ($trigger ne '') {
                   5586:                 $triggerblock = $trigger;
                   5587:             }
1.502     raeburn  5588:         }
                   5589:         if (($end != 0)  &&
                   5590:             (($endblock == 0) || ($endblock < $end))) {
                   5591:             $endblock = $end;
1.1062    raeburn  5592:             if ($trigger ne '') {
                   5593:                 $triggerblock = $trigger;
                   5594:             }
1.502     raeburn  5595:         }
1.490     raeburn  5596:     }
1.1062    raeburn  5597:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5598: }
                   5599: 
                   5600: sub get_blocks {
1.1347    raeburn  5601:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5602:     my $startblock = 0;
                   5603:     my $endblock = 0;
1.1062    raeburn  5604:     my $triggerblock = '';
1.490     raeburn  5605:     my $course = $cdom.'_'.$cnum;
                   5606:     $setters->{$course} = {};
                   5607:     $setters->{$course}{'staff'} = [];
                   5608:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5609:     $setters->{$course}{'triggers'} = [];
                   5610:     my (@blockers,%triggered);
                   5611:     my $now = time;
                   5612:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5613:     if ($activity eq 'docs') {
1.1348    raeburn  5614:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5615:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5616:             $blocked = 1;
                   5617:             $nosymbcache = 1;
1.1348    raeburn  5618:             $noenccheck = 1;
1.1347    raeburn  5619:         }
1.1348    raeburn  5620:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5621:         foreach my $block (@blockers) {
                   5622:             if ($block =~ /^firstaccess____(.+)$/) {
                   5623:                 my $item = $1;
                   5624:                 my $type = 'map';
                   5625:                 my $timersymb = $item;
                   5626:                 if ($item eq 'course') {
                   5627:                     $type = 'course';
                   5628:                 } elsif ($item =~ /___\d+___/) {
                   5629:                     $type = 'resource';
                   5630:                 } else {
                   5631:                     $timersymb = &Apache::lonnet::symbread($item);
                   5632:                 }
                   5633:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5634:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5635:                 $triggered{$block} = {
                   5636:                                        start => $start,
                   5637:                                        end   => $end,
                   5638:                                        type  => $type,
                   5639:                                      };
                   5640:             }
                   5641:         }
                   5642:     } else {
                   5643:         foreach my $block (keys(%commblocks)) {
                   5644:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5645:                 my ($start,$end) = ($1,$2);
                   5646:                 if ($start <= time && $end >= time) {
                   5647:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5648:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5649:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5650:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5651:                                     push(@blockers,$block);
                   5652:                                 }
                   5653:                             }
                   5654:                         }
                   5655:                     }
                   5656:                 }
                   5657:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5658:                 my $item = $1;
                   5659:                 my $timersymb = $item; 
                   5660:                 my $type = 'map';
                   5661:                 if ($item eq 'course') {
                   5662:                     $type = 'course';
                   5663:                 } elsif ($item =~ /___\d+___/) {
                   5664:                     $type = 'resource';
                   5665:                 } else {
                   5666:                     $timersymb = &Apache::lonnet::symbread($item);
                   5667:                 }
                   5668:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5669:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5670:                 if ($start && $end) {
                   5671:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5672:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5673:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5674:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5675:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5676:                                         push(@blockers,$block);
                   5677:                                         $triggered{$block} = {
                   5678:                                                                start => $start,
                   5679:                                                                end   => $end,
                   5680:                                                                type  => $type,
                   5681:                                                              };
                   5682:                                     }
                   5683:                                 }
                   5684:                             }
1.1062    raeburn  5685:                         }
                   5686:                     }
1.490     raeburn  5687:                 }
1.1062    raeburn  5688:             }
                   5689:         }
                   5690:     }
                   5691:     foreach my $blocker (@blockers) {
                   5692:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5693:             &parse_block_record($commblocks{$blocker});
                   5694:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5695:         my ($start,$end,$triggertype);
                   5696:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5697:             ($start,$end) = ($1,$2);
                   5698:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5699:             $start = $triggered{$blocker}{'start'};
                   5700:             $end = $triggered{$blocker}{'end'};
                   5701:             $triggertype = $triggered{$blocker}{'type'};
                   5702:         }
                   5703:         if ($start) {
                   5704:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5705:             if ($triggertype) {
                   5706:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5707:             } else {
                   5708:                 push(@{$$setters{$course}{'triggers'}},0);
                   5709:             }
                   5710:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5711:                 $startblock = $start;
                   5712:                 if ($triggertype) {
                   5713:                     $triggerblock = $blocker;
1.474     raeburn  5714:                 }
                   5715:             }
1.1062    raeburn  5716:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5717:                $endblock = $end;
                   5718:                if ($triggertype) {
                   5719:                    $triggerblock = $blocker;
                   5720:                }
                   5721:             }
1.474     raeburn  5722:         }
                   5723:     }
1.1062    raeburn  5724:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5725: }
                   5726: 
                   5727: sub parse_block_record {
                   5728:     my ($record) = @_;
                   5729:     my ($setuname,$setudom,$title,$blocks);
                   5730:     if (ref($record) eq 'HASH') {
                   5731:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5732:         $title = &unescape($record->{'event'});
                   5733:         $blocks = $record->{'blocks'};
                   5734:     } else {
                   5735:         my @data = split(/:/,$record,3);
                   5736:         if (scalar(@data) eq 2) {
                   5737:             $title = $data[1];
                   5738:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5739:         } else {
                   5740:             ($setuname,$setudom,$title) = @data;
                   5741:         }
                   5742:         $blocks = { 'com' => 'on' };
                   5743:     }
                   5744:     return ($setuname,$setudom,$title,$blocks);
                   5745: }
                   5746: 
1.854     kalberla 5747: sub blocking_status {
1.1372    raeburn  5748:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5749:     my %setters;
1.890     droeschl 5750: 
1.1061    raeburn  5751: # check for active blocking
1.1372    raeburn  5752:     if ($clientip eq '') {
                   5753:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5754:     }
                   5755:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5756:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5757:     my $blocked = 0;
1.1372    raeburn  5758:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5759:         $blocked = 1;
                   5760:     }
1.890     droeschl 5761: 
1.1061    raeburn  5762: # caller just wants to know whether a block is active
                   5763:     if (!wantarray) { return $blocked; }
                   5764: 
                   5765: # build a link to a popup window containing the details
                   5766:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5767: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5768:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5769:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5770:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5771:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5772:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5773:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5774:         if ($symb) {
                   5775:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5776:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5777:         }
1.1062    raeburn  5778:     }
1.1061    raeburn  5779: 
                   5780:     my $output .= <<'END_MYBLOCK';
                   5781: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5782:     var options = "width=" + w + ",height=" + h + ",";
                   5783:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5784:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5785:     var newWin = window.open(url, wdwName, options);
                   5786:     newWin.focus();
                   5787: }
1.890     droeschl 5788: END_MYBLOCK
1.854     kalberla 5789: 
1.1061    raeburn  5790:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5791:   
1.1061    raeburn  5792:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5793:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5794:     my $class = 'LC_comblock';
1.1062    raeburn  5795:     if ($activity eq 'docs') {
                   5796:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5797:         $class = '';
1.1063    raeburn  5798:     } elsif ($activity eq 'printout') {
                   5799:         $text = &mt('Printing Blocked');
1.1232    raeburn  5800:     } elsif ($activity eq 'passwd') {
                   5801:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5802:     } elsif ($activity eq 'grades') {
                   5803:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5804:     } elsif ($activity eq 'search') {
                   5805:         $text = &mt('Search Blocked');
1.1282    raeburn  5806:     } elsif ($activity eq 'alert') {
                   5807:         $text = &mt('Checking Critical Messages Blocked');
                   5808:     } elsif ($activity eq 'reinit') {
                   5809:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5810:     } elsif ($activity eq 'about') {
                   5811:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5812:     } elsif ($activity eq 'wishlist') {
                   5813:         $text = &mt('Access to Stored Links Blocked');
                   5814:     } elsif ($activity eq 'annotate') {
                   5815:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5816:     }
1.1061    raeburn  5817:     $output .= <<"END_BLOCK";
1.1217    raeburn  5818: <div class='$class'>
1.869     kalberla 5819:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5820:   title='$text'>
                   5821:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5822:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5823:   title='$text'>$text</a>
1.867     kalberla 5824: </div>
                   5825: 
                   5826: END_BLOCK
1.474     raeburn  5827: 
1.1061    raeburn  5828:     return ($blocked, $output);
1.854     kalberla 5829: }
1.490     raeburn  5830: 
1.60      matthew  5831: ###############################################
                   5832: 
1.682     raeburn  5833: sub check_ip_acc {
1.1201    raeburn  5834:     my ($acc,$clientip)=@_;
1.682     raeburn  5835:     &Apache::lonxml::debug("acc is $acc");
                   5836:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5837:         return 1;
                   5838:     }
1.1339    raeburn  5839:     my ($ip,$allowed);
                   5840:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5841:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5842:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5843:     } else {
1.1350    raeburn  5844:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5845:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5846:     }
1.682     raeburn  5847: 
                   5848:     my $name;
1.1219    raeburn  5849:     my %access = (
                   5850:                      allowfrom => 1,
                   5851:                      denyfrom  => 0,
                   5852:                  );
                   5853:     my @allows;
                   5854:     my @denies;
                   5855:     foreach my $item (split(',',$acc)) {
                   5856:         $item =~ s/^\s*//;
                   5857:         $item =~ s/\s*$//;
                   5858:         my $pattern;
                   5859:         if ($item =~ /^\!(.+)$/) {
                   5860:             push(@denies,$1);
                   5861:         } else {
                   5862:             push(@allows,$item);
                   5863:         }
                   5864:    }
                   5865:    my $numdenies = scalar(@denies);
                   5866:    my $numallows = scalar(@allows);
                   5867:    my $count = 0;
                   5868:    foreach my $pattern (@denies,@allows) {
                   5869:         $count ++; 
                   5870:         my $acctype = 'allowfrom';
                   5871:         if ($count <= $numdenies) {
                   5872:             $acctype = 'denyfrom';
                   5873:         }
1.682     raeburn  5874:         if ($pattern =~ /\*$/) {
                   5875:             #35.8.*
                   5876:             $pattern=~s/\*//;
1.1219    raeburn  5877:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5878:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5879:             #35.8.3.[34-56]
                   5880:             my $low=$2;
                   5881:             my $high=$3;
                   5882:             $pattern=$1;
                   5883:             if ($ip =~ /^\Q$pattern\E/) {
                   5884:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5885:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5886:             }
                   5887:         } elsif ($pattern =~ /^\*/) {
                   5888:             #*.msu.edu
                   5889:             $pattern=~s/\*//;
                   5890:             if (!defined($name)) {
                   5891:                 use Socket;
                   5892:                 my $netaddr=inet_aton($ip);
                   5893:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5894:             }
1.1219    raeburn  5895:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5896:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5897:             #127.0.0.1
1.1219    raeburn  5898:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5899:         } else {
                   5900:             #some.name.com
                   5901:             if (!defined($name)) {
                   5902:                 use Socket;
                   5903:                 my $netaddr=inet_aton($ip);
                   5904:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5905:             }
1.1219    raeburn  5906:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5907:         }
                   5908:         if ($allowed =~ /^(0|1)$/) { last; }
                   5909:     }
                   5910:     if ($allowed eq '') {
                   5911:         if ($numdenies && !$numallows) {
                   5912:             $allowed = 1;
                   5913:         } else {
                   5914:             $allowed = 0;
1.682     raeburn  5915:         }
                   5916:     }
                   5917:     return $allowed;
                   5918: }
                   5919: 
                   5920: ###############################################
                   5921: 
1.60      matthew  5922: =pod
                   5923: 
1.112     bowersj2 5924: =head1 Domain Template Functions
                   5925: 
                   5926: =over 4
                   5927: 
                   5928: =item * &determinedomain()
1.60      matthew  5929: 
                   5930: Inputs: $domain (usually will be undef)
                   5931: 
1.63      www      5932: Returns: Determines which domain should be used for designs
1.60      matthew  5933: 
                   5934: =cut
1.54      www      5935: 
1.60      matthew  5936: ###############################################
1.63      www      5937: sub determinedomain {
                   5938:     my $domain=shift;
1.531     albertel 5939:     if (! $domain) {
1.60      matthew  5940:         # Determine domain if we have not been given one
1.893     raeburn  5941:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5942:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5943:         if ($env{'request.role.domain'}) { 
                   5944:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5945:         }
                   5946:     }
1.63      www      5947:     return $domain;
                   5948: }
                   5949: ###############################################
1.517     raeburn  5950: 
1.518     albertel 5951: sub devalidate_domconfig_cache {
                   5952:     my ($udom)=@_;
                   5953:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5954: }
                   5955: 
                   5956: # ---------------------- Get domain configuration for a domain
                   5957: sub get_domainconf {
                   5958:     my ($udom) = @_;
                   5959:     my $cachetime=1800;
                   5960:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5961:     if (defined($cached)) { return %{$result}; }
                   5962: 
                   5963:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5964: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5965:     my (%designhash,%legacy);
1.518     albertel 5966:     if (keys(%domconfig) > 0) {
                   5967:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5968:             if (keys(%{$domconfig{'login'}})) {
                   5969:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5970:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5971:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5972:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5973:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5974:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5975:                                         if ($key eq 'loginvia') {
                   5976:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5977:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5978:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5979:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5980: 
                   5981:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5982:                                                 } else {
                   5983:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5984:                                                 }
1.948     raeburn  5985:                                             }
1.1208    raeburn  5986:                                         } elsif ($key eq 'headtag') {
                   5987:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5988:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5989:                                             }
1.946     raeburn  5990:                                         }
1.1208    raeburn  5991:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5992:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5993:                                         }
1.946     raeburn  5994:                                     }
                   5995:                                 }
                   5996:                             }
1.1366    raeburn  5997:                         } elsif ($key eq 'saml') {
                   5998:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5999:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6000:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6001:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
                   6002:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   6003:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6004:                                         }
                   6005:                                     }
                   6006:                                 }
                   6007:                             }
1.946     raeburn  6008:                         } else {
                   6009:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6010:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6011:                                     $domconfig{'login'}{$key}{$img};
                   6012:                             }
1.699     raeburn  6013:                         }
                   6014:                     } else {
                   6015:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6016:                     }
1.632     raeburn  6017:                 }
                   6018:             } else {
                   6019:                 $legacy{'login'} = 1;
1.518     albertel 6020:             }
1.632     raeburn  6021:         } else {
                   6022:             $legacy{'login'} = 1;
1.518     albertel 6023:         }
                   6024:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6025:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6026:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6027:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6028:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6029:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6030:                         }
1.518     albertel 6031:                     }
                   6032:                 }
1.632     raeburn  6033:             } else {
                   6034:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6035:             }
1.632     raeburn  6036:         } else {
                   6037:             $legacy{'rolecolors'} = 1;
1.518     albertel 6038:         }
1.948     raeburn  6039:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6040:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6041:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6042:             }
                   6043:         }
1.632     raeburn  6044:         if (keys(%legacy) > 0) {
                   6045:             my %legacyhash = &get_legacy_domconf($udom);
                   6046:             foreach my $item (keys(%legacyhash)) {
                   6047:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6048:                     if ($legacy{'login'}) { 
                   6049:                         $designhash{$item} = $legacyhash{$item};
                   6050:                     }
                   6051:                 } else {
                   6052:                     if ($legacy{'rolecolors'}) {
                   6053:                         $designhash{$item} = $legacyhash{$item};
                   6054:                     }
1.518     albertel 6055:                 }
                   6056:             }
                   6057:         }
1.632     raeburn  6058:     } else {
                   6059:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6060:     }
                   6061:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6062: 				  $cachetime);
                   6063:     return %designhash;
                   6064: }
                   6065: 
1.632     raeburn  6066: sub get_legacy_domconf {
                   6067:     my ($udom) = @_;
                   6068:     my %legacyhash;
                   6069:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6070:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6071:     if (-e $designfile) {
1.1317    raeburn  6072:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6073:             while (my $line = <$fh>) {
                   6074:                 next if ($line =~ /^\#/);
                   6075:                 chomp($line);
                   6076:                 my ($key,$val)=(split(/\=/,$line));
                   6077:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6078:             }
                   6079:             close($fh);
                   6080:         }
                   6081:     }
1.1026    raeburn  6082:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6083:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6084:     }
                   6085:     return %legacyhash;
                   6086: }
                   6087: 
1.63      www      6088: =pod
                   6089: 
1.112     bowersj2 6090: =item * &domainlogo()
1.63      www      6091: 
                   6092: Inputs: $domain (usually will be undef)
                   6093: 
                   6094: Returns: A link to a domain logo, if the domain logo exists.
                   6095: If the domain logo does not exist, a description of the domain.
                   6096: 
                   6097: =cut
1.112     bowersj2 6098: 
1.63      www      6099: ###############################################
                   6100: sub domainlogo {
1.517     raeburn  6101:     my $domain = &determinedomain(shift);
1.518     albertel 6102:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6103:     # See if there is a logo
                   6104:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6105:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6106:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6107: 	    if ($imgsrc =~ m{^/res/}) {
                   6108: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6109: 		&Apache::lonnet::repcopy($local_name);
                   6110: 	    }
                   6111: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6112:         }
                   6113:         my $alttext = $domain;
                   6114:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6115:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6116:         }
                   6117:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6118:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6119:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6120:     } else {
1.60      matthew  6121:         return '';
1.59      www      6122:     }
                   6123: }
1.63      www      6124: ##############################################
                   6125: 
                   6126: =pod
                   6127: 
1.112     bowersj2 6128: =item * &designparm()
1.63      www      6129: 
                   6130: Inputs: $which parameter; $domain (usually will be undef)
                   6131: 
                   6132: Returns: value of designparamter $which
                   6133: 
                   6134: =cut
1.112     bowersj2 6135: 
1.397     albertel 6136: 
1.400     albertel 6137: ##############################################
1.397     albertel 6138: sub designparm {
                   6139:     my ($which,$domain)=@_;
                   6140:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6141:         return $env{'environment.color.'.$which};
1.96      www      6142:     }
1.63      www      6143:     $domain=&determinedomain($domain);
1.1016    raeburn  6144:     my %domdesign;
                   6145:     unless ($domain eq 'public') {
                   6146:         %domdesign = &get_domainconf($domain);
                   6147:     }
1.520     raeburn  6148:     my $output;
1.517     raeburn  6149:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6150:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6151:     } else {
1.520     raeburn  6152:         $output = $defaultdesign{$which};
                   6153:     }
                   6154:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6155:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6156:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6157:             if ($output =~ m{^/res/}) {
                   6158:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6159:                 &Apache::lonnet::repcopy($local_name);
                   6160:             }
1.520     raeburn  6161:             $output = &lonhttpdurl($output);
                   6162:         }
1.63      www      6163:     }
1.520     raeburn  6164:     return $output;
1.63      www      6165: }
1.59      www      6166: 
1.822     bisitz   6167: ##############################################
                   6168: =pod
                   6169: 
1.832     bisitz   6170: =item * &authorspace()
                   6171: 
1.1028    raeburn  6172: Inputs: $url (usually will be undef).
1.832     bisitz   6173: 
1.1132    raeburn  6174: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6175:          directory being viewed (or for which action is being taken). 
                   6176:          If $url is provided, and begins /priv/<domain>/<uname>
                   6177:          the path will be that portion of the $context argument.
                   6178:          Otherwise the path will be for the author space of the current
                   6179:          user when the current role is author, or for that of the 
                   6180:          co-author/assistant co-author space when the current role 
                   6181:          is co-author or assistant co-author.
1.832     bisitz   6182: 
                   6183: =cut
                   6184: 
                   6185: sub authorspace {
1.1028    raeburn  6186:     my ($url) = @_;
                   6187:     if ($url ne '') {
                   6188:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6189:            return $1;
                   6190:         }
                   6191:     }
1.832     bisitz   6192:     my $caname = '';
1.1024    www      6193:     my $cadom = '';
1.1028    raeburn  6194:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6195:         ($cadom,$caname) =
1.832     bisitz   6196:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6197:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6198:         $caname = $env{'user.name'};
1.1024    www      6199:         $cadom = $env{'user.domain'};
1.832     bisitz   6200:     }
1.1028    raeburn  6201:     if (($caname ne '') && ($cadom ne '')) {
                   6202:         return "/priv/$cadom/$caname/";
                   6203:     }
                   6204:     return;
1.832     bisitz   6205: }
                   6206: 
                   6207: ##############################################
                   6208: =pod
                   6209: 
1.822     bisitz   6210: =item * &head_subbox()
                   6211: 
                   6212: Inputs: $content (contains HTML code with page functions, etc.)
                   6213: 
                   6214: Returns: HTML div with $content
                   6215:          To be included in page header
                   6216: 
                   6217: =cut
                   6218: 
                   6219: sub head_subbox {
                   6220:     my ($content)=@_;
                   6221:     my $output =
1.993     raeburn  6222:         '<div class="LC_head_subbox">'
1.822     bisitz   6223:        .$content
                   6224:        .'</div>'
                   6225: }
                   6226: 
                   6227: ##############################################
                   6228: =pod
                   6229: 
                   6230: =item * &CSTR_pageheader()
                   6231: 
1.1026    raeburn  6232: Input: (optional) filename from which breadcrumb trail is built.
                   6233:        In most cases no input as needed, as $env{'request.filename'}
                   6234:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6235:        frameset flag
                   6236:        If page header is being requested for use in a frameset, then
                   6237:        the second (option) argument -- frameset will be true, and
                   6238:        the target attribute set for links should be target="_parent".
1.822     bisitz   6239: 
                   6240: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6241:          To be included on Authoring Space pages
1.822     bisitz   6242: 
                   6243: =cut
                   6244: 
                   6245: sub CSTR_pageheader {
1.1379    raeburn  6246:     my ($trailfile,$frameset) = @_;
1.1026    raeburn  6247:     if ($trailfile eq '') {
                   6248:         $trailfile = $env{'request.filename'};
                   6249:     }
                   6250: 
                   6251: # this is for resources; directories have customtitle, and crumbs
                   6252: # and select recent are created in lonpubdir.pm
                   6253: 
                   6254:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6255:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6256:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6257:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6258:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6259: 
                   6260:     my $parentpath = '';
                   6261:     my $lastitem = '';
                   6262:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6263:         $parentpath = $1;
                   6264:         $lastitem = $2;
                   6265:     } else {
                   6266:         $lastitem = $thisdisfn;
                   6267:     }
1.921     bisitz   6268: 
1.1246    raeburn  6269:     my ($crsauthor,$title);
                   6270:     if (($env{'request.course.id'}) &&
                   6271:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6272:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6273:         $crsauthor = 1;
                   6274:         $title = &mt('Course Authoring Space');
                   6275:     } else {
                   6276:         $title = &mt('Authoring Space');
                   6277:     }
                   6278: 
1.1379    raeburn  6279:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6280:     if ($frameset) {
                   6281:         $target = ' target="_parent"';
                   6282:         $crumbtarget = '_parent';
                   6283:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6284:         $target = '';
                   6285:         $crumbtarget = '';
1.1379    raeburn  6286:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6287:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6288:         $crumbtarget = $env{'request.deeplink.target'};
                   6289:     }
1.1313    raeburn  6290: 
1.921     bisitz   6291:     my $output =
1.822     bisitz   6292:          '<div>'
                   6293:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6294:         .'<b>'.$title.'</b> '
1.1314    raeburn  6295:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6296:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6297: 
                   6298:     if ($lastitem) {
                   6299:         $output .=
                   6300:              '<span class="LC_filename">'
                   6301:             .$lastitem
                   6302:             .'</span>';
                   6303:     }
1.1245    raeburn  6304: 
1.1246    raeburn  6305:     if ($crsauthor) {
1.1379    raeburn  6306:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6307:     } else {
                   6308:         $output .=
                   6309:              '<br />'
1.1314    raeburn  6310:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6311:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6312:             .'</form>'
1.1379    raeburn  6313:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6314:     }
                   6315:     $output .= '</div>';
1.921     bisitz   6316: 
                   6317:     return $output;
1.822     bisitz   6318: }
                   6319: 
1.60      matthew  6320: ###############################################
                   6321: ###############################################
                   6322: 
                   6323: =pod
                   6324: 
1.112     bowersj2 6325: =back
                   6326: 
1.549     albertel 6327: =head1 HTML Helpers
1.112     bowersj2 6328: 
                   6329: =over 4
                   6330: 
                   6331: =item * &bodytag()
1.60      matthew  6332: 
                   6333: Returns a uniform header for LON-CAPA web pages.
                   6334: 
                   6335: Inputs: 
                   6336: 
1.112     bowersj2 6337: =over 4
                   6338: 
                   6339: =item * $title, A title to be displayed on the page.
                   6340: 
                   6341: =item * $function, the current role (can be undef).
                   6342: 
                   6343: =item * $addentries, extra parameters for the <body> tag.
                   6344: 
                   6345: =item * $bodyonly, if defined, only return the <body> tag.
                   6346: 
                   6347: =item * $domain, if defined, force a given domain.
                   6348: 
                   6349: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6350:             text interface only)
1.60      matthew  6351: 
1.814     bisitz   6352: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6353:                      navigational links
1.317     albertel 6354: 
1.338     albertel 6355: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6356: 
1.460     albertel 6357: =item * $args, optional argument valid values are
                   6358:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6359:             use_absolute     -> for external resource or syllabus, this will
                   6360:                                 contain https://<hostname> if server uses
                   6361:                                 https (as per hosts.tab), but request is for http
                   6362:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6363: 
1.1096    raeburn  6364: =item * $advtoolsref, optional argument, ref to an array containing
                   6365:             inlineremote items to be added in "Functions" menu below
                   6366:             breadcrumbs.
                   6367: 
1.1316    raeburn  6368: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6369:             course, if LON-CAPA is in LTI Provider context. Value is
                   6370:             the scope of use, i.e., launch was for access to a single, a map
                   6371:             or the entire course.
                   6372: 
                   6373: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6374:             context, this will contain the URL for the landing item in
                   6375:             the course, after launch from an LTI Consumer
                   6376: 
1.1318    raeburn  6377: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6378:             context, this will contain a reference to hash of items
                   6379:             to be included in the page header and/or inline menu.
                   6380: 
1.112     bowersj2 6381: =back
                   6382: 
1.60      matthew  6383: Returns: A uniform header for LON-CAPA web pages.  
                   6384: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6385: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6386: other decorations will be returned.
                   6387: 
                   6388: =cut
                   6389: 
1.54      www      6390: sub bodytag {
1.831     bisitz   6391:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6392:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
                   6393:         $ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 6394: 
1.954     raeburn  6395:     my $public;
                   6396:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6397:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6398:         $public = 1;
                   6399:     }
1.460     albertel 6400:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6401:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6402:     my $hostname = $args->{'hostname'};
1.339     albertel 6403: 
1.183     matthew  6404:     $function = &get_users_function() if (!$function);
1.339     albertel 6405:     my $img =    &designparm($function.'.img',$domain);
                   6406:     my $font =   &designparm($function.'.font',$domain);
                   6407:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6408: 
1.803     bisitz   6409:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6410: 		   'bgcolor' => $pgbg,
1.339     albertel 6411: 		   'text'    => $font,
                   6412:                    'alink'   => &designparm($function.'.alink',$domain),
                   6413: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6414: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6415:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6416: 
1.63      www      6417:  # role and realm
1.1178    raeburn  6418:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6419:     if ($realm) {
                   6420:         $realm = '/'.$realm;
                   6421:     }
1.1357    raeburn  6422:     if ($role eq 'ca') {
1.479     albertel 6423:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6424:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6425:     } 
1.55      www      6426: # realm
1.1357    raeburn  6427:     my ($cid,$sec);
1.258     albertel 6428:     if ($env{'request.course.id'}) {
1.1357    raeburn  6429:         $cid = $env{'request.course.id'};
                   6430:         if ($env{'request.course.sec'}) {
                   6431:             $sec = $env{'request.course.sec'};
                   6432:         }
                   6433:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6434:         if (&Apache::lonnet::is_course($1,$2)) {
                   6435:             $cid = $1.'_'.$2;
                   6436:             $sec = $3;
                   6437:         }
                   6438:     }
                   6439:     if ($cid) {
1.378     raeburn  6440:         if ($env{'request.role'} !~ /^cr/) {
                   6441:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6442:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6443:             if ($env{'request.role.desc'}) {
                   6444:                 $role = $env{'request.role.desc'};
                   6445:             } else {
                   6446:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6447:             }
1.1257    raeburn  6448:         } else {
                   6449:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6450:         }
1.1357    raeburn  6451:         if ($sec) {
                   6452:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6453:         }   
1.1357    raeburn  6454: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6455:     } else {
                   6456:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6457:     }
1.433     albertel 6458: 
1.359     albertel 6459:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6460: 
1.438     albertel 6461:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6462: 
1.101     www      6463: # construct main body tag
1.359     albertel 6464:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6465: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6466: 
1.1131    raeburn  6467:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6468: 
1.1130    raeburn  6469:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6470:         return $bodytag;
1.1130    raeburn  6471:     }
1.359     albertel 6472: 
1.954     raeburn  6473:     if ($public) {
1.433     albertel 6474: 	undef($role);
                   6475:     }
1.1318    raeburn  6476: 
1.1359    raeburn  6477:     my $showcrstitle = 1;
1.1357    raeburn  6478:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6479:         if (ref($ltimenu) eq 'HASH') {
                   6480:             unless ($ltimenu->{'role'}) {
                   6481:                 undef($role);
                   6482:             }
                   6483:             unless ($ltimenu->{'coursetitle'}) {
                   6484:                 $realm='&nbsp;';
1.1359    raeburn  6485:                 $showcrstitle = 0;
                   6486:             }
                   6487:         }
                   6488:     } elsif (($cid) && ($menucoll)) {
                   6489:         if (ref($menuref) eq 'HASH') {
                   6490:             unless ($menuref->{'role'}) {
                   6491:                 undef($role);
                   6492:             }
                   6493:             unless ($menuref->{'crs'}) {
                   6494:                 $realm='&nbsp;';
                   6495:                 $showcrstitle = 0;
1.1318    raeburn  6496:             }
                   6497:         }
                   6498:     }
                   6499: 
1.762     bisitz   6500:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6501:     #
                   6502:     # Extra info if you are the DC
                   6503:     my $dc_info = '';
1.1359    raeburn  6504:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6505:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6506:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6507:         $dc_info =~ s/\s+$//;
1.359     albertel 6508:     }
                   6509: 
1.1237    raeburn  6510:     my $crstype;
1.1357    raeburn  6511:     if ($cid) {
                   6512:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6513:     } elsif ($args->{'crstype'}) {
                   6514:         $crstype = $args->{'crstype'};
                   6515:     }
                   6516:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6517:         undef($role);
                   6518:     } else {
1.1242    raeburn  6519:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6520:     }
1.853     droeschl 6521: 
1.903     droeschl 6522:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6523: 
                   6524:         #    if ($env{'request.state'} eq 'construct') {
                   6525:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6526:         #    }
                   6527: 
1.1130    raeburn  6528:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6529:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6530: 
1.1318    raeburn  6531:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6532:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6533:                                                               $args->{'links_disabled'},
                   6534:                                                               $args->{'links_target'});
1.359     albertel 6535: 
1.1318    raeburn  6536:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6537:                 if ($dc_info) {
                   6538:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6539:                 }
                   6540:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6541:                                <em>$realm</em> $dc_info</div>|;
                   6542:                 return $bodytag;
                   6543:             }
1.894     droeschl 6544: 
1.1318    raeburn  6545:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6546:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6547:             }
1.916     droeschl 6548: 
1.1318    raeburn  6549:             $bodytag .= $right;
1.852     droeschl 6550: 
1.1318    raeburn  6551:             if ($dc_info) {
                   6552:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6553:             }
                   6554:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6555:         }
1.916     droeschl 6556: 
1.1169    raeburn  6557:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6558:         if ($args->{'no_secondary_menu'}) {
                   6559:             return $bodytag;
                   6560:         }
1.1169    raeburn  6561:         #don't show menus for public users
1.954     raeburn  6562:         if (!$public){
1.1318    raeburn  6563:             unless ($args->{'no_inline_menu'}) {
                   6564:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6565:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6566:                                                             $menucoll,$menuref,
1.1380    raeburn  6567:                                                             $args->{'links_disabled'},
                   6568:                                                             $args->{'links_target'});
1.1318    raeburn  6569:             }
1.903     droeschl 6570:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6571:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6572:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6573:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6574:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6575:             } elsif ($forcereg) {
                   6576:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6577:                                                             $args->{'group'},
1.1274    raeburn  6578:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6579:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6580:             } else {
                   6581:                 $bodytag .= 
                   6582:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6583:                                                         $forcereg,$args->{'group'},
                   6584:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6585:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6586:             }
1.903     droeschl 6587:         }else{
                   6588:             # this is to seperate menu from content when there's no secondary
                   6589:             # menu. Especially needed for public accessible ressources.
                   6590:             $bodytag .= '<hr style="clear:both" />';
                   6591:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6592:         }
1.903     droeschl 6593: 
1.235     raeburn  6594:         return $bodytag;
1.182     matthew  6595: }
                   6596: 
1.917     raeburn  6597: sub dc_courseid_toggle {
                   6598:     my ($dc_info) = @_;
1.980     raeburn  6599:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6600:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6601:            &mt('(More ...)').'</a></span>'.
                   6602:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6603: }
                   6604: 
1.330     albertel 6605: sub make_attr_string {
                   6606:     my ($register,$attr_ref) = @_;
                   6607: 
                   6608:     if ($attr_ref && !ref($attr_ref)) {
                   6609: 	die("addentries Must be a hash ref ".
                   6610: 	    join(':',caller(1))." ".
                   6611: 	    join(':',caller(0))." ");
                   6612:     }
                   6613: 
                   6614:     if ($register) {
1.339     albertel 6615: 	my ($on_load,$on_unload);
                   6616: 	foreach my $key (keys(%{$attr_ref})) {
                   6617: 	    if      (lc($key) eq 'onload') {
                   6618: 		$on_load.=$attr_ref->{$key}.';';
                   6619: 		delete($attr_ref->{$key});
                   6620: 
                   6621: 	    } elsif (lc($key) eq 'onunload') {
                   6622: 		$on_unload.=$attr_ref->{$key}.';';
                   6623: 		delete($attr_ref->{$key});
                   6624: 	    }
                   6625: 	}
1.953     droeschl 6626: 	$attr_ref->{'onload'}  = $on_load;
                   6627: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6628:     }
1.339     albertel 6629: 
1.330     albertel 6630:     my $attr_string;
1.1159    raeburn  6631:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6632: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6633:     }
                   6634:     return $attr_string;
                   6635: }
                   6636: 
                   6637: 
1.182     matthew  6638: ###############################################
1.251     albertel 6639: ###############################################
                   6640: 
                   6641: =pod
                   6642: 
                   6643: =item * &endbodytag()
                   6644: 
                   6645: Returns a uniform footer for LON-CAPA web pages.
                   6646: 
1.635     raeburn  6647: Inputs: 1 - optional reference to an args hash
                   6648: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6649: a 'Continue' link is not displayed if the page contains an
                   6650: internal redirect in the <head></head> section,
                   6651: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6652: 
                   6653: =cut
                   6654: 
                   6655: sub endbodytag {
1.635     raeburn  6656:     my ($args) = @_;
1.1080    raeburn  6657:     my $endbodytag;
                   6658:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6659:         $endbodytag='</body>';
                   6660:     }
1.315     albertel 6661:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6662:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6663: 	    $endbodytag=
                   6664: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6665: 	        &mt('Continue').'</a>'.
                   6666: 	        $endbodytag;
                   6667:         }
1.315     albertel 6668:     }
1.251     albertel 6669:     return $endbodytag;
                   6670: }
                   6671: 
1.352     albertel 6672: =pod
                   6673: 
                   6674: =item * &standard_css()
                   6675: 
                   6676: Returns a style sheet
                   6677: 
                   6678: Inputs: (all optional)
                   6679:             domain         -> force to color decorate a page for a specific
                   6680:                                domain
                   6681:             function       -> force usage of a specific rolish color scheme
                   6682:             bgcolor        -> override the default page bgcolor
                   6683: 
                   6684: =cut
                   6685: 
1.343     albertel 6686: sub standard_css {
1.345     albertel 6687:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6688:     $function  = &get_users_function() if (!$function);
                   6689:     my $img    = &designparm($function.'.img',   $domain);
                   6690:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6691:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6692:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6693: #second colour for later usage
1.345     albertel 6694:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6695:     my $pgbg_or_bgcolor =
                   6696: 	         $bgcolor ||
1.352     albertel 6697: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6698:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6699:     my $alink  = &designparm($function.'.alink', $domain);
                   6700:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6701:     my $link   = &designparm($function.'.link',  $domain);
                   6702: 
1.602     albertel 6703:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6704:     my $mono                 = 'monospace';
1.850     bisitz   6705:     my $data_table_head      = $sidebg;
                   6706:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6707:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6708:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6709:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6710:     my $mail_new             = '#FFBB77';
                   6711:     my $mail_new_hover       = '#DD9955';
                   6712:     my $mail_read            = '#BBBB77';
                   6713:     my $mail_read_hover      = '#999944';
                   6714:     my $mail_replied         = '#AAAA88';
                   6715:     my $mail_replied_hover   = '#888855';
                   6716:     my $mail_other           = '#99BBBB';
                   6717:     my $mail_other_hover     = '#669999';
1.391     albertel 6718:     my $table_header         = '#DDDDDD';
1.489     raeburn  6719:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6720:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6721:     my $button_hover         = '#BF2317';
1.392     albertel 6722: 
1.608     albertel 6723:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6724:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6725:                                              : '0 3px 0 4px';
1.448     albertel 6726: 
1.523     albertel 6727: 
1.343     albertel 6728:     return <<END;
1.947     droeschl 6729: 
                   6730: /* needed for iframe to allow 100% height in FF */
                   6731: body, html { 
                   6732:     margin: 0;
                   6733:     padding: 0 0.5%;
                   6734:     height: 99%; /* to avoid scrollbars */
                   6735: }
                   6736: 
1.795     www      6737: body {
1.911     bisitz   6738:   font-family: $sans;
                   6739:   line-height:130%;
                   6740:   font-size:0.83em;
                   6741:   color:$font;
1.795     www      6742: }
                   6743: 
1.959     onken    6744: a:focus,
                   6745: a:focus img {
1.795     www      6746:   color: red;
                   6747: }
1.698     harmsja  6748: 
1.911     bisitz   6749: form, .inline {
                   6750:   display: inline;
1.795     www      6751: }
1.721     harmsja  6752: 
1.795     www      6753: .LC_right {
1.911     bisitz   6754:   text-align:right;
1.795     www      6755: }
                   6756: 
                   6757: .LC_middle {
1.911     bisitz   6758:   vertical-align:middle;
1.795     www      6759: }
1.721     harmsja  6760: 
1.1130    raeburn  6761: .LC_floatleft {
                   6762:   float: left;
                   6763: }
                   6764: 
                   6765: .LC_floatright {
                   6766:   float: right;
                   6767: }
                   6768: 
1.911     bisitz   6769: .LC_400Box {
                   6770:   width:400px;
                   6771: }
1.721     harmsja  6772: 
1.947     droeschl 6773: .LC_iframecontainer {
                   6774:     width: 98%;
                   6775:     margin: 0;
                   6776:     position: fixed;
                   6777:     top: 8.5em;
                   6778:     bottom: 0;
                   6779: }
                   6780: 
                   6781: .LC_iframecontainer iframe{
                   6782:     border: none;
                   6783:     width: 100%;
                   6784:     height: 100%;
                   6785: }
                   6786: 
1.778     bisitz   6787: .LC_filename {
                   6788:   font-family: $mono;
                   6789:   white-space:pre;
1.921     bisitz   6790:   font-size: 120%;
1.778     bisitz   6791: }
                   6792: 
                   6793: .LC_fileicon {
                   6794:   border: none;
                   6795:   height: 1.3em;
                   6796:   vertical-align: text-bottom;
                   6797:   margin-right: 0.3em;
                   6798:   text-decoration:none;
                   6799: }
                   6800: 
1.1008    www      6801: .LC_setting {
                   6802:   text-decoration:underline;
                   6803: }
                   6804: 
1.350     albertel 6805: .LC_error {
                   6806:   color: red;
                   6807: }
1.795     www      6808: 
1.1097    bisitz   6809: .LC_warning {
                   6810:   color: darkorange;
                   6811: }
                   6812: 
1.457     albertel 6813: .LC_diff_removed {
1.733     bisitz   6814:   color: red;
1.394     albertel 6815: }
1.532     albertel 6816: 
                   6817: .LC_info,
1.457     albertel 6818: .LC_success,
                   6819: .LC_diff_added {
1.350     albertel 6820:   color: green;
                   6821: }
1.795     www      6822: 
1.802     bisitz   6823: div.LC_confirm_box {
                   6824:   background-color: #FAFAFA;
                   6825:   border: 1px solid $lg_border_color;
                   6826:   margin-right: 0;
                   6827:   padding: 5px;
                   6828: }
                   6829: 
                   6830: div.LC_confirm_box .LC_error img,
                   6831: div.LC_confirm_box .LC_success img {
                   6832:   vertical-align: middle;
                   6833: }
                   6834: 
1.1242    raeburn  6835: .LC_maxwidth {
                   6836:   max-width: 100%;
                   6837:   height: auto;
                   6838: }
                   6839: 
1.1243    raeburn  6840: .LC_textsize_mobile {
                   6841:   \@media only screen and (max-device-width: 480px) {
                   6842:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6843:   }
                   6844: }
                   6845: 
1.440     albertel 6846: .LC_icon {
1.771     droeschl 6847:   border: none;
1.790     droeschl 6848:   vertical-align: middle;
1.771     droeschl 6849: }
                   6850: 
1.543     albertel 6851: .LC_docs_spacer {
                   6852:   width: 25px;
                   6853:   height: 1px;
1.771     droeschl 6854:   border: none;
1.543     albertel 6855: }
1.346     albertel 6856: 
1.532     albertel 6857: .LC_internal_info {
1.735     bisitz   6858:   color: #999999;
1.532     albertel 6859: }
                   6860: 
1.794     www      6861: .LC_discussion {
1.1050    www      6862:   background: $data_table_dark;
1.911     bisitz   6863:   border: 1px solid black;
                   6864:   margin: 2px;
1.794     www      6865: }
                   6866: 
                   6867: .LC_disc_action_left {
1.1050    www      6868:   background: $sidebg;
1.911     bisitz   6869:   text-align: left;
1.1050    www      6870:   padding: 4px;
                   6871:   margin: 2px;
1.794     www      6872: }
                   6873: 
                   6874: .LC_disc_action_right {
1.1050    www      6875:   background: $sidebg;
1.911     bisitz   6876:   text-align: right;
1.1050    www      6877:   padding: 4px;
                   6878:   margin: 2px;
1.794     www      6879: }
                   6880: 
                   6881: .LC_disc_new_item {
1.911     bisitz   6882:   background: white;
                   6883:   border: 2px solid red;
1.1050    www      6884:   margin: 4px;
                   6885:   padding: 4px;
1.794     www      6886: }
                   6887: 
                   6888: .LC_disc_old_item {
1.911     bisitz   6889:   background: white;
1.1050    www      6890:   margin: 4px;
                   6891:   padding: 4px;
1.794     www      6892: }
                   6893: 
1.458     albertel 6894: table.LC_pastsubmission {
                   6895:   border: 1px solid black;
                   6896:   margin: 2px;
                   6897: }
                   6898: 
1.924     bisitz   6899: table#LC_menubuttons {
1.345     albertel 6900:   width: 100%;
                   6901:   background: $pgbg;
1.392     albertel 6902:   border: 2px;
1.402     albertel 6903:   border-collapse: separate;
1.803     bisitz   6904:   padding: 0;
1.345     albertel 6905: }
1.392     albertel 6906: 
1.801     tempelho 6907: table#LC_title_bar a {
                   6908:   color: $fontmenu;
                   6909: }
1.836     bisitz   6910: 
1.807     droeschl 6911: table#LC_title_bar {
1.819     tempelho 6912:   clear: both;
1.836     bisitz   6913:   display: none;
1.807     droeschl 6914: }
                   6915: 
1.795     www      6916: table#LC_title_bar,
1.933     droeschl 6917: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6918: table#LC_title_bar.LC_with_remote {
1.359     albertel 6919:   width: 100%;
1.392     albertel 6920:   border-color: $pgbg;
                   6921:   border-style: solid;
                   6922:   border-width: $border;
1.379     albertel 6923:   background: $pgbg;
1.801     tempelho 6924:   color: $fontmenu;
1.392     albertel 6925:   border-collapse: collapse;
1.803     bisitz   6926:   padding: 0;
1.819     tempelho 6927:   margin: 0;
1.359     albertel 6928: }
1.795     www      6929: 
1.933     droeschl 6930: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6931:     margin: 0;
                   6932:     padding: 0;
1.933     droeschl 6933:     position: relative;
                   6934:     list-style: none;
1.913     droeschl 6935: }
1.933     droeschl 6936: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6937:     display: inline;
                   6938: }
1.933     droeschl 6939: 
                   6940: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6941:     padding: 0;
1.933     droeschl 6942:     margin: 0;
                   6943:     float: left;
1.913     droeschl 6944: }
1.933     droeschl 6945: .LC_breadcrumb_tools_tools {
                   6946:     padding: 0;
                   6947:     margin: 0;
1.913     droeschl 6948:     float: right;
                   6949: }
                   6950: 
1.1240    raeburn  6951: .LC_placement_prog {
                   6952:     padding-right: 20px;
                   6953:     font-weight: bold;
                   6954:     font-size: 90%;
                   6955: }
                   6956: 
1.359     albertel 6957: table#LC_title_bar td {
                   6958:   background: $tabbg;
                   6959: }
1.795     www      6960: 
1.911     bisitz   6961: table#LC_menubuttons img {
1.803     bisitz   6962:   border: none;
1.346     albertel 6963: }
1.795     www      6964: 
1.842     droeschl 6965: .LC_breadcrumbs_component {
1.911     bisitz   6966:   float: right;
                   6967:   margin: 0 1em;
1.357     albertel 6968: }
1.842     droeschl 6969: .LC_breadcrumbs_component img {
1.911     bisitz   6970:   vertical-align: middle;
1.777     tempelho 6971: }
1.795     www      6972: 
1.1243    raeburn  6973: .LC_breadcrumbs_hoverable {
                   6974:   background: $sidebg;
                   6975: }
                   6976: 
1.383     albertel 6977: td.LC_table_cell_checkbox {
                   6978:   text-align: center;
                   6979: }
1.795     www      6980: 
                   6981: .LC_fontsize_small {
1.911     bisitz   6982:   font-size: 70%;
1.705     tempelho 6983: }
                   6984: 
1.844     bisitz   6985: #LC_breadcrumbs {
1.911     bisitz   6986:   clear:both;
                   6987:   background: $sidebg;
                   6988:   border-bottom: 1px solid $lg_border_color;
                   6989:   line-height: 2.5em;
1.933     droeschl 6990:   overflow: hidden;
1.911     bisitz   6991:   margin: 0;
                   6992:   padding: 0;
1.995     raeburn  6993:   text-align: left;
1.819     tempelho 6994: }
1.862     bisitz   6995: 
1.1098    bisitz   6996: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6997:   clear:both;
                   6998:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6999:   border: 1px solid $sidebg;
1.1098    bisitz   7000:   margin: 0 0 10px 0;
1.966     bisitz   7001:   padding: 3px;
1.995     raeburn  7002:   text-align: left;
1.822     bisitz   7003: }
                   7004: 
1.795     www      7005: .LC_fontsize_medium {
1.911     bisitz   7006:   font-size: 85%;
1.705     tempelho 7007: }
                   7008: 
1.795     www      7009: .LC_fontsize_large {
1.911     bisitz   7010:   font-size: 120%;
1.705     tempelho 7011: }
                   7012: 
1.346     albertel 7013: .LC_menubuttons_inline_text {
                   7014:   color: $font;
1.698     harmsja  7015:   font-size: 90%;
1.701     harmsja  7016:   padding-left:3px;
1.346     albertel 7017: }
                   7018: 
1.934     droeschl 7019: .LC_menubuttons_inline_text img{
                   7020:   vertical-align: middle;
                   7021: }
                   7022: 
1.1051    www      7023: li.LC_menubuttons_inline_text img {
1.951     onken    7024:   cursor:pointer;
1.1002    droeschl 7025:   text-decoration: none;
1.951     onken    7026: }
                   7027: 
1.526     www      7028: .LC_menubuttons_link {
                   7029:   text-decoration: none;
                   7030: }
1.795     www      7031: 
1.522     albertel 7032: .LC_menubuttons_category {
1.521     www      7033:   color: $font;
1.526     www      7034:   background: $pgbg;
1.521     www      7035:   font-size: larger;
                   7036:   font-weight: bold;
                   7037: }
                   7038: 
1.346     albertel 7039: td.LC_menubuttons_text {
1.911     bisitz   7040:   color: $font;
1.346     albertel 7041: }
1.706     harmsja  7042: 
1.346     albertel 7043: .LC_current_location {
                   7044:   background: $tabbg;
                   7045: }
1.795     www      7046: 
1.1286    raeburn  7047: td.LC_zero_height {
                   7048:   line-height: 0; 
                   7049:   cellpadding: 0;
                   7050: }
                   7051: 
1.938     bisitz   7052: table.LC_data_table {
1.347     albertel 7053:   border: 1px solid #000000;
1.402     albertel 7054:   border-collapse: separate;
1.426     albertel 7055:   border-spacing: 1px;
1.610     albertel 7056:   background: $pgbg;
1.347     albertel 7057: }
1.795     www      7058: 
1.422     albertel 7059: .LC_data_table_dense {
                   7060:   font-size: small;
                   7061: }
1.795     www      7062: 
1.507     raeburn  7063: table.LC_nested_outer {
                   7064:   border: 1px solid #000000;
1.589     raeburn  7065:   border-collapse: collapse;
1.803     bisitz   7066:   border-spacing: 0;
1.507     raeburn  7067:   width: 100%;
                   7068: }
1.795     www      7069: 
1.879     raeburn  7070: table.LC_innerpickbox,
1.507     raeburn  7071: table.LC_nested {
1.803     bisitz   7072:   border: none;
1.589     raeburn  7073:   border-collapse: collapse;
1.803     bisitz   7074:   border-spacing: 0;
1.507     raeburn  7075:   width: 100%;
                   7076: }
1.795     www      7077: 
1.911     bisitz   7078: table.LC_data_table tr th,
                   7079: table.LC_calendar tr th,
1.879     raeburn  7080: table.LC_prior_tries tr th,
                   7081: table.LC_innerpickbox tr th {
1.349     albertel 7082:   font-weight: bold;
                   7083:   background-color: $data_table_head;
1.801     tempelho 7084:   color:$fontmenu;
1.701     harmsja  7085:   font-size:90%;
1.347     albertel 7086: }
1.795     www      7087: 
1.879     raeburn  7088: table.LC_innerpickbox tr th,
                   7089: table.LC_innerpickbox tr td {
                   7090:   vertical-align: top;
                   7091: }
                   7092: 
1.711     raeburn  7093: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7094:   background-color: #CCCCCC;
1.711     raeburn  7095:   font-weight: bold;
                   7096:   text-align: left;
                   7097: }
1.795     www      7098: 
1.912     bisitz   7099: table.LC_data_table tr.LC_odd_row > td {
                   7100:   background-color: $data_table_light;
                   7101:   padding: 2px;
                   7102:   vertical-align: top;
                   7103: }
                   7104: 
1.809     bisitz   7105: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7106:   background-color: $data_table_light;
1.912     bisitz   7107:   vertical-align: top;
                   7108: }
                   7109: 
                   7110: table.LC_data_table tr.LC_even_row > td {
                   7111:   background-color: $data_table_dark;
1.425     albertel 7112:   padding: 2px;
1.900     bisitz   7113:   vertical-align: top;
1.347     albertel 7114: }
1.795     www      7115: 
1.809     bisitz   7116: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7117:   background-color: $data_table_dark;
1.900     bisitz   7118:   vertical-align: top;
1.347     albertel 7119: }
1.795     www      7120: 
1.425     albertel 7121: table.LC_data_table tr.LC_data_table_highlight td {
                   7122:   background-color: $data_table_darker;
                   7123: }
1.795     www      7124: 
1.639     raeburn  7125: table.LC_data_table tr td.LC_leftcol_header {
                   7126:   background-color: $data_table_head;
                   7127:   font-weight: bold;
                   7128: }
1.795     www      7129: 
1.451     albertel 7130: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7131: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7132:   font-weight: bold;
                   7133:   font-style: italic;
                   7134:   text-align: center;
                   7135:   padding: 8px;
1.347     albertel 7136: }
1.795     www      7137: 
1.1114    raeburn  7138: table.LC_data_table tr.LC_empty_row td,
                   7139: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7140:   background-color: $sidebg;
                   7141: }
                   7142: 
                   7143: table.LC_nested tr.LC_empty_row td {
                   7144:   background-color: #FFFFFF;
                   7145: }
                   7146: 
1.890     droeschl 7147: table.LC_caption {
                   7148: }
                   7149: 
1.507     raeburn  7150: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7151:   padding: 4ex
                   7152: }
1.795     www      7153: 
1.507     raeburn  7154: table.LC_nested_outer tr th {
                   7155:   font-weight: bold;
1.801     tempelho 7156:   color:$fontmenu;
1.507     raeburn  7157:   background-color: $data_table_head;
1.701     harmsja  7158:   font-size: small;
1.507     raeburn  7159:   border-bottom: 1px solid #000000;
                   7160: }
1.795     www      7161: 
1.507     raeburn  7162: table.LC_nested_outer tr td.LC_subheader {
                   7163:   background-color: $data_table_head;
                   7164:   font-weight: bold;
                   7165:   font-size: small;
                   7166:   border-bottom: 1px solid #000000;
                   7167:   text-align: right;
1.451     albertel 7168: }
1.795     www      7169: 
1.507     raeburn  7170: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7171:   background-color: #CCCCCC;
1.451     albertel 7172:   font-weight: bold;
                   7173:   font-size: small;
1.507     raeburn  7174:   text-align: center;
                   7175: }
1.795     www      7176: 
1.589     raeburn  7177: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7178: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7179:   text-align: left;
1.451     albertel 7180: }
1.795     www      7181: 
1.507     raeburn  7182: table.LC_nested td {
1.735     bisitz   7183:   background-color: #FFFFFF;
1.451     albertel 7184:   font-size: small;
1.507     raeburn  7185: }
1.795     www      7186: 
1.507     raeburn  7187: table.LC_nested_outer tr th.LC_right_item,
                   7188: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7189: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7190: table.LC_nested tr td.LC_right_item {
1.451     albertel 7191:   text-align: right;
                   7192: }
                   7193: 
1.507     raeburn  7194: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7195:   background-color: #EEEEEE;
1.451     albertel 7196: }
                   7197: 
1.473     raeburn  7198: table.LC_createuser {
                   7199: }
                   7200: 
                   7201: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7202:   font-size: small;
1.473     raeburn  7203: }
                   7204: 
                   7205: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7206:   background-color: #CCCCCC;
1.473     raeburn  7207:   font-weight: bold;
                   7208:   text-align: center;
                   7209: }
                   7210: 
1.349     albertel 7211: table.LC_calendar {
                   7212:   border: 1px solid #000000;
                   7213:   border-collapse: collapse;
1.917     raeburn  7214:   width: 98%;
1.349     albertel 7215: }
1.795     www      7216: 
1.349     albertel 7217: table.LC_calendar_pickdate {
                   7218:   font-size: xx-small;
                   7219: }
1.795     www      7220: 
1.349     albertel 7221: table.LC_calendar tr td {
                   7222:   border: 1px solid #000000;
                   7223:   vertical-align: top;
1.917     raeburn  7224:   width: 14%;
1.349     albertel 7225: }
1.795     www      7226: 
1.349     albertel 7227: table.LC_calendar tr td.LC_calendar_day_empty {
                   7228:   background-color: $data_table_dark;
                   7229: }
1.795     www      7230: 
1.779     bisitz   7231: table.LC_calendar tr td.LC_calendar_day_current {
                   7232:   background-color: $data_table_highlight;
1.777     tempelho 7233: }
1.795     www      7234: 
1.938     bisitz   7235: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7236:   background-color: $mail_new;
                   7237: }
1.795     www      7238: 
1.938     bisitz   7239: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7240:   background-color: $mail_new_hover;
                   7241: }
1.795     www      7242: 
1.938     bisitz   7243: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7244:   background-color: $mail_read;
                   7245: }
1.795     www      7246: 
1.938     bisitz   7247: /*
                   7248: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7249:   background-color: $mail_read_hover;
                   7250: }
1.938     bisitz   7251: */
1.795     www      7252: 
1.938     bisitz   7253: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7254:   background-color: $mail_replied;
                   7255: }
1.795     www      7256: 
1.938     bisitz   7257: /*
                   7258: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7259:   background-color: $mail_replied_hover;
                   7260: }
1.938     bisitz   7261: */
1.795     www      7262: 
1.938     bisitz   7263: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7264:   background-color: $mail_other;
                   7265: }
1.795     www      7266: 
1.938     bisitz   7267: /*
                   7268: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7269:   background-color: $mail_other_hover;
                   7270: }
1.938     bisitz   7271: */
1.494     raeburn  7272: 
1.777     tempelho 7273: table.LC_data_table tr > td.LC_browser_file,
                   7274: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7275:   background: #AAEE77;
1.389     albertel 7276: }
1.795     www      7277: 
1.777     tempelho 7278: table.LC_data_table tr > td.LC_browser_file_locked,
                   7279: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7280:   background: #FFAA99;
1.387     albertel 7281: }
1.795     www      7282: 
1.777     tempelho 7283: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7284:   background: #888888;
1.779     bisitz   7285: }
1.795     www      7286: 
1.777     tempelho 7287: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7288: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7289:   background: #F8F866;
1.777     tempelho 7290: }
1.795     www      7291: 
1.696     bisitz   7292: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7293:   background: #E0E8FF;
1.387     albertel 7294: }
1.696     bisitz   7295: 
1.707     bisitz   7296: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7297:   /* background: #77FF77; */
1.707     bisitz   7298: }
1.795     www      7299: 
1.707     bisitz   7300: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7301:   border-right: 8px solid #FFFF77;
1.707     bisitz   7302: }
1.795     www      7303: 
1.707     bisitz   7304: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7305:   border-right: 8px solid #FFAA77;
1.707     bisitz   7306: }
1.795     www      7307: 
1.707     bisitz   7308: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7309:   border-right: 8px solid #FF7777;
1.707     bisitz   7310: }
1.795     www      7311: 
1.707     bisitz   7312: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7313:   border-right: 8px solid #AAFF77;
1.707     bisitz   7314: }
1.795     www      7315: 
1.707     bisitz   7316: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7317:   border-right: 8px solid #11CC55;
1.707     bisitz   7318: }
                   7319: 
1.388     albertel 7320: span.LC_current_location {
1.701     harmsja  7321:   font-size:larger;
1.388     albertel 7322:   background: $pgbg;
                   7323: }
1.387     albertel 7324: 
1.1029    www      7325: span.LC_current_nav_location {
                   7326:   font-weight:bold;
                   7327:   background: $sidebg;
                   7328: }
                   7329: 
1.395     albertel 7330: span.LC_parm_menu_item {
                   7331:   font-size: larger;
                   7332: }
1.795     www      7333: 
1.395     albertel 7334: span.LC_parm_scope_all {
                   7335:   color: red;
                   7336: }
1.795     www      7337: 
1.395     albertel 7338: span.LC_parm_scope_folder {
                   7339:   color: green;
                   7340: }
1.795     www      7341: 
1.395     albertel 7342: span.LC_parm_scope_resource {
                   7343:   color: orange;
                   7344: }
1.795     www      7345: 
1.395     albertel 7346: span.LC_parm_part {
                   7347:   color: blue;
                   7348: }
1.795     www      7349: 
1.911     bisitz   7350: span.LC_parm_folder,
                   7351: span.LC_parm_symb {
1.395     albertel 7352:   font-size: x-small;
                   7353:   font-family: $mono;
                   7354:   color: #AAAAAA;
                   7355: }
                   7356: 
1.977     bisitz   7357: ul.LC_parm_parmlist li {
                   7358:   display: inline-block;
                   7359:   padding: 0.3em 0.8em;
                   7360:   vertical-align: top;
                   7361:   width: 150px;
                   7362:   border-top:1px solid $lg_border_color;
                   7363: }
                   7364: 
1.795     www      7365: td.LC_parm_overview_level_menu,
                   7366: td.LC_parm_overview_map_menu,
                   7367: td.LC_parm_overview_parm_selectors,
                   7368: td.LC_parm_overview_restrictions  {
1.396     albertel 7369:   border: 1px solid black;
                   7370:   border-collapse: collapse;
                   7371: }
1.795     www      7372: 
1.1285    raeburn  7373: span.LC_parm_recursive,
                   7374: td.LC_parm_recursive {
                   7375:   font-weight: bold;
                   7376:   font-size: smaller;
                   7377: }
                   7378: 
1.396     albertel 7379: table.LC_parm_overview_restrictions td {
                   7380:   border-width: 1px 4px 1px 4px;
                   7381:   border-style: solid;
                   7382:   border-color: $pgbg;
                   7383:   text-align: center;
                   7384: }
1.795     www      7385: 
1.396     albertel 7386: table.LC_parm_overview_restrictions th {
                   7387:   background: $tabbg;
                   7388:   border-width: 1px 4px 1px 4px;
                   7389:   border-style: solid;
                   7390:   border-color: $pgbg;
                   7391: }
1.795     www      7392: 
1.398     albertel 7393: table#LC_helpmenu {
1.803     bisitz   7394:   border: none;
1.398     albertel 7395:   height: 55px;
1.803     bisitz   7396:   border-spacing: 0;
1.398     albertel 7397: }
                   7398: 
                   7399: table#LC_helpmenu fieldset legend {
                   7400:   font-size: larger;
                   7401: }
1.795     www      7402: 
1.397     albertel 7403: table#LC_helpmenu_links {
                   7404:   width: 100%;
                   7405:   border: 1px solid black;
                   7406:   background: $pgbg;
1.803     bisitz   7407:   padding: 0;
1.397     albertel 7408:   border-spacing: 1px;
                   7409: }
1.795     www      7410: 
1.397     albertel 7411: table#LC_helpmenu_links tr td {
                   7412:   padding: 1px;
                   7413:   background: $tabbg;
1.399     albertel 7414:   text-align: center;
                   7415:   font-weight: bold;
1.397     albertel 7416: }
1.396     albertel 7417: 
1.795     www      7418: table#LC_helpmenu_links a:link,
                   7419: table#LC_helpmenu_links a:visited,
1.397     albertel 7420: table#LC_helpmenu_links a:active {
                   7421:   text-decoration: none;
                   7422:   color: $font;
                   7423: }
1.795     www      7424: 
1.397     albertel 7425: table#LC_helpmenu_links a:hover {
                   7426:   text-decoration: underline;
                   7427:   color: $vlink;
                   7428: }
1.396     albertel 7429: 
1.417     albertel 7430: .LC_chrt_popup_exists {
                   7431:   border: 1px solid #339933;
                   7432:   margin: -1px;
                   7433: }
1.795     www      7434: 
1.417     albertel 7435: .LC_chrt_popup_up {
                   7436:   border: 1px solid yellow;
                   7437:   margin: -1px;
                   7438: }
1.795     www      7439: 
1.417     albertel 7440: .LC_chrt_popup {
                   7441:   border: 1px solid #8888FF;
                   7442:   background: #CCCCFF;
                   7443: }
1.795     www      7444: 
1.421     albertel 7445: table.LC_pick_box {
                   7446:   border-collapse: separate;
                   7447:   background: white;
                   7448:   border: 1px solid black;
                   7449:   border-spacing: 1px;
                   7450: }
1.795     www      7451: 
1.421     albertel 7452: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7453:   background: $sidebg;
1.421     albertel 7454:   font-weight: bold;
1.900     bisitz   7455:   text-align: left;
1.740     bisitz   7456:   vertical-align: top;
1.421     albertel 7457:   width: 184px;
                   7458:   padding: 8px;
                   7459: }
1.795     www      7460: 
1.579     raeburn  7461: table.LC_pick_box td.LC_pick_box_value {
                   7462:   text-align: left;
                   7463:   padding: 8px;
                   7464: }
1.795     www      7465: 
1.579     raeburn  7466: table.LC_pick_box td.LC_pick_box_select {
                   7467:   text-align: left;
                   7468:   padding: 8px;
                   7469: }
1.795     www      7470: 
1.424     albertel 7471: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7472:   padding: 0;
1.421     albertel 7473:   height: 1px;
                   7474:   background: black;
                   7475: }
1.795     www      7476: 
1.421     albertel 7477: table.LC_pick_box td.LC_pick_box_submit {
                   7478:   text-align: right;
                   7479: }
1.795     www      7480: 
1.579     raeburn  7481: table.LC_pick_box td.LC_evenrow_value {
                   7482:   text-align: left;
                   7483:   padding: 8px;
                   7484:   background-color: $data_table_light;
                   7485: }
1.795     www      7486: 
1.579     raeburn  7487: table.LC_pick_box td.LC_oddrow_value {
                   7488:   text-align: left;
                   7489:   padding: 8px;
                   7490:   background-color: $data_table_light;
                   7491: }
1.795     www      7492: 
1.579     raeburn  7493: span.LC_helpform_receipt_cat {
                   7494:   font-weight: bold;
                   7495: }
1.795     www      7496: 
1.424     albertel 7497: table.LC_group_priv_box {
                   7498:   background: white;
                   7499:   border: 1px solid black;
                   7500:   border-spacing: 1px;
                   7501: }
1.795     www      7502: 
1.424     albertel 7503: table.LC_group_priv_box td.LC_pick_box_title {
                   7504:   background: $tabbg;
                   7505:   font-weight: bold;
                   7506:   text-align: right;
                   7507:   width: 184px;
                   7508: }
1.795     www      7509: 
1.424     albertel 7510: table.LC_group_priv_box td.LC_groups_fixed {
                   7511:   background: $data_table_light;
                   7512:   text-align: center;
                   7513: }
1.795     www      7514: 
1.424     albertel 7515: table.LC_group_priv_box td.LC_groups_optional {
                   7516:   background: $data_table_dark;
                   7517:   text-align: center;
                   7518: }
1.795     www      7519: 
1.424     albertel 7520: table.LC_group_priv_box td.LC_groups_functionality {
                   7521:   background: $data_table_darker;
                   7522:   text-align: center;
                   7523:   font-weight: bold;
                   7524: }
1.795     www      7525: 
1.424     albertel 7526: table.LC_group_priv td {
                   7527:   text-align: left;
1.803     bisitz   7528:   padding: 0;
1.424     albertel 7529: }
                   7530: 
                   7531: .LC_navbuttons {
                   7532:   margin: 2ex 0ex 2ex 0ex;
                   7533: }
1.795     www      7534: 
1.423     albertel 7535: .LC_topic_bar {
                   7536:   font-weight: bold;
                   7537:   background: $tabbg;
1.918     wenzelju 7538:   margin: 1em 0em 1em 2em;
1.805     bisitz   7539:   padding: 3px;
1.918     wenzelju 7540:   font-size: 1.2em;
1.423     albertel 7541: }
1.795     www      7542: 
1.423     albertel 7543: .LC_topic_bar span {
1.918     wenzelju 7544:   left: 0.5em;
                   7545:   position: absolute;
1.423     albertel 7546:   vertical-align: middle;
1.918     wenzelju 7547:   font-size: 1.2em;
1.423     albertel 7548: }
1.795     www      7549: 
1.423     albertel 7550: table.LC_course_group_status {
                   7551:   margin: 20px;
                   7552: }
1.795     www      7553: 
1.423     albertel 7554: table.LC_status_selector td {
                   7555:   vertical-align: top;
                   7556:   text-align: center;
1.424     albertel 7557:   padding: 4px;
                   7558: }
1.795     www      7559: 
1.599     albertel 7560: div.LC_feedback_link {
1.616     albertel 7561:   clear: both;
1.829     kalberla 7562:   background: $sidebg;
1.779     bisitz   7563:   width: 100%;
1.829     kalberla 7564:   padding-bottom: 10px;
                   7565:   border: 1px $tabbg solid;
1.833     kalberla 7566:   height: 22px;
                   7567:   line-height: 22px;
                   7568:   padding-top: 5px;
                   7569: }
                   7570: 
                   7571: div.LC_feedback_link img {
                   7572:   height: 22px;
1.867     kalberla 7573:   vertical-align:middle;
1.829     kalberla 7574: }
                   7575: 
1.911     bisitz   7576: div.LC_feedback_link a {
1.829     kalberla 7577:   text-decoration: none;
1.489     raeburn  7578: }
1.795     www      7579: 
1.867     kalberla 7580: div.LC_comblock {
1.911     bisitz   7581:   display:inline;
1.867     kalberla 7582:   color:$font;
                   7583:   font-size:90%;
                   7584: }
                   7585: 
                   7586: div.LC_feedback_link div.LC_comblock {
                   7587:   padding-left:5px;
                   7588: }
                   7589: 
                   7590: div.LC_feedback_link div.LC_comblock a {
                   7591:   color:$font;
                   7592: }
                   7593: 
1.489     raeburn  7594: span.LC_feedback_link {
1.858     bisitz   7595:   /* background: $feedback_link_bg; */
1.599     albertel 7596:   font-size: larger;
                   7597: }
1.795     www      7598: 
1.599     albertel 7599: span.LC_message_link {
1.858     bisitz   7600:   /* background: $feedback_link_bg; */
1.599     albertel 7601:   font-size: larger;
                   7602:   position: absolute;
                   7603:   right: 1em;
1.489     raeburn  7604: }
1.421     albertel 7605: 
1.515     albertel 7606: table.LC_prior_tries {
1.524     albertel 7607:   border: 1px solid #000000;
                   7608:   border-collapse: separate;
                   7609:   border-spacing: 1px;
1.515     albertel 7610: }
1.523     albertel 7611: 
1.515     albertel 7612: table.LC_prior_tries td {
1.524     albertel 7613:   padding: 2px;
1.515     albertel 7614: }
1.523     albertel 7615: 
                   7616: .LC_answer_correct {
1.795     www      7617:   background: lightgreen;
                   7618:   color: darkgreen;
                   7619:   padding: 6px;
1.523     albertel 7620: }
1.795     www      7621: 
1.523     albertel 7622: .LC_answer_charged_try {
1.797     www      7623:   background: #FFAAAA;
1.795     www      7624:   color: darkred;
                   7625:   padding: 6px;
1.523     albertel 7626: }
1.795     www      7627: 
1.779     bisitz   7628: .LC_answer_not_charged_try,
1.523     albertel 7629: .LC_answer_no_grade,
                   7630: .LC_answer_late {
1.795     www      7631:   background: lightyellow;
1.523     albertel 7632:   color: black;
1.795     www      7633:   padding: 6px;
1.523     albertel 7634: }
1.795     www      7635: 
1.523     albertel 7636: .LC_answer_previous {
1.795     www      7637:   background: lightblue;
                   7638:   color: darkblue;
                   7639:   padding: 6px;
1.523     albertel 7640: }
1.795     www      7641: 
1.779     bisitz   7642: .LC_answer_no_message {
1.777     tempelho 7643:   background: #FFFFFF;
                   7644:   color: black;
1.795     www      7645:   padding: 6px;
1.779     bisitz   7646: }
1.795     www      7647: 
1.1334    raeburn  7648: .LC_answer_unknown,
                   7649: .LC_answer_warning {
1.779     bisitz   7650:   background: orange;
                   7651:   color: black;
1.795     www      7652:   padding: 6px;
1.777     tempelho 7653: }
1.795     www      7654: 
1.529     albertel 7655: span.LC_prior_numerical,
                   7656: span.LC_prior_string,
                   7657: span.LC_prior_custom,
                   7658: span.LC_prior_reaction,
                   7659: span.LC_prior_math {
1.925     bisitz   7660:   font-family: $mono;
1.523     albertel 7661:   white-space: pre;
                   7662: }
                   7663: 
1.525     albertel 7664: span.LC_prior_string {
1.925     bisitz   7665:   font-family: $mono;
1.525     albertel 7666:   white-space: pre;
                   7667: }
                   7668: 
1.523     albertel 7669: table.LC_prior_option {
                   7670:   width: 100%;
                   7671:   border-collapse: collapse;
                   7672: }
1.795     www      7673: 
1.911     bisitz   7674: table.LC_prior_rank,
1.795     www      7675: table.LC_prior_match {
1.528     albertel 7676:   border-collapse: collapse;
                   7677: }
1.795     www      7678: 
1.528     albertel 7679: table.LC_prior_option tr td,
                   7680: table.LC_prior_rank tr td,
                   7681: table.LC_prior_match tr td {
1.524     albertel 7682:   border: 1px solid #000000;
1.515     albertel 7683: }
                   7684: 
1.855     bisitz   7685: .LC_nobreak {
1.544     albertel 7686:   white-space: nowrap;
1.519     raeburn  7687: }
                   7688: 
1.576     raeburn  7689: span.LC_cusr_emph {
                   7690:   font-style: italic;
                   7691: }
                   7692: 
1.633     raeburn  7693: span.LC_cusr_subheading {
                   7694:   font-weight: normal;
                   7695:   font-size: 85%;
                   7696: }
                   7697: 
1.861     bisitz   7698: div.LC_docs_entry_move {
1.859     bisitz   7699:   border: 1px solid #BBBBBB;
1.545     albertel 7700:   background: #DDDDDD;
1.861     bisitz   7701:   width: 22px;
1.859     bisitz   7702:   padding: 1px;
                   7703:   margin: 0;
1.545     albertel 7704: }
                   7705: 
1.861     bisitz   7706: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7707: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7708:   font-size: x-small;
                   7709: }
1.795     www      7710: 
1.861     bisitz   7711: .LC_docs_entry_parameter {
                   7712:   white-space: nowrap;
                   7713: }
                   7714: 
1.544     albertel 7715: .LC_docs_copy {
1.545     albertel 7716:   color: #000099;
1.544     albertel 7717: }
1.795     www      7718: 
1.544     albertel 7719: .LC_docs_cut {
1.545     albertel 7720:   color: #550044;
1.544     albertel 7721: }
1.795     www      7722: 
1.544     albertel 7723: .LC_docs_rename {
1.545     albertel 7724:   color: #009900;
1.544     albertel 7725: }
1.795     www      7726: 
1.544     albertel 7727: .LC_docs_remove {
1.545     albertel 7728:   color: #990000;
                   7729: }
                   7730: 
1.1284    raeburn  7731: .LC_docs_alias {
                   7732:   color: #440055;  
                   7733: }
                   7734: 
1.1286    raeburn  7735: .LC_domprefs_email,
1.1284    raeburn  7736: .LC_docs_alias_name,
1.547     albertel 7737: .LC_docs_reinit_warn,
                   7738: .LC_docs_ext_edit {
                   7739:   font-size: x-small;
                   7740: }
                   7741: 
1.545     albertel 7742: table.LC_docs_adddocs td,
                   7743: table.LC_docs_adddocs th {
                   7744:   border: 1px solid #BBBBBB;
                   7745:   padding: 4px;
                   7746:   background: #DDDDDD;
1.543     albertel 7747: }
                   7748: 
1.584     albertel 7749: table.LC_sty_begin {
                   7750:   background: #BBFFBB;
                   7751: }
1.795     www      7752: 
1.584     albertel 7753: table.LC_sty_end {
                   7754:   background: #FFBBBB;
                   7755: }
                   7756: 
1.589     raeburn  7757: table.LC_double_column {
1.803     bisitz   7758:   border-width: 0;
1.589     raeburn  7759:   border-collapse: collapse;
                   7760:   width: 100%;
                   7761:   padding: 2px;
                   7762: }
                   7763: 
                   7764: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7765:   top: 2px;
1.589     raeburn  7766:   left: 2px;
                   7767:   width: 47%;
                   7768:   vertical-align: top;
                   7769: }
                   7770: 
                   7771: table.LC_double_column tr td.LC_right_col {
                   7772:   top: 2px;
1.779     bisitz   7773:   right: 2px;
1.589     raeburn  7774:   width: 47%;
                   7775:   vertical-align: top;
                   7776: }
                   7777: 
1.591     raeburn  7778: div.LC_left_float {
                   7779:   float: left;
                   7780:   padding-right: 5%;
1.597     albertel 7781:   padding-bottom: 4px;
1.591     raeburn  7782: }
                   7783: 
                   7784: div.LC_clear_float_header {
1.597     albertel 7785:   padding-bottom: 2px;
1.591     raeburn  7786: }
                   7787: 
                   7788: div.LC_clear_float_footer {
1.597     albertel 7789:   padding-top: 10px;
1.591     raeburn  7790:   clear: both;
                   7791: }
                   7792: 
1.597     albertel 7793: div.LC_grade_show_user {
1.941     bisitz   7794: /*  border-left: 5px solid $sidebg; */
                   7795:   border-top: 5px solid #000000;
                   7796:   margin: 50px 0 0 0;
1.936     bisitz   7797:   padding: 15px 0 5px 10px;
1.597     albertel 7798: }
1.795     www      7799: 
1.936     bisitz   7800: div.LC_grade_show_user_odd_row {
1.941     bisitz   7801: /*  border-left: 5px solid #000000; */
                   7802: }
                   7803: 
                   7804: div.LC_grade_show_user div.LC_Box {
                   7805:   margin-right: 50px;
1.597     albertel 7806: }
                   7807: 
                   7808: div.LC_grade_submissions,
                   7809: div.LC_grade_message_center,
1.936     bisitz   7810: div.LC_grade_info_links {
1.597     albertel 7811:   margin: 5px;
                   7812:   width: 99%;
                   7813:   background: #FFFFFF;
                   7814: }
1.795     www      7815: 
1.597     albertel 7816: div.LC_grade_submissions_header,
1.936     bisitz   7817: div.LC_grade_message_center_header {
1.705     tempelho 7818:   font-weight: bold;
                   7819:   font-size: large;
1.597     albertel 7820: }
1.795     www      7821: 
1.597     albertel 7822: div.LC_grade_submissions_body,
1.936     bisitz   7823: div.LC_grade_message_center_body {
1.597     albertel 7824:   border: 1px solid black;
                   7825:   width: 99%;
                   7826:   background: #FFFFFF;
                   7827: }
1.795     www      7828: 
1.613     albertel 7829: table.LC_scantron_action {
                   7830:   width: 100%;
                   7831: }
1.795     www      7832: 
1.613     albertel 7833: table.LC_scantron_action tr th {
1.698     harmsja  7834:   font-weight:bold;
                   7835:   font-style:normal;
1.613     albertel 7836: }
1.795     www      7837: 
1.779     bisitz   7838: .LC_edit_problem_header,
1.614     albertel 7839: div.LC_edit_problem_footer {
1.705     tempelho 7840:   font-weight: normal;
                   7841:   font-size:  medium;
1.602     albertel 7842:   margin: 2px;
1.1060    bisitz   7843:   background-color: $sidebg;
1.600     albertel 7844: }
1.795     www      7845: 
1.600     albertel 7846: div.LC_edit_problem_header,
1.602     albertel 7847: div.LC_edit_problem_header div,
1.614     albertel 7848: div.LC_edit_problem_footer,
                   7849: div.LC_edit_problem_footer div,
1.602     albertel 7850: div.LC_edit_problem_editxml_header,
                   7851: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7852:   z-index: 100;
1.600     albertel 7853: }
1.795     www      7854: 
1.600     albertel 7855: div.LC_edit_problem_header_title {
1.705     tempelho 7856:   font-weight: bold;
                   7857:   font-size: larger;
1.602     albertel 7858:   background: $tabbg;
                   7859:   padding: 3px;
1.1060    bisitz   7860:   margin: 0 0 5px 0;
1.602     albertel 7861: }
1.795     www      7862: 
1.602     albertel 7863: table.LC_edit_problem_header_title {
                   7864:   width: 100%;
1.600     albertel 7865:   background: $tabbg;
1.602     albertel 7866: }
                   7867: 
1.1205    golterma 7868: div.LC_edit_actionbar {
                   7869:     background-color: $sidebg;
1.1218    droeschl 7870:     margin: 0;
                   7871:     padding: 0;
                   7872:     line-height: 200%;
1.602     albertel 7873: }
1.795     www      7874: 
1.1218    droeschl 7875: div.LC_edit_actionbar div{
                   7876:     padding: 0;
                   7877:     margin: 0;
                   7878:     display: inline-block;
1.600     albertel 7879: }
1.795     www      7880: 
1.1124    bisitz   7881: .LC_edit_opt {
                   7882:   padding-left: 1em;
                   7883:   white-space: nowrap;
                   7884: }
                   7885: 
1.1152    golterma 7886: .LC_edit_problem_latexhelper{
                   7887:     text-align: right;
                   7888: }
                   7889: 
                   7890: #LC_edit_problem_colorful div{
                   7891:     margin-left: 40px;
                   7892: }
                   7893: 
1.1205    golterma 7894: #LC_edit_problem_codemirror div{
                   7895:     margin-left: 0px;
                   7896: }
                   7897: 
1.911     bisitz   7898: img.stift {
1.803     bisitz   7899:   border-width: 0;
                   7900:   vertical-align: middle;
1.677     riegler  7901: }
1.680     riegler  7902: 
1.923     bisitz   7903: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7904:   vertical-align: top;
1.777     tempelho 7905: }
1.795     www      7906: 
1.716     raeburn  7907: div.LC_createcourse {
1.911     bisitz   7908:   margin: 10px 10px 10px 10px;
1.716     raeburn  7909: }
                   7910: 
1.917     raeburn  7911: .LC_dccid {
1.1130    raeburn  7912:   float: right;
1.917     raeburn  7913:   margin: 0.2em 0 0 0;
                   7914:   padding: 0;
                   7915:   font-size: 90%;
                   7916:   display:none;
                   7917: }
                   7918: 
1.897     wenzelju 7919: ol.LC_primary_menu a:hover,
1.721     harmsja  7920: ol#LC_MenuBreadcrumbs a:hover,
                   7921: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7922: ul#LC_secondary_menu a:hover,
1.721     harmsja  7923: .LC_FormSectionClearButton input:hover
1.795     www      7924: ul.LC_TabContent   li:hover a {
1.952     onken    7925:   color:$button_hover;
1.911     bisitz   7926:   text-decoration:none;
1.693     droeschl 7927: }
                   7928: 
1.779     bisitz   7929: h1 {
1.911     bisitz   7930:   padding: 0;
                   7931:   line-height:130%;
1.693     droeschl 7932: }
1.698     harmsja  7933: 
1.911     bisitz   7934: h2,
                   7935: h3,
                   7936: h4,
                   7937: h5,
                   7938: h6 {
                   7939:   margin: 5px 0 5px 0;
                   7940:   padding: 0;
                   7941:   line-height:130%;
1.693     droeschl 7942: }
1.795     www      7943: 
                   7944: .LC_hcell {
1.911     bisitz   7945:   padding:3px 15px 3px 15px;
                   7946:   margin: 0;
                   7947:   background-color:$tabbg;
                   7948:   color:$fontmenu;
                   7949:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7950: }
1.795     www      7951: 
1.840     bisitz   7952: .LC_Box > .LC_hcell {
1.911     bisitz   7953:   margin: 0 -10px 10px -10px;
1.835     bisitz   7954: }
                   7955: 
1.721     harmsja  7956: .LC_noBorder {
1.911     bisitz   7957:   border: 0;
1.698     harmsja  7958: }
1.693     droeschl 7959: 
1.721     harmsja  7960: .LC_FormSectionClearButton input {
1.911     bisitz   7961:   background-color:transparent;
                   7962:   border: none;
                   7963:   cursor:pointer;
                   7964:   text-decoration:underline;
1.693     droeschl 7965: }
1.763     bisitz   7966: 
                   7967: .LC_help_open_topic {
1.911     bisitz   7968:   color: #FFFFFF;
                   7969:   background-color: #EEEEFF;
                   7970:   margin: 1px;
                   7971:   padding: 4px;
                   7972:   border: 1px solid #000033;
                   7973:   white-space: nowrap;
                   7974:   /* vertical-align: middle; */
1.759     neumanie 7975: }
1.693     droeschl 7976: 
1.911     bisitz   7977: dl,
                   7978: ul,
                   7979: div,
                   7980: fieldset {
                   7981:   margin: 10px 10px 10px 0;
                   7982:   /* overflow: hidden; */
1.693     droeschl 7983: }
1.795     www      7984: 
1.1211    raeburn  7985: article.geogebraweb div {
                   7986:     margin: 0;
                   7987: }
                   7988: 
1.838     bisitz   7989: fieldset > legend {
1.911     bisitz   7990:   font-weight: bold;
                   7991:   padding: 0 5px 0 5px;
1.838     bisitz   7992: }
                   7993: 
1.813     bisitz   7994: #LC_nav_bar {
1.911     bisitz   7995:   float: left;
1.995     raeburn  7996:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7997:   margin: 0 0 2px 0;
1.807     droeschl 7998: }
                   7999: 
1.916     droeschl 8000: #LC_realm {
                   8001:   margin: 0.2em 0 0 0;
                   8002:   padding: 0;
                   8003:   font-weight: bold;
                   8004:   text-align: center;
1.995     raeburn  8005:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8006: }
                   8007: 
1.911     bisitz   8008: #LC_nav_bar em {
                   8009:   font-weight: bold;
                   8010:   font-style: normal;
1.807     droeschl 8011: }
                   8012: 
1.897     wenzelju 8013: ol.LC_primary_menu {
1.934     droeschl 8014:   margin: 0;
1.1076    raeburn  8015:   padding: 0;
1.807     droeschl 8016: }
                   8017: 
1.852     droeschl 8018: ol#LC_PathBreadcrumbs {
1.911     bisitz   8019:   margin: 0;
1.693     droeschl 8020: }
                   8021: 
1.897     wenzelju 8022: ol.LC_primary_menu li {
1.1076    raeburn  8023:   color: RGB(80, 80, 80);
                   8024:   vertical-align: middle;
                   8025:   text-align: left;
                   8026:   list-style: none;
1.1205    golterma 8027:   position: relative;
1.1076    raeburn  8028:   float: left;
1.1205    golterma 8029:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8030:   line-height: 1.5em;
1.1076    raeburn  8031: }
                   8032: 
1.1205    golterma 8033: ol.LC_primary_menu li a,
                   8034: ol.LC_primary_menu li p {
1.1076    raeburn  8035:   display: block;
                   8036:   margin: 0;
                   8037:   padding: 0 5px 0 10px;
                   8038:   text-decoration: none;
                   8039: }
                   8040: 
1.1205    golterma 8041: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8042:   display: inline-block;
                   8043:   width: 95%;
                   8044:   text-align: left;
                   8045: }
                   8046: 
                   8047: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8048:   display: inline-block;	
                   8049:   width: 5%;
                   8050:   float: right;
                   8051:   text-align: right;
                   8052:   font-size: 70%;
                   8053: }
                   8054: 
                   8055: ol.LC_primary_menu ul {
1.1076    raeburn  8056:   display: none;
1.1205    golterma 8057:   width: 15em;
1.1076    raeburn  8058:   background-color: $data_table_light;
1.1205    golterma 8059:   position: absolute;
                   8060:   top: 100%;
1.1076    raeburn  8061: }
                   8062: 
1.1205    golterma 8063: ol.LC_primary_menu ul ul {
                   8064:   left: 100%;
                   8065:   top: 0;
                   8066: }
                   8067: 
                   8068: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8069:   display: block;
                   8070:   position: absolute;
                   8071:   margin: 0;
                   8072:   padding: 0;
1.1078    raeburn  8073:   z-index: 2;
1.1076    raeburn  8074: }
                   8075: 
                   8076: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8077: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8078:   font-size: 90%;
1.911     bisitz   8079:   vertical-align: top;
1.1076    raeburn  8080:   float: none;
1.1079    raeburn  8081:   border-left: 1px solid black;
                   8082:   border-right: 1px solid black;
1.1205    golterma 8083: /* A dark bottom border to visualize different menu options; 
                   8084: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8085:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8086: }
                   8087: 
1.1205    golterma 8088: ol.LC_primary_menu li li p:hover {
                   8089:   color:$button_hover;
                   8090:   text-decoration:none;
                   8091:   background-color:$data_table_dark;
1.1076    raeburn  8092: }
                   8093: 
                   8094: ol.LC_primary_menu li li a:hover {
                   8095:    color:$button_hover;
                   8096:    background-color:$data_table_dark;
1.693     droeschl 8097: }
                   8098: 
1.1205    golterma 8099: /* Font-size equal to the size of the predecessors*/
                   8100: ol.LC_primary_menu li:hover li li {
                   8101:   font-size: 100%;
                   8102: }
                   8103: 
1.897     wenzelju 8104: ol.LC_primary_menu li img {
1.911     bisitz   8105:   vertical-align: bottom;
1.934     droeschl 8106:   height: 1.1em;
1.1077    raeburn  8107:   margin: 0.2em 0 0 0;
1.693     droeschl 8108: }
                   8109: 
1.897     wenzelju 8110: ol.LC_primary_menu a {
1.911     bisitz   8111:   color: RGB(80, 80, 80);
                   8112:   text-decoration: none;
1.693     droeschl 8113: }
1.795     www      8114: 
1.949     droeschl 8115: ol.LC_primary_menu a.LC_new_message {
                   8116:   font-weight:bold;
                   8117:   color: darkred;
                   8118: }
                   8119: 
1.975     raeburn  8120: ol.LC_docs_parameters {
                   8121:   margin-left: 0;
                   8122:   padding: 0;
                   8123:   list-style: none;
                   8124: }
                   8125: 
                   8126: ol.LC_docs_parameters li {
                   8127:   margin: 0;
                   8128:   padding-right: 20px;
                   8129:   display: inline;
                   8130: }
                   8131: 
1.976     raeburn  8132: ol.LC_docs_parameters li:before {
                   8133:   content: "\\002022 \\0020";
                   8134: }
                   8135: 
                   8136: li.LC_docs_parameters_title {
                   8137:   font-weight: bold;
                   8138: }
                   8139: 
                   8140: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8141:   content: "";
                   8142: }
                   8143: 
1.897     wenzelju 8144: ul#LC_secondary_menu {
1.1107    raeburn  8145:   clear: right;
1.911     bisitz   8146:   color: $fontmenu;
                   8147:   background: $tabbg;
                   8148:   list-style: none;
                   8149:   padding: 0;
                   8150:   margin: 0;
                   8151:   width: 100%;
1.995     raeburn  8152:   text-align: left;
1.1107    raeburn  8153:   float: left;
1.808     droeschl 8154: }
                   8155: 
1.897     wenzelju 8156: ul#LC_secondary_menu li {
1.911     bisitz   8157:   font-weight: bold;
                   8158:   line-height: 1.8em;
1.1107    raeburn  8159:   border-right: 1px solid black;
                   8160:   float: left;
                   8161: }
                   8162: 
                   8163: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8164:   background-color: $data_table_light;
                   8165: }
                   8166: 
                   8167: ul#LC_secondary_menu li a {
1.911     bisitz   8168:   padding: 0 0.8em;
1.1107    raeburn  8169: }
                   8170: 
                   8171: ul#LC_secondary_menu li ul {
                   8172:   display: none;
                   8173: }
                   8174: 
                   8175: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8176:   display: block;
                   8177:   position: absolute;
                   8178:   margin: 0;
                   8179:   padding: 0;
                   8180:   list-style:none;
                   8181:   float: none;
                   8182:   background-color: $data_table_light;
                   8183:   z-index: 2;
                   8184:   margin-left: -1px;
                   8185: }
                   8186: 
                   8187: ul#LC_secondary_menu li ul li {
                   8188:   font-size: 90%;
                   8189:   vertical-align: top;
                   8190:   border-left: 1px solid black;
1.911     bisitz   8191:   border-right: 1px solid black;
1.1119    raeburn  8192:   background-color: $data_table_light;
1.1107    raeburn  8193:   list-style:none;
                   8194:   float: none;
                   8195: }
                   8196: 
                   8197: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8198:   background-color: $data_table_dark;
1.807     droeschl 8199: }
                   8200: 
1.847     tempelho 8201: ul.LC_TabContent {
1.911     bisitz   8202:   display:block;
                   8203:   background: $sidebg;
                   8204:   border-bottom: solid 1px $lg_border_color;
                   8205:   list-style:none;
1.1020    raeburn  8206:   margin: -1px -10px 0 -10px;
1.911     bisitz   8207:   padding: 0;
1.693     droeschl 8208: }
                   8209: 
1.795     www      8210: ul.LC_TabContent li,
                   8211: ul.LC_TabContentBigger li {
1.911     bisitz   8212:   float:left;
1.741     harmsja  8213: }
1.795     www      8214: 
1.897     wenzelju 8215: ul#LC_secondary_menu li a {
1.911     bisitz   8216:   color: $fontmenu;
                   8217:   text-decoration: none;
1.693     droeschl 8218: }
1.795     www      8219: 
1.721     harmsja  8220: ul.LC_TabContent {
1.952     onken    8221:   min-height:20px;
1.721     harmsja  8222: }
1.795     www      8223: 
                   8224: ul.LC_TabContent li {
1.911     bisitz   8225:   vertical-align:middle;
1.959     onken    8226:   padding: 0 16px 0 10px;
1.911     bisitz   8227:   background-color:$tabbg;
                   8228:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8229:   border-left: solid 1px $font;
1.721     harmsja  8230: }
1.795     www      8231: 
1.847     tempelho 8232: ul.LC_TabContent .right {
1.911     bisitz   8233:   float:right;
1.847     tempelho 8234: }
                   8235: 
1.911     bisitz   8236: ul.LC_TabContent li a,
                   8237: ul.LC_TabContent li {
                   8238:   color:rgb(47,47,47);
                   8239:   text-decoration:none;
                   8240:   font-size:95%;
                   8241:   font-weight:bold;
1.952     onken    8242:   min-height:20px;
                   8243: }
                   8244: 
1.959     onken    8245: ul.LC_TabContent li a:hover,
                   8246: ul.LC_TabContent li a:focus {
1.952     onken    8247:   color: $button_hover;
1.959     onken    8248:   background:none;
                   8249:   outline:none;
1.952     onken    8250: }
                   8251: 
                   8252: ul.LC_TabContent li:hover {
                   8253:   color: $button_hover;
                   8254:   cursor:pointer;
1.721     harmsja  8255: }
1.795     www      8256: 
1.911     bisitz   8257: ul.LC_TabContent li.active {
1.952     onken    8258:   color: $font;
1.911     bisitz   8259:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8260:   border-bottom:solid 1px #FFFFFF;
                   8261:   cursor: default;
1.744     ehlerst  8262: }
1.795     www      8263: 
1.959     onken    8264: ul.LC_TabContent li.active a {
                   8265:   color:$font;
                   8266:   background:#FFFFFF;
                   8267:   outline: none;
                   8268: }
1.1047    raeburn  8269: 
                   8270: ul.LC_TabContent li.goback {
                   8271:   float: left;
                   8272:   border-left: none;
                   8273: }
                   8274: 
1.870     tempelho 8275: #maincoursedoc {
1.911     bisitz   8276:   clear:both;
1.870     tempelho 8277: }
                   8278: 
                   8279: ul.LC_TabContentBigger {
1.911     bisitz   8280:   display:block;
                   8281:   list-style:none;
                   8282:   padding: 0;
1.870     tempelho 8283: }
                   8284: 
1.795     www      8285: ul.LC_TabContentBigger li {
1.911     bisitz   8286:   vertical-align:bottom;
                   8287:   height: 30px;
                   8288:   font-size:110%;
                   8289:   font-weight:bold;
                   8290:   color: #737373;
1.841     tempelho 8291: }
                   8292: 
1.957     onken    8293: ul.LC_TabContentBigger li.active {
                   8294:   position: relative;
                   8295:   top: 1px;
                   8296: }
                   8297: 
1.870     tempelho 8298: ul.LC_TabContentBigger li a {
1.911     bisitz   8299:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8300:   height: 30px;
                   8301:   line-height: 30px;
                   8302:   text-align: center;
                   8303:   display: block;
                   8304:   text-decoration: none;
1.958     onken    8305:   outline: none;  
1.741     harmsja  8306: }
1.795     www      8307: 
1.870     tempelho 8308: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8309:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8310:   color:$font;
1.744     ehlerst  8311: }
1.795     www      8312: 
1.870     tempelho 8313: ul.LC_TabContentBigger li b {
1.911     bisitz   8314:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8315:   display: block;
                   8316:   float: left;
                   8317:   padding: 0 30px;
1.957     onken    8318:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8319: }
                   8320: 
1.956     onken    8321: ul.LC_TabContentBigger li:hover b {
                   8322:   color:$button_hover;
                   8323: }
                   8324: 
1.870     tempelho 8325: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8326:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8327:   color:$font;
1.957     onken    8328:   border: 0;
1.741     harmsja  8329: }
1.693     droeschl 8330: 
1.870     tempelho 8331: 
1.862     bisitz   8332: ul.LC_CourseBreadcrumbs {
                   8333:   background: $sidebg;
1.1020    raeburn  8334:   height: 2em;
1.862     bisitz   8335:   padding-left: 10px;
1.1020    raeburn  8336:   margin: 0;
1.862     bisitz   8337:   list-style-position: inside;
                   8338: }
                   8339: 
1.911     bisitz   8340: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8341: ol#LC_PathBreadcrumbs {
1.911     bisitz   8342:   padding-left: 10px;
                   8343:   margin: 0;
1.933     droeschl 8344:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8345: }
                   8346: 
1.911     bisitz   8347: ol#LC_MenuBreadcrumbs li,
                   8348: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8349: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8350:   display: inline;
1.933     droeschl 8351:   white-space: normal;  
1.693     droeschl 8352: }
                   8353: 
1.823     bisitz   8354: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8355: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8356:   text-decoration: none;
                   8357:   font-size:90%;
1.693     droeschl 8358: }
1.795     www      8359: 
1.969     droeschl 8360: ol#LC_MenuBreadcrumbs h1 {
                   8361:   display: inline;
                   8362:   font-size: 90%;
                   8363:   line-height: 2.5em;
                   8364:   margin: 0;
                   8365:   padding: 0;
                   8366: }
                   8367: 
1.795     www      8368: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8369:   text-decoration:none;
                   8370:   font-size:100%;
                   8371:   font-weight:bold;
1.693     droeschl 8372: }
1.795     www      8373: 
1.840     bisitz   8374: .LC_Box {
1.911     bisitz   8375:   border: solid 1px $lg_border_color;
                   8376:   padding: 0 10px 10px 10px;
1.746     neumanie 8377: }
1.795     www      8378: 
1.1020    raeburn  8379: .LC_DocsBox {
                   8380:   border: solid 1px $lg_border_color;
                   8381:   padding: 0 0 10px 10px;
                   8382: }
                   8383: 
1.795     www      8384: .LC_AboutMe_Image {
1.911     bisitz   8385:   float:left;
                   8386:   margin-right:10px;
1.747     neumanie 8387: }
1.795     www      8388: 
                   8389: .LC_Clear_AboutMe_Image {
1.911     bisitz   8390:   clear:left;
1.747     neumanie 8391: }
1.795     www      8392: 
1.721     harmsja  8393: dl.LC_ListStyleClean dt {
1.911     bisitz   8394:   padding-right: 5px;
                   8395:   display: table-header-group;
1.693     droeschl 8396: }
                   8397: 
1.721     harmsja  8398: dl.LC_ListStyleClean dd {
1.911     bisitz   8399:   display: table-row;
1.693     droeschl 8400: }
                   8401: 
1.721     harmsja  8402: .LC_ListStyleClean,
                   8403: .LC_ListStyleSimple,
                   8404: .LC_ListStyleNormal,
1.795     www      8405: .LC_ListStyleSpecial {
1.911     bisitz   8406:   /* display:block; */
                   8407:   list-style-position: inside;
                   8408:   list-style-type: none;
                   8409:   overflow: hidden;
                   8410:   padding: 0;
1.693     droeschl 8411: }
                   8412: 
1.721     harmsja  8413: .LC_ListStyleSimple li,
                   8414: .LC_ListStyleSimple dd,
                   8415: .LC_ListStyleNormal li,
                   8416: .LC_ListStyleNormal dd,
                   8417: .LC_ListStyleSpecial li,
1.795     www      8418: .LC_ListStyleSpecial dd {
1.911     bisitz   8419:   margin: 0;
                   8420:   padding: 5px 5px 5px 10px;
                   8421:   clear: both;
1.693     droeschl 8422: }
                   8423: 
1.721     harmsja  8424: .LC_ListStyleClean li,
                   8425: .LC_ListStyleClean dd {
1.911     bisitz   8426:   padding-top: 0;
                   8427:   padding-bottom: 0;
1.693     droeschl 8428: }
                   8429: 
1.721     harmsja  8430: .LC_ListStyleSimple dd,
1.795     www      8431: .LC_ListStyleSimple li {
1.911     bisitz   8432:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8433: }
                   8434: 
1.721     harmsja  8435: .LC_ListStyleSpecial li,
                   8436: .LC_ListStyleSpecial dd {
1.911     bisitz   8437:   list-style-type: none;
                   8438:   background-color: RGB(220, 220, 220);
                   8439:   margin-bottom: 4px;
1.693     droeschl 8440: }
                   8441: 
1.721     harmsja  8442: table.LC_SimpleTable {
1.911     bisitz   8443:   margin:5px;
                   8444:   border:solid 1px $lg_border_color;
1.795     www      8445: }
1.693     droeschl 8446: 
1.721     harmsja  8447: table.LC_SimpleTable tr {
1.911     bisitz   8448:   padding: 0;
                   8449:   border:solid 1px $lg_border_color;
1.693     droeschl 8450: }
1.795     www      8451: 
                   8452: table.LC_SimpleTable thead {
1.911     bisitz   8453:   background:rgb(220,220,220);
1.693     droeschl 8454: }
                   8455: 
1.721     harmsja  8456: div.LC_columnSection {
1.911     bisitz   8457:   display: block;
                   8458:   clear: both;
                   8459:   overflow: hidden;
                   8460:   margin: 0;
1.693     droeschl 8461: }
                   8462: 
1.721     harmsja  8463: div.LC_columnSection>* {
1.911     bisitz   8464:   float: left;
                   8465:   margin: 10px 20px 10px 0;
                   8466:   overflow:hidden;
1.693     droeschl 8467: }
1.721     harmsja  8468: 
1.795     www      8469: table em {
1.911     bisitz   8470:   font-weight: bold;
                   8471:   font-style: normal;
1.748     schulted 8472: }
1.795     www      8473: 
1.779     bisitz   8474: table.LC_tableBrowseRes,
1.795     www      8475: table.LC_tableOfContent {
1.911     bisitz   8476:   border:none;
                   8477:   border-spacing: 1px;
                   8478:   padding: 3px;
                   8479:   background-color: #FFFFFF;
                   8480:   font-size: 90%;
1.753     droeschl 8481: }
1.789     droeschl 8482: 
1.911     bisitz   8483: table.LC_tableOfContent {
                   8484:   border-collapse: collapse;
1.789     droeschl 8485: }
                   8486: 
1.771     droeschl 8487: table.LC_tableBrowseRes a,
1.768     schulted 8488: table.LC_tableOfContent a {
1.911     bisitz   8489:   background-color: transparent;
                   8490:   text-decoration: none;
1.753     droeschl 8491: }
                   8492: 
1.795     www      8493: table.LC_tableOfContent img {
1.911     bisitz   8494:   border: none;
                   8495:   height: 1.3em;
                   8496:   vertical-align: text-bottom;
                   8497:   margin-right: 0.3em;
1.753     droeschl 8498: }
1.757     schulted 8499: 
1.795     www      8500: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8501:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8502: }
                   8503: 
1.795     www      8504: a#LC_content_toolbar_everything {
1.911     bisitz   8505:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8506: }
                   8507: 
1.795     www      8508: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8509:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8510: }
                   8511: 
1.795     www      8512: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8513:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8514: }
                   8515: 
1.795     www      8516: a#LC_content_toolbar_changefolder {
1.911     bisitz   8517:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8518: }
                   8519: 
1.795     www      8520: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8521:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8522: }
                   8523: 
1.1043    raeburn  8524: a#LC_content_toolbar_edittoplevel {
                   8525:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8526: }
                   8527: 
1.795     www      8528: ul#LC_toolbar li a:hover {
1.911     bisitz   8529:   background-position: bottom center;
1.757     schulted 8530: }
                   8531: 
1.795     www      8532: ul#LC_toolbar {
1.911     bisitz   8533:   padding: 0;
                   8534:   margin: 2px;
                   8535:   list-style:none;
                   8536:   position:relative;
                   8537:   background-color:white;
1.1082    raeburn  8538:   overflow: auto;
1.757     schulted 8539: }
                   8540: 
1.795     www      8541: ul#LC_toolbar li {
1.911     bisitz   8542:   border:1px solid white;
                   8543:   padding: 0;
                   8544:   margin: 0;
                   8545:   float: left;
                   8546:   display:inline;
                   8547:   vertical-align:middle;
1.1082    raeburn  8548:   white-space: nowrap;
1.911     bisitz   8549: }
1.757     schulted 8550: 
1.783     amueller 8551: 
1.795     www      8552: a.LC_toolbarItem {
1.911     bisitz   8553:   display:block;
                   8554:   padding: 0;
                   8555:   margin: 0;
                   8556:   height: 32px;
                   8557:   width: 32px;
                   8558:   color:white;
                   8559:   border: none;
                   8560:   background-repeat:no-repeat;
                   8561:   background-color:transparent;
1.757     schulted 8562: }
                   8563: 
1.915     droeschl 8564: ul.LC_funclist {
                   8565:     margin: 0;
                   8566:     padding: 0.5em 1em 0.5em 0;
                   8567: }
                   8568: 
1.933     droeschl 8569: ul.LC_funclist > li:first-child {
                   8570:     font-weight:bold; 
                   8571:     margin-left:0.8em;
                   8572: }
                   8573: 
1.915     droeschl 8574: ul.LC_funclist + ul.LC_funclist {
                   8575:     /* 
                   8576:        left border as a seperator if we have more than
                   8577:        one list 
                   8578:     */
                   8579:     border-left: 1px solid $sidebg;
                   8580:     /* 
                   8581:        this hides the left border behind the border of the 
                   8582:        outer box if element is wrapped to the next 'line' 
                   8583:     */
                   8584:     margin-left: -1px;
                   8585: }
                   8586: 
1.843     bisitz   8587: ul.LC_funclist li {
1.915     droeschl 8588:   display: inline;
1.782     bisitz   8589:   white-space: nowrap;
1.915     droeschl 8590:   margin: 0 0 0 25px;
                   8591:   line-height: 150%;
1.782     bisitz   8592: }
                   8593: 
1.974     wenzelju 8594: .LC_hidden {
                   8595:   display: none;
                   8596: }
                   8597: 
1.1030    www      8598: .LCmodal-overlay {
                   8599: 		position:fixed;
                   8600: 		top:0;
                   8601: 		right:0;
                   8602: 		bottom:0;
                   8603: 		left:0;
                   8604: 		height:100%;
                   8605: 		width:100%;
                   8606: 		margin:0;
                   8607: 		padding:0;
                   8608: 		background:#999;
                   8609: 		opacity:.75;
                   8610: 		filter: alpha(opacity=75);
                   8611: 		-moz-opacity: 0.75;
                   8612: 		z-index:101;
                   8613: }
                   8614: 
                   8615: * html .LCmodal-overlay {   
                   8616: 		position: absolute;
                   8617: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8618: }
                   8619: 
                   8620: .LCmodal-window {
                   8621: 		position:fixed;
                   8622: 		top:50%;
                   8623: 		left:50%;
                   8624: 		margin:0;
                   8625: 		padding:0;
                   8626: 		z-index:102;
                   8627: 	}
                   8628: 
                   8629: * html .LCmodal-window {
                   8630: 		position:absolute;
                   8631: }
                   8632: 
                   8633: .LCclose-window {
                   8634: 		position:absolute;
                   8635: 		width:32px;
                   8636: 		height:32px;
                   8637: 		right:8px;
                   8638: 		top:8px;
                   8639: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8640: 		text-indent:-99999px;
                   8641: 		overflow:hidden;
                   8642: 		cursor:pointer;
                   8643: }
                   8644: 
1.1369    raeburn  8645: .LCisDisabled {
                   8646:   cursor: not-allowed;
                   8647:   opacity: 0.5;
                   8648: }
                   8649: 
                   8650: a[aria-disabled="true"] {
                   8651:   color: currentColor;
                   8652:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8653:   pointer-events: none;
                   8654:   text-decoration: none;
                   8655: }
                   8656: 
1.1335    raeburn  8657: pre.LC_wordwrap {
                   8658:   white-space: pre-wrap;
                   8659:   white-space: -moz-pre-wrap;
                   8660:   white-space: -pre-wrap;
                   8661:   white-space: -o-pre-wrap;
                   8662:   word-wrap: break-word;
                   8663: }
                   8664: 
1.1100    raeburn  8665: /*
1.1231    damieng  8666:   styles used for response display
                   8667: */
                   8668: div.LC_radiofoil, div.LC_rankfoil {
                   8669:   margin: .5em 0em .5em 0em;
                   8670: }
                   8671: table.LC_itemgroup {
                   8672:   margin-top: 1em;
                   8673: }
                   8674: 
                   8675: /*
1.1100    raeburn  8676:   styles used by TTH when "Default set of options to pass to tth/m
                   8677:   when converting TeX" in course settings has been set
                   8678: 
                   8679:   option passed: -t
                   8680: 
                   8681: */
                   8682: 
                   8683: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8684: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8685: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8686: td div.norm {line-height:normal;}
                   8687: 
                   8688: /*
                   8689:   option passed -y3
                   8690: */
                   8691: 
                   8692: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8693: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8694: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8695: 
1.1230    damieng  8696: /*
                   8697:   sections with roles, for content only
                   8698: */
                   8699: section[class^="role-"] {
                   8700:   padding-left: 10px;
                   8701:   padding-right: 5px;
                   8702:   margin-top: 8px;
                   8703:   margin-bottom: 8px;
                   8704:   border: 1px solid #2A4;
                   8705:   border-radius: 5px;
                   8706:   box-shadow: 0px 1px 1px #BBB;
                   8707: }
                   8708: section[class^="role-"]>h1 {
                   8709:   position: relative;
                   8710:   margin: 0px;
                   8711:   padding-top: 10px;
                   8712:   padding-left: 40px;
                   8713: }
                   8714: section[class^="role-"]>h1:before {
                   8715:   position: absolute;
                   8716:   left: -5px;
                   8717:   top: 5px;
                   8718: }
                   8719: section.role-activity>h1:before {
                   8720:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8721: }
                   8722: section.role-advice>h1:before {
                   8723:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8724: }
                   8725: section.role-bibliography>h1:before {
                   8726:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8727: }
                   8728: section.role-citation>h1:before {
                   8729:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8730: }
                   8731: section.role-conclusion>h1:before {
                   8732:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8733: }
                   8734: section.role-definition>h1:before {
                   8735:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8736: }
                   8737: section.role-demonstration>h1:before {
                   8738:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8739: }
                   8740: section.role-example>h1:before {
                   8741:   content:url('/adm/daxe/images/section_icons/example.png');
                   8742: }
                   8743: section.role-explanation>h1:before {
                   8744:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8745: }
                   8746: section.role-introduction>h1:before {
                   8747:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8748: }
                   8749: section.role-method>h1:before {
                   8750:   content:url('/adm/daxe/images/section_icons/method.png');
                   8751: }
                   8752: section.role-more_information>h1:before {
                   8753:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8754: }
                   8755: section.role-objectives>h1:before {
                   8756:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8757: }
                   8758: section.role-prerequisites>h1:before {
                   8759:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8760: }
                   8761: section.role-remark>h1:before {
                   8762:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8763: }
                   8764: section.role-reminder>h1:before {
                   8765:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8766: }
                   8767: section.role-summary>h1:before {
                   8768:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8769: }
                   8770: section.role-syntax>h1:before {
                   8771:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8772: }
                   8773: section.role-warning>h1:before {
                   8774:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8775: }
                   8776: 
1.1269    raeburn  8777: #LC_minitab_header {
                   8778:   float:left;
                   8779:   width:100%;
                   8780:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8781:   font-size:93%;
                   8782:   line-height:normal;
                   8783:   margin: 0.5em 0 0.5em 0;
                   8784: }
                   8785: #LC_minitab_header ul {
                   8786:   margin:0;
                   8787:   padding:10px 10px 0;
                   8788:   list-style:none;
                   8789: }
                   8790: #LC_minitab_header li {
                   8791:   float:left;
                   8792:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8793:   margin:0;
                   8794:   padding:0 0 0 9px;
                   8795: }
                   8796: #LC_minitab_header a {
                   8797:   display:block;
                   8798:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8799:   padding:5px 15px 4px 6px;
                   8800: }
                   8801: #LC_minitab_header #LC_current_minitab {
                   8802:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8803: }
                   8804: #LC_minitab_header #LC_current_minitab a {
                   8805:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8806:   padding-bottom:5px;
                   8807: }
                   8808: 
                   8809: 
1.343     albertel 8810: END
                   8811: }
                   8812: 
1.306     albertel 8813: =pod
                   8814: 
                   8815: =item * &headtag()
                   8816: 
                   8817: Returns a uniform footer for LON-CAPA web pages.
                   8818: 
1.307     albertel 8819: Inputs: $title - optional title for the head
                   8820:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8821:         $args - optional arguments
1.319     albertel 8822:             force_register - if is true call registerurl so the remote is 
                   8823:                              informed
1.415     albertel 8824:             redirect       -> array ref of
                   8825:                                    1- seconds before redirect occurs
                   8826:                                    2- url to redirect to
                   8827:                                    3- whether the side effect should occur
1.315     albertel 8828:                            (side effect of setting 
                   8829:                                $env{'internal.head.redirect'} to the url 
                   8830:                                redirected too)
1.352     albertel 8831:             domain         -> force to color decorate a page for a specific
                   8832:                                domain
                   8833:             function       -> force usage of a specific rolish color scheme
                   8834:             bgcolor        -> override the default page bgcolor
1.460     albertel 8835:             no_auto_mt_title
                   8836:                            -> prevent &mt()ing the title arg
1.464     albertel 8837: 
1.306     albertel 8838: =cut
                   8839: 
                   8840: sub headtag {
1.313     albertel 8841:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8842:     
1.363     albertel 8843:     my $function = $args->{'function'} || &get_users_function();
                   8844:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8845:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8846:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8847:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8848: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8849: 		   #time(),
1.418     albertel 8850: 		   $env{'environment.color.timestamp'},
1.363     albertel 8851: 		   $function,$domain,$bgcolor);
                   8852: 
1.369     www      8853:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8854: 
1.308     albertel 8855:     my $result =
                   8856: 	'<head>'.
1.1160    raeburn  8857: 	&font_settings($args);
1.319     albertel 8858: 
1.1188    raeburn  8859:     my $inhibitprint;
                   8860:     if ($args->{'print_suppress'}) {
                   8861:         $inhibitprint = &print_suppression();
                   8862:     }
1.1064    raeburn  8863: 
1.461     albertel 8864:     if (!$args->{'frameset'}) {
                   8865: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8866:     }
1.962     droeschl 8867:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8868:         $result .= Apache::lonxml::display_title();
1.319     albertel 8869:     }
1.436     albertel 8870:     if (!$args->{'no_nav_bar'} 
                   8871: 	&& !$args->{'only_body'}
                   8872: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8873: 	$result .= &help_menu_js($httphost);
1.1032    www      8874:         $result.=&modal_window();
1.1038    www      8875:         $result.=&togglebox_script();
1.1034    www      8876:         $result.=&wishlist_window();
1.1041    www      8877:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8878:     } else {
                   8879:         if ($args->{'add_modal'}) {
                   8880:            $result.=&modal_window();
                   8881:         }
                   8882:         if ($args->{'add_wishlist'}) {
                   8883:            $result.=&wishlist_window();
                   8884:         }
1.1038    www      8885:         if ($args->{'add_togglebox'}) {
                   8886:            $result.=&togglebox_script();
                   8887:         }
1.1041    www      8888:         if ($args->{'add_progressbar'}) {
                   8889:            $result.=&LCprogressbarUpdate_script();
                   8890:         }
1.436     albertel 8891:     }
1.314     albertel 8892:     if (ref($args->{'redirect'})) {
1.414     albertel 8893: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8894: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8895: 	if (!$inhibit_continue) {
                   8896: 	    $env{'internal.head.redirect'} = $url;
                   8897: 	}
1.313     albertel 8898: 	$result.=<<ADDMETA
                   8899: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8900: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8901: ADDMETA
1.1210    raeburn  8902:     } else {
                   8903:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8904:             my $requrl = $env{'request.uri'};
                   8905:             if ($requrl eq '') {
                   8906:                 $requrl = $ENV{'REQUEST_URI'};
                   8907:                 $requrl =~ s/\?.+$//;
                   8908:             }
                   8909:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8910:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8911:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8912:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8913:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8914:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8915:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8916:                     my ($offload,$offloadoth);
1.1210    raeburn  8917:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8918:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8919:                             $offload = 1;
1.1353    raeburn  8920:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8921:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8922:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8923:                                     $offloadoth = 1;
                   8924:                                     $dom_in_use = $env{'user.domain'};
                   8925:                                 }
                   8926:                             }
1.1340    raeburn  8927:                         }
                   8928:                     }
                   8929:                     unless ($offload) {
                   8930:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8931:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8932:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8933:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8934:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8935:                                         $offload = 1;
1.1352    raeburn  8936:                                         $offloadoth = 1;
1.1340    raeburn  8937:                                         $dom_in_use = $env{'user.domain'};
                   8938:                                     }
1.1210    raeburn  8939:                                 }
1.1340    raeburn  8940:                             }
                   8941:                         }
                   8942:                     }
                   8943:                     if ($offload) {
1.1358    raeburn  8944:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8945:                         if (($newserver eq '') && ($offloadoth)) {
                   8946:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8947:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8948:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8949:                             }
                   8950:                         }
1.1340    raeburn  8951:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8952:                             my $numsec = 5;
                   8953:                             my $timeout = $numsec * 1000;
                   8954:                             my ($newurl,$locknum,%locks,$msg);
                   8955:                             if ($env{'request.role.adv'}) {
                   8956:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8957:                             }
                   8958:                             my $disable_submit = 0;
                   8959:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8960:                                 $disable_submit = 1;
                   8961:                             }
                   8962:                             if ($locknum) {
                   8963:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8964:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8965:                                        join(", ",sort(values(%locks)))."\n";
                   8966:                                 if (&show_course()) {
                   8967:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8968:                                 } else {
                   8969:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8970:                                 }
1.1340    raeburn  8971:                             } else {
                   8972:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8973:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8974:                                 }
                   8975:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8976:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8977:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8978:                                     $newurl .= '&role='.$env{'request.role'};
                   8979:                                 }
                   8980:                                 if ($env{'request.symb'}) {
                   8981:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8982:                                     if ($shownsymb =~ m{^/enc/}) {
                   8983:                                         my $reqdmajor = 2;
                   8984:                                         my $reqdminor = 11;
                   8985:                                         my $reqdsubminor = 3;
                   8986:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8987:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8988:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8989:                                         if (($major eq '' && $minor eq '') ||
                   8990:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8991:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8992:                                              ($reqdsubminor > $subminor))))) {
                   8993:                                             undef($shownsymb);
                   8994:                                         }
1.1210    raeburn  8995:                                     }
1.1340    raeburn  8996:                                     if ($shownsymb) {
                   8997:                                         &js_escape(\$shownsymb);
                   8998:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  8999:                                     }
1.1340    raeburn  9000:                                 } else {
                   9001:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9002:                                     &js_escape(\$shownurl);
                   9003:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9004:                                 }
1.1340    raeburn  9005:                             }
                   9006:                             &js_escape(\$msg);
                   9007:                             $result.=<<OFFLOAD
1.1210    raeburn  9008: <meta http-equiv="pragma" content="no-cache" />
                   9009: <script type="text/javascript">
1.1215    raeburn  9010: // <![CDATA[
1.1210    raeburn  9011: function LC_Offload_Now() {
                   9012:     var dest = "$newurl";
                   9013:     if (dest != '') {
                   9014:         window.location.href="$newurl";
                   9015:     }
                   9016: }
1.1214    raeburn  9017: \$(document).ready(function () {
                   9018:     window.alert('$msg');
                   9019:     if ($disable_submit) {
1.1210    raeburn  9020:         \$(".LC_hwk_submit").prop("disabled", true);
                   9021:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9022:     }
                   9023:     setTimeout('LC_Offload_Now()', $timeout);
                   9024: });
1.1215    raeburn  9025: // ]]>
1.1210    raeburn  9026: </script>
                   9027: OFFLOAD
                   9028:                         }
                   9029:                     }
                   9030:                 }
                   9031:             }
                   9032:         }
1.313     albertel 9033:     }
1.306     albertel 9034:     if (!defined($title)) {
                   9035: 	$title = 'The LearningOnline Network with CAPA';
                   9036:     }
1.460     albertel 9037:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9038:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9039: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9040:     if (!$args->{'frameset'}) {
                   9041:         $result .= ' /';
                   9042:     }
                   9043:     $result .= '>' 
1.1064    raeburn  9044:         .$inhibitprint
1.414     albertel 9045: 	.$head_extra;
1.1242    raeburn  9046:     my $clientmobile;
                   9047:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9048:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9049:     } else {
                   9050:         $clientmobile = $env{'browser.mobile'};
                   9051:     }
                   9052:     if ($clientmobile) {
1.1137    raeburn  9053:         $result .= '
                   9054: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9055: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9056:     }
1.1278    raeburn  9057:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9058:     return $result.'</head>';
1.306     albertel 9059: }
                   9060: 
                   9061: =pod
                   9062: 
1.340     albertel 9063: =item * &font_settings()
                   9064: 
                   9065: Returns neccessary <meta> to set the proper encoding
                   9066: 
1.1160    raeburn  9067: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9068: 
                   9069: =cut
                   9070: 
                   9071: sub font_settings {
1.1160    raeburn  9072:     my ($args) = @_;
1.340     albertel 9073:     my $headerstring='';
1.1160    raeburn  9074:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9075:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9076:         $headerstring.=
                   9077:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9078:         if (!$args->{'frameset'}) {
                   9079: 	    $headerstring.= ' /';
                   9080:         }
                   9081: 	$headerstring .= '>'."\n";
1.340     albertel 9082:     }
                   9083:     return $headerstring;
                   9084: }
                   9085: 
1.341     albertel 9086: =pod
                   9087: 
1.1064    raeburn  9088: =item * &print_suppression()
                   9089: 
                   9090: In course context returns css which causes the body to be blank when media="print",
                   9091: if printout generation is unavailable for the current resource.
                   9092: 
                   9093: This could be because:
                   9094: 
                   9095: (a) printstartdate is in the future
                   9096: 
                   9097: (b) printenddate is in the past
                   9098: 
                   9099: (c) there is an active exam block with "printout"
                   9100: functionality blocked
                   9101: 
                   9102: Users with pav, pfo or evb privileges are exempt.
                   9103: 
                   9104: Inputs: none
                   9105: 
                   9106: =cut
                   9107: 
                   9108: 
                   9109: sub print_suppression {
                   9110:     my $noprint;
                   9111:     if ($env{'request.course.id'}) {
                   9112:         my $scope = $env{'request.course.id'};
                   9113:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9114:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9115:             return;
                   9116:         }
                   9117:         if ($env{'request.course.sec'} ne '') {
                   9118:             $scope .= "/$env{'request.course.sec'}";
                   9119:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9120:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9121:                 return;
1.1064    raeburn  9122:             }
                   9123:         }
                   9124:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9125:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9126:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9127:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9128:         if ($blocked) {
                   9129:             my $checkrole = "cm./$cdom/$cnum";
                   9130:             if ($env{'request.course.sec'} ne '') {
                   9131:                 $checkrole .= "/$env{'request.course.sec'}";
                   9132:             }
                   9133:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9134:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9135:                 $noprint = 1;
                   9136:             }
                   9137:         }
                   9138:         unless ($noprint) {
                   9139:             my $symb = &Apache::lonnet::symbread();
                   9140:             if ($symb ne '') {
                   9141:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9142:                 if (ref($navmap)) {
                   9143:                     my $res = $navmap->getBySymb($symb);
                   9144:                     if (ref($res)) {
                   9145:                         if (!$res->resprintable()) {
                   9146:                             $noprint = 1;
                   9147:                         }
                   9148:                     }
                   9149:                 }
                   9150:             }
                   9151:         }
                   9152:         if ($noprint) {
                   9153:             return <<"ENDSTYLE";
                   9154: <style type="text/css" media="print">
                   9155:     body { display:none }
                   9156: </style>
                   9157: ENDSTYLE
                   9158:         }
                   9159:     }
                   9160:     return;
                   9161: }
                   9162: 
                   9163: =pod
                   9164: 
1.341     albertel 9165: =item * &xml_begin()
                   9166: 
                   9167: Returns the needed doctype and <html>
                   9168: 
                   9169: Inputs: none
                   9170: 
                   9171: =cut
                   9172: 
                   9173: sub xml_begin {
1.1168    raeburn  9174:     my ($is_frameset) = @_;
1.341     albertel 9175:     my $output='';
                   9176: 
                   9177:     if ($env{'browser.mathml'}) {
                   9178: 	$output='<?xml version="1.0"?>'
                   9179:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9180: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9181:             
                   9182: #	    .'<!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">] >'
                   9183: 	    .'<!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">'
                   9184:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9185: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9186:     } elsif ($is_frameset) {
                   9187:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9188:                 '<html>'."\n";
1.341     albertel 9189:     } else {
1.1168    raeburn  9190: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9191:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9192:     }
                   9193:     return $output;
                   9194: }
1.340     albertel 9195: 
                   9196: =pod
                   9197: 
1.306     albertel 9198: =item * &start_page()
                   9199: 
                   9200: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9201: 
1.648     raeburn  9202: Inputs:
                   9203: 
                   9204: =over 4
                   9205: 
                   9206: $title - optional title for the page
                   9207: 
                   9208: $head_extra - optional extra HTML to incude inside the <head>
                   9209: 
                   9210: $args - additional optional args supported are:
                   9211: 
                   9212: =over 8
                   9213: 
                   9214:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9215:                                     arg on
1.814     bisitz   9216:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9217:              add_entries    -> additional attributes to add to the  <body>
                   9218:              domain         -> force to color decorate a page for a 
1.317     albertel 9219:                                     specific domain
1.648     raeburn  9220:              function       -> force usage of a specific rolish color
1.317     albertel 9221:                                     scheme
1.648     raeburn  9222:              redirect       -> see &headtag()
                   9223:              bgcolor        -> override the default page bg color
                   9224:              js_ready       -> return a string ready for being used in 
1.317     albertel 9225:                                     a javascript writeln
1.648     raeburn  9226:              html_encode    -> return a string ready for being used in 
1.320     albertel 9227:                                     a html attribute
1.648     raeburn  9228:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9229:                                     $forcereg arg
1.648     raeburn  9230:              frameset       -> if true will start with a <frameset>
1.330     albertel 9231:                                     rather than <body>
1.648     raeburn  9232:              skip_phases    -> hash ref of 
1.338     albertel 9233:                                     head -> skip the <html><head> generation
                   9234:                                     body -> skip all <body> generation
1.648     raeburn  9235:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9236:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9237:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9238:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9239:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9240:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9241:                                specific group
                   9242:              use_absolute   -> for request for external resource or syllabus, this
                   9243:                                will contain https://<hostname> if server uses
                   9244:                                https (as per hosts.tab), but request is for http
                   9245:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9246:              links_disabled -> Links in primary and secondary menus are disabled
                   9247:                                (Can enable them once page has loaded - see lonroles.pm
                   9248:                                for an example).
1.1380    raeburn  9249:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9250: 
1.648     raeburn  9251: =back
1.460     albertel 9252: 
1.648     raeburn  9253: =back
1.562     albertel 9254: 
1.306     albertel 9255: =cut
                   9256: 
                   9257: sub start_page {
1.309     albertel 9258:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9259:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9260: 
1.315     albertel 9261:     $env{'internal.start_page'}++;
1.1359    raeburn  9262:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9263: 
1.338     albertel 9264:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9265:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9266:     }
1.1316    raeburn  9267: 
                   9268:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9269:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9270:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9271:                 $args->{'no_primary_menu'} = 1;
                   9272:             }
                   9273:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9274:                 $args->{'no_inline_menu'} = 1;
                   9275:             }
                   9276:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9277:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9278:             }
                   9279:         } else {
                   9280:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9281:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9282:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9283:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9284:                     $args->{'no_primary_menu'} = 1;
                   9285:                 }
                   9286:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9287:                     $args->{'no_inline_menu'} = 1;
                   9288:                 }
                   9289:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9290:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9291:                 }
                   9292:             }
                   9293:         }
1.1316    raeburn  9294:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9295:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9296:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9297:     } elsif ($env{'request.course.id'}) {
                   9298:         my $expiretime=600;
                   9299:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9300:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9301:         }
                   9302:         my ($deeplinkmenu,$menuref);
                   9303:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9304:         if ($menucoll) {
                   9305:             if (ref($menuref) eq 'HASH') {
                   9306:                 %menu = %{$menuref};
                   9307:             }
                   9308:             if ($menu{'top'} eq 'n') {
                   9309:                 $args->{'no_primary_menu'} = 1;
                   9310:             }
                   9311:             if ($menu{'inline'} eq 'n') {
                   9312:                 unless (&Apache::lonnet::allowed('opa')) {
                   9313:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9314:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9315:                     my $crstype = &course_type();
                   9316:                     my $now = time;
                   9317:                     my $ccrole;
                   9318:                     if ($crstype eq 'Community') {
                   9319:                         $ccrole = 'co';
                   9320:                     } else {
                   9321:                         $ccrole = 'cc';
                   9322:                     }
                   9323:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9324:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9325:                         if ((($start) && ($start<0)) ||
                   9326:                             (($end) && ($end<$now))  ||
                   9327:                             (($start) && ($now<$start))) {
                   9328:                             $args->{'no_inline_menu'} = 1;
                   9329:                         }
                   9330:                     } else {
                   9331:                         $args->{'no_inline_menu'} = 1;
                   9332:                     }
                   9333:                 }
                   9334:             }
                   9335:         }
1.1316    raeburn  9336:     }
1.1359    raeburn  9337: 
1.338     albertel 9338:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9339: 	if ($args->{'frameset'}) {
                   9340: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9341: 						$args->{'add_entries'});
                   9342: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9343:         } else {
                   9344:             $result .=
                   9345:                 &bodytag($title, 
                   9346:                          $args->{'function'},       $args->{'add_entries'},
                   9347:                          $args->{'only_body'},      $args->{'domain'},
                   9348:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9349:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9350:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9351:         }
1.330     albertel 9352:     }
1.338     albertel 9353: 
1.315     albertel 9354:     if ($args->{'js_ready'}) {
1.713     kaisler  9355: 		$result = &js_ready($result);
1.315     albertel 9356:     }
1.320     albertel 9357:     if ($args->{'html_encode'}) {
1.713     kaisler  9358: 		$result = &html_encode($result);
                   9359:     }
                   9360: 
1.813     bisitz   9361:     # Preparation for new and consistent functionlist at top of screen
                   9362:     # if ($args->{'functionlist'}) {
                   9363:     #            $result .= &build_functionlist();
                   9364:     #}
                   9365: 
1.964     droeschl 9366:     # Don't add anything more if only_body wanted or in const space
                   9367:     return $result if    $args->{'only_body'} 
                   9368:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9369: 
                   9370:     #Breadcrumbs
1.758     kaisler  9371:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9372: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9373: 		#if any br links exists, add them to the breadcrumbs
                   9374: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9375: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9376: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9377: 			}
                   9378: 		}
1.1096    raeburn  9379:                 # if @advtools array contains items add then to the breadcrumbs
                   9380:                 if (@advtools > 0) {
                   9381:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9382:                 }
1.1272    raeburn  9383:                 my $menulink;
                   9384:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9385:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9386:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9387:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9388:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9389:                      (!$env{'request.role.adv'}))) {
                   9390:                     $menulink = 0;
                   9391:                 } else {
                   9392:                     undef($menulink);
                   9393:                 }
1.758     kaisler  9394: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9395: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9396: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9397:                 } else {
1.1272    raeburn  9398: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9399: 		}
1.320     albertel 9400:     }
1.315     albertel 9401:     return $result;
1.306     albertel 9402: }
                   9403: 
                   9404: sub end_page {
1.315     albertel 9405:     my ($args) = @_;
                   9406:     $env{'internal.end_page'}++;
1.330     albertel 9407:     my $result;
1.335     albertel 9408:     if ($args->{'discussion'}) {
                   9409: 	my ($target,$parser);
                   9410: 	if (ref($args->{'discussion'})) {
                   9411: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9412: 				$args->{'discussion'}{'parser'});
                   9413: 	}
                   9414: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9415:     }
1.330     albertel 9416:     if ($args->{'frameset'}) {
                   9417: 	$result .= '</frameset>';
                   9418:     } else {
1.635     raeburn  9419: 	$result .= &endbodytag($args);
1.330     albertel 9420:     }
1.1080    raeburn  9421:     unless ($args->{'notbody'}) {
                   9422:         $result .= "\n</html>";
                   9423:     }
1.330     albertel 9424: 
1.315     albertel 9425:     if ($args->{'js_ready'}) {
1.317     albertel 9426: 	$result = &js_ready($result);
1.315     albertel 9427:     }
1.335     albertel 9428: 
1.320     albertel 9429:     if ($args->{'html_encode'}) {
                   9430: 	$result = &html_encode($result);
                   9431:     }
1.335     albertel 9432: 
1.315     albertel 9433:     return $result;
                   9434: }
                   9435: 
1.1359    raeburn  9436: sub menucoll_in_effect {
                   9437:     my ($menucoll,$deeplinkmenu,%menu);
                   9438:     if ($env{'request.course.id'}) {
                   9439:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9440:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9441:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9442:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9443:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9444:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9445:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9446:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9447:                     if (ref($navmap)) {
                   9448:                         $deeplink = $navmap->get_mapparam(undef,
                   9449:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9450:                                                           '0.deeplink');
1.1370    raeburn  9451:                     } else {
                   9452:                         $check_login_symb = 1;
1.1362    raeburn  9453:                     }
                   9454:                 } else {
1.1370    raeburn  9455:                     my $symb = &Apache::lonnet::symbread();
                   9456:                     if ($symb) {
                   9457:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9458:                     } else {
                   9459:                         $check_login_symb = 1;
                   9460:                     }
1.1362    raeburn  9461:                 }
                   9462:             } else {
1.1370    raeburn  9463:                 $check_login_symb = 1;
                   9464:             }
                   9465:             if ($check_login_symb) {
1.1362    raeburn  9466:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9467:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9468:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9469:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9470:                     if (ref($navmap)) {
                   9471:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9472:                     }
                   9473:                 } else {
                   9474:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9475:                 }
                   9476:             }
1.1359    raeburn  9477:             if ($deeplink ne '') {
1.1378    raeburn  9478:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9479:                 if ($display =~ /^\d+$/) {
                   9480:                     $deeplinkmenu = 1;
                   9481:                     $menucoll = $display;
                   9482:                 }
                   9483:             }
                   9484:         }
                   9485:         if ($menucoll) {
                   9486:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9487:         }
                   9488:     }
                   9489:     return ($menucoll,$deeplinkmenu,\%menu);
                   9490: }
                   9491: 
1.1362    raeburn  9492: sub deeplink_login_symb {
                   9493:     my ($cnum,$cdom) = @_;
                   9494:     my $login_symb;
                   9495:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9496:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9497:     }
                   9498:     return $login_symb;
                   9499: }
                   9500: 
                   9501: sub symb_from_tinyurl {
                   9502:     my ($url,$cnum,$cdom) = @_;
                   9503:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9504:         my $key = $1;
                   9505:         my ($tinyurl,$login);
                   9506:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9507:         if (defined($cached)) {
                   9508:             $tinyurl = $result;
                   9509:         } else {
                   9510:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9511:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9512:             if ($currtiny{$key} ne '') {
                   9513:                 $tinyurl = $currtiny{$key};
                   9514:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9515:             }
1.1364    raeburn  9516:         }
                   9517:         if ($tinyurl ne '') {
                   9518:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9519:             if (wantarray) {
                   9520:                 return ($cnumreq,$symb);
                   9521:             } elsif ($cnumreq eq $cnum) {
                   9522:                 return $symb;
1.1362    raeburn  9523:             }
                   9524:         }
                   9525:     }
1.1364    raeburn  9526:     if (wantarray) {
                   9527:         return ();
                   9528:     } else {
                   9529:         return;
                   9530:     }
1.1362    raeburn  9531: }
                   9532: 
1.1034    www      9533: sub wishlist_window {
                   9534:     return(<<'ENDWISHLIST');
1.1046    raeburn  9535: <script type="text/javascript">
1.1034    www      9536: // <![CDATA[
                   9537: // <!-- BEGIN LON-CAPA Internal
                   9538: function set_wishlistlink(title, path) {
                   9539:     if (!title) {
                   9540:         title = document.title;
                   9541:         title = title.replace(/^LON-CAPA /,'');
                   9542:     }
1.1175    raeburn  9543:     title = encodeURIComponent(title);
1.1203    raeburn  9544:     title = title.replace("'","\\\'");
1.1034    www      9545:     if (!path) {
                   9546:         path = location.pathname;
                   9547:     }
1.1175    raeburn  9548:     path = encodeURIComponent(path);
1.1203    raeburn  9549:     path = path.replace("'","\\\'");
1.1034    www      9550:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9551:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9552: }
                   9553: // END LON-CAPA Internal -->
                   9554: // ]]>
                   9555: </script>
                   9556: ENDWISHLIST
                   9557: }
                   9558: 
1.1030    www      9559: sub modal_window {
                   9560:     return(<<'ENDMODAL');
1.1046    raeburn  9561: <script type="text/javascript">
1.1030    www      9562: // <![CDATA[
                   9563: // <!-- BEGIN LON-CAPA Internal
                   9564: var modalWindow = {
                   9565: 	parent:"body",
                   9566: 	windowId:null,
                   9567: 	content:null,
                   9568: 	width:null,
                   9569: 	height:null,
                   9570: 	close:function()
                   9571: 	{
                   9572: 	        $(".LCmodal-window").remove();
                   9573: 	        $(".LCmodal-overlay").remove();
                   9574: 	},
                   9575: 	open:function()
                   9576: 	{
                   9577: 		var modal = "";
                   9578: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9579: 		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;\">";
                   9580: 		modal += this.content;
                   9581: 		modal += "</div>";	
                   9582: 
                   9583: 		$(this.parent).append(modal);
                   9584: 
                   9585: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9586: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9587: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9588: 	}
                   9589: };
1.1140    raeburn  9590: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9591: 	{
1.1266    raeburn  9592:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9593: 		modalWindow.windowId = "myModal";
                   9594: 		modalWindow.width = width;
                   9595: 		modalWindow.height = height;
1.1196    raeburn  9596: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9597: 		modalWindow.open();
1.1208    raeburn  9598: 	};
1.1030    www      9599: // END LON-CAPA Internal -->
                   9600: // ]]>
                   9601: </script>
                   9602: ENDMODAL
                   9603: }
                   9604: 
                   9605: sub modal_link {
1.1140    raeburn  9606:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9607:     unless ($width) { $width=480; }
                   9608:     unless ($height) { $height=400; }
1.1031    www      9609:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9610:     unless ($transparency) { $transparency='true'; }
                   9611: 
1.1074    raeburn  9612:     my $target_attr;
                   9613:     if (defined($target)) {
                   9614:         $target_attr = 'target="'.$target.'"';
                   9615:     }
                   9616:     return <<"ENDLINK";
1.1336    raeburn  9617: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9618: ENDLINK
1.1030    www      9619: }
                   9620: 
1.1032    www      9621: sub modal_adhoc_script {
1.1365    raeburn  9622:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9623:     my $mathjax;
                   9624:     if ($possmathjax) {
                   9625:         $mathjax = <<'ENDJAX';
                   9626:                if (typeof MathJax == 'object') {
                   9627:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9628:                }
                   9629: ENDJAX
                   9630:     }
1.1032    www      9631:     return (<<ENDADHOC);
1.1046    raeburn  9632: <script type="text/javascript">
1.1032    www      9633: // <![CDATA[
                   9634:         var $funcname = function()
                   9635:         {
                   9636:                 modalWindow.windowId = "myModal";
                   9637:                 modalWindow.width = $width;
                   9638:                 modalWindow.height = $height;
                   9639:                 modalWindow.content = '$content';
                   9640:                 modalWindow.open();
1.1365    raeburn  9641:                 $mathjax
1.1032    www      9642:         };  
                   9643: // ]]>
                   9644: </script>
                   9645: ENDADHOC
                   9646: }
                   9647: 
1.1041    www      9648: sub modal_adhoc_inner {
1.1365    raeburn  9649:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9650:     my $innerwidth=$width-20;
                   9651:     $content=&js_ready(
1.1140    raeburn  9652:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9653:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9654:                  $content.
1.1041    www      9655:                  &end_scrollbox().
1.1140    raeburn  9656:                  &end_page()
1.1041    www      9657:              );
1.1365    raeburn  9658:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9659: }
                   9660: 
                   9661: sub modal_adhoc_window {
1.1365    raeburn  9662:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9663:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9664:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9665: }
                   9666: 
                   9667: sub modal_adhoc_launch {
                   9668:     my ($funcname,$width,$height,$content)=@_;
                   9669:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9670: <script type="text/javascript">
                   9671: // <![CDATA[
                   9672: $funcname();
                   9673: // ]]>
                   9674: </script>
                   9675: ENDLAUNCH
                   9676: }
                   9677: 
                   9678: sub modal_adhoc_close {
                   9679:     return (<<ENDCLOSE);
                   9680: <script type="text/javascript">
                   9681: // <![CDATA[
                   9682: modalWindow.close();
                   9683: // ]]>
                   9684: </script>
                   9685: ENDCLOSE
                   9686: }
                   9687: 
1.1038    www      9688: sub togglebox_script {
                   9689:    return(<<ENDTOGGLE);
                   9690: <script type="text/javascript"> 
                   9691: // <![CDATA[
                   9692: function LCtoggleDisplay(id,hidetext,showtext) {
                   9693:    link = document.getElementById(id + "link").childNodes[0];
                   9694:    with (document.getElementById(id).style) {
                   9695:       if (display == "none" ) {
                   9696:           display = "inline";
                   9697:           link.nodeValue = hidetext;
                   9698:         } else {
                   9699:           display = "none";
                   9700:           link.nodeValue = showtext;
                   9701:        }
                   9702:    }
                   9703: }
                   9704: // ]]>
                   9705: </script>
                   9706: ENDTOGGLE
                   9707: }
                   9708: 
1.1039    www      9709: sub start_togglebox {
                   9710:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9711:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9712:     unless ($showtext) { $showtext=&mt('show'); }
                   9713:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9714:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9715:     return &start_data_table().
                   9716:            &start_data_table_header_row().
                   9717:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9718:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9719:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9720:            &end_data_table_header_row().
                   9721:            '<tr id="'.$id.'" style="display:none""><td>';
                   9722: }
                   9723: 
                   9724: sub end_togglebox {
                   9725:     return '</td></tr>'.&end_data_table();
                   9726: }
                   9727: 
1.1041    www      9728: sub LCprogressbar_script {
1.1302    raeburn  9729:    my ($id,$number_to_do)=@_;
                   9730:    if ($number_to_do) {
                   9731:        return(<<ENDPROGRESS);
1.1041    www      9732: <script type="text/javascript">
                   9733: // <![CDATA[
1.1045    www      9734: \$('#progressbar$id').progressbar({
1.1041    www      9735:   value: 0,
                   9736:   change: function(event, ui) {
                   9737:     var newVal = \$(this).progressbar('option', 'value');
                   9738:     \$('.pblabel', this).text(LCprogressTxt);
                   9739:   }
                   9740: });
                   9741: // ]]>
                   9742: </script>
                   9743: ENDPROGRESS
1.1302    raeburn  9744:    } else {
                   9745:        return(<<ENDPROGRESS);
                   9746: <script type="text/javascript">
                   9747: // <![CDATA[
                   9748: \$('#progressbar$id').progressbar({
                   9749:   value: false,
                   9750:   create: function(event, ui) {
                   9751:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9752:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9753:   }
                   9754: });
                   9755: // ]]>
                   9756: </script>
                   9757: ENDPROGRESS
                   9758:    }
1.1041    www      9759: }
                   9760: 
                   9761: sub LCprogressbarUpdate_script {
                   9762:    return(<<ENDPROGRESSUPDATE);
                   9763: <style type="text/css">
                   9764: .ui-progressbar { position:relative; }
1.1302    raeburn  9765: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      9766: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9767: </style>
                   9768: <script type="text/javascript">
                   9769: // <![CDATA[
1.1045    www      9770: var LCprogressTxt='---';
                   9771: 
1.1302    raeburn  9772: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9773:    LCprogressTxt=progresstext;
1.1302    raeburn  9774:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9775:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9776:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9777:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9778:    } else {
                   9779:        \$('#progressbar'+id).progressbar('value',percent);
                   9780:    }
1.1041    www      9781: }
                   9782: // ]]>
                   9783: </script>
                   9784: ENDPROGRESSUPDATE
                   9785: }
                   9786: 
1.1042    www      9787: my $LClastpercent;
1.1045    www      9788: my $LCidcnt;
                   9789: my $LCcurrentid;
1.1042    www      9790: 
1.1041    www      9791: sub LCprogressbar {
1.1302    raeburn  9792:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9793:     $LClastpercent=0;
1.1045    www      9794:     $LCidcnt++;
                   9795:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9796:     my ($starting,$content);
                   9797:     if ($number_to_do) {
                   9798:         $starting=&mt('Starting');
                   9799:         $content=(<<ENDPROGBAR);
                   9800: $preamble
1.1045    www      9801:   <div id="progressbar$LCcurrentid">
1.1041    www      9802:     <span class="pblabel">$starting</span>
                   9803:   </div>
                   9804: ENDPROGBAR
1.1302    raeburn  9805:     } else {
                   9806:         $starting=&mt('Loading...');
                   9807:         $LClastpercent='false';
                   9808:         $content=(<<ENDPROGBAR);
                   9809: $preamble
                   9810:   <div id="progressbar$LCcurrentid">
                   9811:       <div class="progress-label">$starting</div>
                   9812:   </div>
                   9813: ENDPROGBAR
                   9814:     }
                   9815:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9816: }
                   9817: 
                   9818: sub LCprogressbarUpdate {
1.1302    raeburn  9819:     my ($r,$val,$text,$number_to_do)=@_;
                   9820:     if ($number_to_do) {
                   9821:         unless ($val) { 
                   9822:             if ($LClastpercent) {
                   9823:                 $val=$LClastpercent;
                   9824:             } else {
                   9825:                 $val=0;
                   9826:             }
                   9827:         }
                   9828:         if ($val<0) { $val=0; }
                   9829:         if ($val>100) { $val=0; }
                   9830:         $LClastpercent=$val;
                   9831:         unless ($text) { $text=$val.'%'; }
                   9832:     } else {
                   9833:         $val = 'false';
1.1042    www      9834:     }
1.1041    www      9835:     $text=&js_ready($text);
1.1044    www      9836:     &r_print($r,<<ENDUPDATE);
1.1041    www      9837: <script type="text/javascript">
                   9838: // <![CDATA[
1.1302    raeburn  9839: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9840: // ]]>
                   9841: </script>
                   9842: ENDUPDATE
1.1035    www      9843: }
                   9844: 
1.1042    www      9845: sub LCprogressbarClose {
                   9846:     my ($r)=@_;
                   9847:     $LClastpercent=0;
1.1044    www      9848:     &r_print($r,<<ENDCLOSE);
1.1042    www      9849: <script type="text/javascript">
                   9850: // <![CDATA[
1.1045    www      9851: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9852: // ]]>
                   9853: </script>
                   9854: ENDCLOSE
1.1044    www      9855: }
                   9856: 
                   9857: sub r_print {
                   9858:     my ($r,$to_print)=@_;
                   9859:     if ($r) {
                   9860:       $r->print($to_print);
                   9861:       $r->rflush();
                   9862:     } else {
                   9863:       print($to_print);
                   9864:     }
1.1042    www      9865: }
                   9866: 
1.320     albertel 9867: sub html_encode {
                   9868:     my ($result) = @_;
                   9869: 
1.322     albertel 9870:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9871:     
                   9872:     return $result;
                   9873: }
1.1044    www      9874: 
1.317     albertel 9875: sub js_ready {
                   9876:     my ($result) = @_;
                   9877: 
1.323     albertel 9878:     $result =~ s/[\n\r]/ /xmsg;
                   9879:     $result =~ s/\\/\\\\/xmsg;
                   9880:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9881:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9882:     
                   9883:     return $result;
                   9884: }
                   9885: 
1.315     albertel 9886: sub validate_page {
                   9887:     if (  exists($env{'internal.start_page'})
1.316     albertel 9888: 	  &&     $env{'internal.start_page'} > 1) {
                   9889: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9890: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9891: 				 $ENV{'request.filename'});
1.315     albertel 9892:     }
                   9893:     if (  exists($env{'internal.end_page'})
1.316     albertel 9894: 	  &&     $env{'internal.end_page'} > 1) {
                   9895: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9896: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9897: 				 $env{'request.filename'});
1.315     albertel 9898:     }
                   9899:     if (     exists($env{'internal.start_page'})
                   9900: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9901: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9902: 				 $env{'request.filename'});
1.315     albertel 9903:     }
                   9904:     if (   ! exists($env{'internal.start_page'})
                   9905: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9906: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9907: 				 $env{'request.filename'});
1.315     albertel 9908:     }
1.306     albertel 9909: }
1.315     albertel 9910: 
1.996     www      9911: 
                   9912: sub start_scrollbox {
1.1140    raeburn  9913:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9914:     unless ($outerwidth) { $outerwidth='520px'; }
                   9915:     unless ($width) { $width='500px'; }
                   9916:     unless ($height) { $height='200px'; }
1.1075    raeburn  9917:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9918:     if ($id ne '') {
1.1140    raeburn  9919:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9920:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9921:     }
1.1075    raeburn  9922:     if ($bgcolor ne '') {
                   9923:         $tdcol = "background-color: $bgcolor;";
                   9924:     }
1.1137    raeburn  9925:     my $nicescroll_js;
                   9926:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9927:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9928:     }
                   9929:     return <<"END";
                   9930: $nicescroll_js
                   9931: 
                   9932: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9933: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9934: END
                   9935: }
                   9936: 
                   9937: sub end_scrollbox {
                   9938:     return '</div></td></tr></table>';
                   9939: }
                   9940: 
                   9941: sub nicescroll_javascript {
                   9942:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9943:     my %options;
                   9944:     if (ref($cursor) eq 'HASH') {
                   9945:         %options = %{$cursor};
                   9946:     }
                   9947:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9948:         $options{'railalign'} = 'left';
                   9949:     }
                   9950:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9951:         my $function  = &get_users_function();
                   9952:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9953:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9954:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9955:         }
1.1140    raeburn  9956:     }
                   9957:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9958:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9959:             $options{'cursoropacity'}='1.0';
                   9960:         }
1.1140    raeburn  9961:     } else {
                   9962:         $options{'cursoropacity'}='1.0';
                   9963:     }
                   9964:     if ($options{'cursorfixedheight'} eq 'none') {
                   9965:         delete($options{'cursorfixedheight'});
                   9966:     } else {
                   9967:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9968:     }
                   9969:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9970:         delete($options{'railoffset'});
                   9971:     }
                   9972:     my @niceoptions;
                   9973:     while (my($key,$value) = each(%options)) {
                   9974:         if ($value =~ /^\{.+\}$/) {
                   9975:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9976:         } else {
1.1140    raeburn  9977:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9978:         }
1.1140    raeburn  9979:     }
                   9980:     my $nicescroll_js = '
1.1137    raeburn  9981: $(document).ready(
1.1140    raeburn  9982:       function() {
                   9983:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9984:       }
1.1137    raeburn  9985: );
                   9986: ';
1.1140    raeburn  9987:     if ($framecheck) {
                   9988:         $nicescroll_js .= '
                   9989: function expand_div(caller) {
                   9990:     if (top === self) {
                   9991:         document.getElementById("'.$id.'").style.width = "auto";
                   9992:         document.getElementById("'.$id.'").style.height = "auto";
                   9993:     } else {
                   9994:         try {
                   9995:             if (parent.frames) {
                   9996:                 if (parent.frames.length > 1) {
                   9997:                     var framesrc = parent.frames[1].location.href;
                   9998:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9999:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10000:                         document.getElementById("'.$id.'").style.width = "auto";
                   10001:                         document.getElementById("'.$id.'").style.height = "auto";
                   10002:                     }
                   10003:                 }
                   10004:             }
                   10005:         } catch (e) {
                   10006:             return;
                   10007:         }
1.1137    raeburn  10008:     }
1.1140    raeburn  10009:     return;
1.996     www      10010: }
1.1140    raeburn  10011: ';
                   10012:     }
                   10013:     if ($needjsready) {
                   10014:         $nicescroll_js = '
                   10015: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10016:     } else {
                   10017:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10018:     }
                   10019:     return $nicescroll_js;
1.996     www      10020: }
                   10021: 
1.318     albertel 10022: sub simple_error_page {
1.1150    bisitz   10023:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10024:     my %displayargs;
1.1151    raeburn  10025:     if (ref($args) eq 'HASH') {
                   10026:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10027:         if ($args->{'only_body'}) {
                   10028:             $displayargs{'only_body'} = 1;
                   10029:         }
                   10030:         if ($args->{'no_nav_bar'}) {
                   10031:             $displayargs{'no_nav_bar'} = 1;
                   10032:         }
1.1151    raeburn  10033:     } else {
                   10034:         $msg = &mt($msg);
                   10035:     }
1.1150    bisitz   10036: 
1.318     albertel 10037:     my $page =
1.1304    raeburn  10038: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10039: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10040: 	&Apache::loncommon::end_page();
                   10041:     if (ref($r)) {
                   10042: 	$r->print($page);
1.327     albertel 10043: 	return;
1.318     albertel 10044:     }
                   10045:     return $page;
                   10046: }
1.347     albertel 10047: 
                   10048: {
1.610     albertel 10049:     my @row_count;
1.961     onken    10050: 
                   10051:     sub start_data_table_count {
                   10052:         unshift(@row_count, 0);
                   10053:         return;
                   10054:     }
                   10055: 
                   10056:     sub end_data_table_count {
                   10057:         shift(@row_count);
                   10058:         return;
                   10059:     }
                   10060: 
1.347     albertel 10061:     sub start_data_table {
1.1018    raeburn  10062: 	my ($add_class,$id) = @_;
1.422     albertel 10063: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10064:         my $table_id;
                   10065:         if (defined($id)) {
                   10066:             $table_id = ' id="'.$id.'"';
                   10067:         }
1.961     onken    10068: 	&start_data_table_count();
1.1018    raeburn  10069: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10070:     }
                   10071: 
                   10072:     sub end_data_table {
1.961     onken    10073: 	&end_data_table_count();
1.389     albertel 10074: 	return '</table>'."\n";;
1.347     albertel 10075:     }
                   10076: 
                   10077:     sub start_data_table_row {
1.974     wenzelju 10078: 	my ($add_class, $id) = @_;
1.610     albertel 10079: 	$row_count[0]++;
                   10080: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10081: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10082:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10083:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10084:     }
1.471     banghart 10085:     
                   10086:     sub continue_data_table_row {
1.974     wenzelju 10087: 	my ($add_class, $id) = @_;
1.610     albertel 10088: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10089: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10090:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10091:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10092:     }
1.347     albertel 10093: 
                   10094:     sub end_data_table_row {
1.389     albertel 10095: 	return '</tr>'."\n";;
1.347     albertel 10096:     }
1.367     www      10097: 
1.421     albertel 10098:     sub start_data_table_empty_row {
1.707     bisitz   10099: #	$row_count[0]++;
1.421     albertel 10100: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10101:     }
                   10102: 
                   10103:     sub end_data_table_empty_row {
                   10104: 	return '</tr>'."\n";;
                   10105:     }
                   10106: 
1.367     www      10107:     sub start_data_table_header_row {
1.389     albertel 10108: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10109:     }
                   10110: 
                   10111:     sub end_data_table_header_row {
1.389     albertel 10112: 	return '</tr>'."\n";;
1.367     www      10113:     }
1.890     droeschl 10114: 
                   10115:     sub data_table_caption {
                   10116:         my $caption = shift;
                   10117:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10118:     }
1.347     albertel 10119: }
                   10120: 
1.548     albertel 10121: =pod
                   10122: 
                   10123: =item * &inhibit_menu_check($arg)
                   10124: 
                   10125: Checks for a inhibitmenu state and generates output to preserve it
                   10126: 
                   10127: Inputs:         $arg - can be any of
                   10128:                      - undef - in which case the return value is a string 
                   10129:                                to add  into arguments list of a uri
                   10130:                      - 'input' - in which case the return value is a HTML
                   10131:                                  <form> <input> field of type hidden to
                   10132:                                  preserve the value
                   10133:                      - a url - in which case the return value is the url with
                   10134:                                the neccesary cgi args added to preserve the
                   10135:                                inhibitmenu state
                   10136:                      - a ref to a url - no return value, but the string is
                   10137:                                         updated to include the neccessary cgi
                   10138:                                         args to preserve the inhibitmenu state
                   10139: 
                   10140: =cut
                   10141: 
                   10142: sub inhibit_menu_check {
                   10143:     my ($arg) = @_;
                   10144:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10145:     if ($arg eq 'input') {
                   10146: 	if ($env{'form.inhibitmenu'}) {
                   10147: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10148: 	} else {
                   10149: 	    return
                   10150: 	}
                   10151:     }
                   10152:     if ($env{'form.inhibitmenu'}) {
                   10153: 	if (ref($arg)) {
                   10154: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10155: 	} elsif ($arg eq '') {
                   10156: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10157: 	} else {
                   10158: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10159: 	}
                   10160:     }
                   10161:     if (!ref($arg)) {
                   10162: 	return $arg;
                   10163:     }
                   10164: }
                   10165: 
1.251     albertel 10166: ###############################################
1.182     matthew  10167: 
                   10168: =pod
                   10169: 
1.549     albertel 10170: =back
                   10171: 
                   10172: =head1 User Information Routines
                   10173: 
                   10174: =over 4
                   10175: 
1.405     albertel 10176: =item * &get_users_function()
1.182     matthew  10177: 
                   10178: Used by &bodytag to determine the current users primary role.
                   10179: Returns either 'student','coordinator','admin', or 'author'.
                   10180: 
                   10181: =cut
                   10182: 
                   10183: ###############################################
                   10184: sub get_users_function {
1.815     tempelho 10185:     my $function = 'norole';
1.818     tempelho 10186:     if ($env{'request.role'}=~/^(st)/) {
                   10187:         $function='student';
                   10188:     }
1.907     raeburn  10189:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10190:         $function='coordinator';
                   10191:     }
1.258     albertel 10192:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10193:         $function='admin';
                   10194:     }
1.826     bisitz   10195:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10196:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10197:         $function='author';
                   10198:     }
                   10199:     return $function;
1.54      www      10200: }
1.99      www      10201: 
                   10202: ###############################################
                   10203: 
1.233     raeburn  10204: =pod
                   10205: 
1.821     raeburn  10206: =item * &show_course()
                   10207: 
                   10208: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10209: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10210: 
                   10211: Inputs:
                   10212: None
                   10213: 
                   10214: Outputs:
                   10215: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10216: 
                   10217: =cut
                   10218: 
                   10219: ###############################################
                   10220: sub show_course {
                   10221:     my $course = !$env{'user.adv'};
                   10222:     if (!$env{'user.adv'}) {
                   10223:         foreach my $env (keys(%env)) {
                   10224:             next if ($env !~ m/^user\.priv\./);
                   10225:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10226:                 $course = 0;
                   10227:                 last;
                   10228:             }
                   10229:         }
                   10230:     }
                   10231:     return $course;
                   10232: }
                   10233: 
                   10234: ###############################################
                   10235: 
                   10236: =pod
                   10237: 
1.542     raeburn  10238: =item * &check_user_status()
1.274     raeburn  10239: 
                   10240: Determines current status of supplied role for a
                   10241: specific user. Roles can be active, previous or future.
                   10242: 
                   10243: Inputs: 
                   10244: user's domain, user's username, course's domain,
1.375     raeburn  10245: course's number, optional section ID.
1.274     raeburn  10246: 
                   10247: Outputs:
                   10248: role status: active, previous or future. 
                   10249: 
                   10250: =cut
                   10251: 
                   10252: sub check_user_status {
1.412     raeburn  10253:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10254:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10255:     my @uroles = keys(%userinfo);
1.274     raeburn  10256:     my $srchstr;
                   10257:     my $active_chk = 'none';
1.412     raeburn  10258:     my $now = time;
1.274     raeburn  10259:     if (@uroles > 0) {
1.908     raeburn  10260:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10261:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10262:         } else {
1.412     raeburn  10263:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10264:         }
                   10265:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10266:             my $role_end = 0;
                   10267:             my $role_start = 0;
                   10268:             $active_chk = 'active';
1.412     raeburn  10269:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10270:                 $role_end = $1;
                   10271:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10272:                     $role_start = $1;
1.274     raeburn  10273:                 }
                   10274:             }
                   10275:             if ($role_start > 0) {
1.412     raeburn  10276:                 if ($now < $role_start) {
1.274     raeburn  10277:                     $active_chk = 'future';
                   10278:                 }
                   10279:             }
                   10280:             if ($role_end > 0) {
1.412     raeburn  10281:                 if ($now > $role_end) {
1.274     raeburn  10282:                     $active_chk = 'previous';
                   10283:                 }
                   10284:             }
                   10285:         }
                   10286:     }
                   10287:     return $active_chk;
                   10288: }
                   10289: 
                   10290: ###############################################
                   10291: 
                   10292: =pod
                   10293: 
1.405     albertel 10294: =item * &get_sections()
1.233     raeburn  10295: 
                   10296: Determines all the sections for a course including
                   10297: sections with students and sections containing other roles.
1.419     raeburn  10298: Incoming parameters: 
                   10299: 
                   10300: 1. domain
                   10301: 2. course number 
                   10302: 3. reference to array containing roles for which sections should 
                   10303: be gathered (optional).
                   10304: 4. reference to array containing status types for which sections 
                   10305: should be gathered (optional).
                   10306: 
                   10307: If the third argument is undefined, sections are gathered for any role. 
                   10308: If the fourth argument is undefined, sections are gathered for any status.
                   10309: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10310:  
1.374     raeburn  10311: Returns section hash (keys are section IDs, values are
                   10312: number of users in each section), subject to the
1.419     raeburn  10313: optional roles filter, optional status filter 
1.233     raeburn  10314: 
                   10315: =cut
                   10316: 
                   10317: ###############################################
                   10318: sub get_sections {
1.419     raeburn  10319:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10320:     if (!defined($cdom) || !defined($cnum)) {
                   10321:         my $cid =  $env{'request.course.id'};
                   10322: 
                   10323: 	return if (!defined($cid));
                   10324: 
                   10325:         $cdom = $env{'course.'.$cid.'.domain'};
                   10326:         $cnum = $env{'course.'.$cid.'.num'};
                   10327:     }
                   10328: 
                   10329:     my %sectioncount;
1.419     raeburn  10330:     my $now = time;
1.240     albertel 10331: 
1.1118    raeburn  10332:     my $check_students = 1;
                   10333:     my $only_students = 0;
                   10334:     if (ref($possible_roles) eq 'ARRAY') {
                   10335:         if (grep(/^st$/,@{$possible_roles})) {
                   10336:             if (@{$possible_roles} == 1) {
                   10337:                 $only_students = 1;
                   10338:             }
                   10339:         } else {
                   10340:             $check_students = 0;
                   10341:         }
                   10342:     }
                   10343: 
                   10344:     if ($check_students) { 
1.276     albertel 10345: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10346: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10347: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10348:         my $start_index = &Apache::loncoursedata::CL_START();
                   10349:         my $end_index = &Apache::loncoursedata::CL_END();
                   10350:         my $status;
1.366     albertel 10351: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10352: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10353: 				                     $data->[$status_index],
                   10354:                                                      $data->[$start_index],
                   10355:                                                      $data->[$end_index]);
                   10356:             if ($stu_status eq 'Active') {
                   10357:                 $status = 'active';
                   10358:             } elsif ($end < $now) {
                   10359:                 $status = 'previous';
                   10360:             } elsif ($start > $now) {
                   10361:                 $status = 'future';
                   10362:             } 
                   10363: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10364:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10365:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10366: 		    $sectioncount{$section}++;
                   10367:                 }
1.240     albertel 10368: 	    }
                   10369: 	}
                   10370:     }
1.1118    raeburn  10371:     if ($only_students) {
                   10372:         return %sectioncount;
                   10373:     }
1.240     albertel 10374:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10375:     foreach my $user (sort(keys(%courseroles))) {
                   10376: 	if ($user !~ /^(\w{2})/) { next; }
                   10377: 	my ($role) = ($user =~ /^(\w{2})/);
                   10378: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10379: 	my ($section,$status);
1.240     albertel 10380: 	if ($role eq 'cr' &&
                   10381: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10382: 	    $section=$1;
                   10383: 	}
                   10384: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10385: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10386:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10387:         if ($end == -1 && $start == -1) {
                   10388:             next; #deleted role
                   10389:         }
                   10390:         if (!defined($possible_status)) { 
                   10391:             $sectioncount{$section}++;
                   10392:         } else {
                   10393:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10394:                 $status = 'active';
                   10395:             } elsif ($end < $now) {
                   10396:                 $status = 'future';
                   10397:             } elsif ($start > $now) {
                   10398:                 $status = 'previous';
                   10399:             }
                   10400:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10401:                 $sectioncount{$section}++;
                   10402:             }
                   10403:         }
1.233     raeburn  10404:     }
1.366     albertel 10405:     return %sectioncount;
1.233     raeburn  10406: }
                   10407: 
1.274     raeburn  10408: ###############################################
1.294     raeburn  10409: 
                   10410: =pod
1.405     albertel 10411: 
                   10412: =item * &get_course_users()
                   10413: 
1.275     raeburn  10414: Retrieves usernames:domains for users in the specified course
                   10415: with specific role(s), and access status. 
                   10416: 
                   10417: Incoming parameters:
1.277     albertel 10418: 1. course domain
                   10419: 2. course number
                   10420: 3. access status: users must have - either active, 
1.275     raeburn  10421: previous, future, or all.
1.277     albertel 10422: 4. reference to array of permissible roles
1.288     raeburn  10423: 5. reference to array of section restrictions (optional)
                   10424: 6. reference to results object (hash of hashes).
                   10425: 7. reference to optional userdata hash
1.609     raeburn  10426: 8. reference to optional statushash
1.630     raeburn  10427: 9. flag if privileged users (except those set to unhide in
                   10428:    course settings) should be excluded    
1.609     raeburn  10429: Keys of top level results hash are roles.
1.275     raeburn  10430: Keys of inner hashes are username:domain, with 
                   10431: values set to access type.
1.288     raeburn  10432: Optional userdata hash returns an array with arguments in the 
                   10433: same order as loncoursedata::get_classlist() for student data.
                   10434: 
1.609     raeburn  10435: Optional statushash returns
                   10436: 
1.288     raeburn  10437: Entries for end, start, section and status are blank because
                   10438: of the possibility of multiple values for non-student roles.
                   10439: 
1.275     raeburn  10440: =cut
1.405     albertel 10441: 
1.275     raeburn  10442: ###############################################
1.405     albertel 10443: 
1.275     raeburn  10444: sub get_course_users {
1.630     raeburn  10445:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10446:     my %idx = ();
1.419     raeburn  10447:     my %seclists;
1.288     raeburn  10448: 
                   10449:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10450:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10451:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10452:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10453:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10454:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10455:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10456:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10457: 
1.290     albertel 10458:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10459:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10460:         my $now = time;
1.277     albertel 10461:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10462:             my $match = 0;
1.412     raeburn  10463:             my $secmatch = 0;
1.419     raeburn  10464:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10465:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10466:             if ($section eq '') {
                   10467:                 $section = 'none';
                   10468:             }
1.291     albertel 10469:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10470:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10471:                     $secmatch = 1;
                   10472:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10473:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10474:                         $secmatch = 1;
                   10475:                     }
                   10476:                 } else {  
1.419     raeburn  10477: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10478: 		        $secmatch = 1;
                   10479:                     }
1.290     albertel 10480: 		}
1.412     raeburn  10481:                 if (!$secmatch) {
                   10482:                     next;
                   10483:                 }
1.419     raeburn  10484:             }
1.275     raeburn  10485:             if (defined($$types{'active'})) {
1.288     raeburn  10486:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10487:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10488:                     $match = 1;
1.275     raeburn  10489:                 }
                   10490:             }
                   10491:             if (defined($$types{'previous'})) {
1.609     raeburn  10492:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10493:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10494:                     $match = 1;
1.275     raeburn  10495:                 }
                   10496:             }
                   10497:             if (defined($$types{'future'})) {
1.609     raeburn  10498:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10499:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10500:                     $match = 1;
1.275     raeburn  10501:                 }
                   10502:             }
1.609     raeburn  10503:             if ($match) {
                   10504:                 push(@{$seclists{$student}},$section);
                   10505:                 if (ref($userdata) eq 'HASH') {
                   10506:                     $$userdata{$student} = $$classlist{$student};
                   10507:                 }
                   10508:                 if (ref($statushash) eq 'HASH') {
                   10509:                     $statushash->{$student}{'st'}{$section} = $status;
                   10510:                 }
1.288     raeburn  10511:             }
1.275     raeburn  10512:         }
                   10513:     }
1.412     raeburn  10514:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10515:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10516:         my $now = time;
1.609     raeburn  10517:         my %displaystatus = ( previous => 'Expired',
                   10518:                               active   => 'Active',
                   10519:                               future   => 'Future',
                   10520:                             );
1.1121    raeburn  10521:         my (%nothide,@possdoms);
1.630     raeburn  10522:         if ($hidepriv) {
                   10523:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10524:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10525:                 if ($user !~ /:/) {
                   10526:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10527:                 } else {
                   10528:                     $nothide{$user} = 1;
                   10529:                 }
                   10530:             }
1.1121    raeburn  10531:             my @possdoms = ($cdom);
                   10532:             if ($coursehash{'checkforpriv'}) {
                   10533:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10534:             }
1.630     raeburn  10535:         }
1.439     raeburn  10536:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10537:             my $match = 0;
1.412     raeburn  10538:             my $secmatch = 0;
1.439     raeburn  10539:             my $status;
1.412     raeburn  10540:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10541:             $user =~ s/:$//;
1.439     raeburn  10542:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10543:             if ($end == -1 || $start == -1) {
                   10544:                 next;
                   10545:             }
                   10546:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10547:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10548:                 my ($uname,$udom) = split(/:/,$user);
                   10549:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10550:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10551:                         $secmatch = 1;
                   10552:                     } elsif ($usec eq '') {
1.420     albertel 10553:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10554:                             $secmatch = 1;
                   10555:                         }
                   10556:                     } else {
                   10557:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10558:                             $secmatch = 1;
                   10559:                         }
                   10560:                     }
                   10561:                     if (!$secmatch) {
                   10562:                         next;
                   10563:                     }
1.288     raeburn  10564:                 }
1.419     raeburn  10565:                 if ($usec eq '') {
                   10566:                     $usec = 'none';
                   10567:                 }
1.275     raeburn  10568:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10569:                     if ($hidepriv) {
1.1121    raeburn  10570:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10571:                             (!$nothide{$uname.':'.$udom})) {
                   10572:                             next;
                   10573:                         }
                   10574:                     }
1.503     raeburn  10575:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10576:                         $status = 'previous';
                   10577:                     } elsif ($start > $now) {
                   10578:                         $status = 'future';
                   10579:                     } else {
                   10580:                         $status = 'active';
                   10581:                     }
1.277     albertel 10582:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10583:                         if ($status eq $type) {
1.420     albertel 10584:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10585:                                 push(@{$$users{$role}{$user}},$type);
                   10586:                             }
1.288     raeburn  10587:                             $match = 1;
                   10588:                         }
                   10589:                     }
1.419     raeburn  10590:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10591:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10592: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10593:                         }
1.420     albertel 10594:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10595:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10596:                         }
1.609     raeburn  10597:                         if (ref($statushash) eq 'HASH') {
                   10598:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10599:                         }
1.275     raeburn  10600:                     }
                   10601:                 }
                   10602:             }
                   10603:         }
1.290     albertel 10604:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10605:             if ((defined($cdom)) && (defined($cnum))) {
                   10606:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10607:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10608:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10609:                     next if ($owner eq '');
                   10610:                     my ($ownername,$ownerdom);
                   10611:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10612:                         $ownername = $1;
                   10613:                         $ownerdom = $2;
                   10614:                     } else {
                   10615:                         $ownername = $owner;
                   10616:                         $ownerdom = $cdom;
                   10617:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10618:                     }
                   10619:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10620:                     if (defined($userdata) && 
1.609     raeburn  10621: 			!exists($$userdata{$owner})) {
                   10622: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10623:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10624:                             push(@{$seclists{$owner}},'none');
                   10625:                         }
                   10626:                         if (ref($statushash) eq 'HASH') {
                   10627:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10628:                         }
1.290     albertel 10629: 		    }
1.279     raeburn  10630:                 }
                   10631:             }
                   10632:         }
1.419     raeburn  10633:         foreach my $user (keys(%seclists)) {
                   10634:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10635:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10636:         }
1.275     raeburn  10637:     }
                   10638:     return;
                   10639: }
                   10640: 
1.288     raeburn  10641: sub get_user_info {
                   10642:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10643:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10644: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10645:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10646:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10647:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10648:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10649:     return;
                   10650: }
1.275     raeburn  10651: 
1.472     raeburn  10652: ###############################################
                   10653: 
                   10654: =pod
                   10655: 
                   10656: =item * &get_user_quota()
                   10657: 
1.1134    raeburn  10658: Retrieves quota assigned for storage of user files.
                   10659: Default is to report quota for portfolio files.
1.472     raeburn  10660: 
                   10661: Incoming parameters:
                   10662: 1. user's username
                   10663: 2. user's domain
1.1134    raeburn  10664: 3. quota name - portfolio, author, or course
1.1136    raeburn  10665:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10666: 4. crstype - official, unofficial, textbook, placement or community, 
                   10667:    if quota name is course
1.472     raeburn  10668: 
                   10669: Returns:
1.1163    raeburn  10670: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10671: 2. (Optional) Type of setting: custom or default
                   10672:    (individually assigned or default for user's 
                   10673:    institutional status).
                   10674: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10675:    or student - types as defined in localenroll::inst_usertypes 
                   10676:    for user's domain, which determines default quota for user.
                   10677: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10678: 
                   10679: If a value has been stored in the user's environment, 
1.536     raeburn  10680: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10681: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10682: 
                   10683: =cut
                   10684: 
                   10685: ###############################################
                   10686: 
                   10687: 
                   10688: sub get_user_quota {
1.1136    raeburn  10689:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10690:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10691:     if (!defined($udom)) {
                   10692:         $udom = $env{'user.domain'};
                   10693:     }
                   10694:     if (!defined($uname)) {
                   10695:         $uname = $env{'user.name'};
                   10696:     }
                   10697:     if (($udom eq '' || $uname eq '') ||
                   10698:         ($udom eq 'public') && ($uname eq 'public')) {
                   10699:         $quota = 0;
1.536     raeburn  10700:         $quotatype = 'default';
                   10701:         $defquota = 0; 
1.472     raeburn  10702:     } else {
1.536     raeburn  10703:         my $inststatus;
1.1134    raeburn  10704:         if ($quotaname eq 'course') {
                   10705:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10706:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10707:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10708:             } else {
                   10709:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10710:                 $quota = $cenv{'internal.uploadquota'};
                   10711:             }
1.536     raeburn  10712:         } else {
1.1134    raeburn  10713:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10714:                 if ($quotaname eq 'author') {
                   10715:                     $quota = $env{'environment.authorquota'};
                   10716:                 } else {
                   10717:                     $quota = $env{'environment.portfolioquota'};
                   10718:                 }
                   10719:                 $inststatus = $env{'environment.inststatus'};
                   10720:             } else {
                   10721:                 my %userenv = 
                   10722:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10723:                                          'authorquota','inststatus'],$udom,$uname);
                   10724:                 my ($tmp) = keys(%userenv);
                   10725:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10726:                     if ($quotaname eq 'author') {
                   10727:                         $quota = $userenv{'authorquota'};
                   10728:                     } else {
                   10729:                         $quota = $userenv{'portfolioquota'};
                   10730:                     }
                   10731:                     $inststatus = $userenv{'inststatus'};
                   10732:                 } else {
                   10733:                     undef(%userenv);
                   10734:                 }
                   10735:             }
                   10736:         }
                   10737:         if ($quota eq '' || wantarray) {
                   10738:             if ($quotaname eq 'course') {
                   10739:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10740:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10741:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10742:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10743:                     $defquota = $domdefs{$crstype.'quota'};
                   10744:                 }
                   10745:                 if ($defquota eq '') {
                   10746:                     $defquota = 500;
                   10747:                 }
1.1134    raeburn  10748:             } else {
                   10749:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10750:             }
                   10751:             if ($quota eq '') {
                   10752:                 $quota = $defquota;
                   10753:                 $quotatype = 'default';
                   10754:             } else {
                   10755:                 $quotatype = 'custom';
                   10756:             }
1.472     raeburn  10757:         }
                   10758:     }
1.536     raeburn  10759:     if (wantarray) {
                   10760:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10761:     } else {
                   10762:         return $quota;
                   10763:     }
1.472     raeburn  10764: }
                   10765: 
                   10766: ###############################################
                   10767: 
                   10768: =pod
                   10769: 
                   10770: =item * &default_quota()
                   10771: 
1.536     raeburn  10772: Retrieves default quota assigned for storage of user portfolio files,
                   10773: given an (optional) user's institutional status.
1.472     raeburn  10774: 
                   10775: Incoming parameters:
1.1142    raeburn  10776: 
1.472     raeburn  10777: 1. domain
1.536     raeburn  10778: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10779:    status types (e.g., faculty, staff, student etc.)
                   10780:    which apply to the user for whom the default is being retrieved.
                   10781:    If the institutional status string in undefined, the domain
1.1134    raeburn  10782:    default quota will be returned.
                   10783: 3.  quota name - portfolio, author, or course
                   10784:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10785: 
                   10786: Returns:
1.1142    raeburn  10787: 
1.1163    raeburn  10788: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10789: 2. (Optional) institutional type which determined the value of the
                   10790:    default quota.
1.472     raeburn  10791: 
                   10792: If a value has been stored in the domain's configuration db,
                   10793: it will return that, otherwise it returns 20 (for backwards 
                   10794: compatibility with domains which have not set up a configuration
1.1163    raeburn  10795: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10796: 
1.536     raeburn  10797: If the user's status includes multiple types (e.g., staff and student),
                   10798: the largest default quota which applies to the user determines the
                   10799: default quota returned.
                   10800: 
1.472     raeburn  10801: =cut
                   10802: 
                   10803: ###############################################
                   10804: 
                   10805: 
                   10806: sub default_quota {
1.1134    raeburn  10807:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10808:     my ($defquota,$settingstatus);
                   10809:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10810:                                             ['quotas'],$udom);
1.1134    raeburn  10811:     my $key = 'defaultquota';
                   10812:     if ($quotaname eq 'author') {
                   10813:         $key = 'authorquota';
                   10814:     }
1.622     raeburn  10815:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10816:         if ($inststatus ne '') {
1.765     raeburn  10817:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10818:             foreach my $item (@statuses) {
1.1134    raeburn  10819:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10820:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10821:                         if ($defquota eq '') {
1.1134    raeburn  10822:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10823:                             $settingstatus = $item;
1.1134    raeburn  10824:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10825:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10826:                             $settingstatus = $item;
                   10827:                         }
                   10828:                     }
1.1134    raeburn  10829:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10830:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10831:                         if ($defquota eq '') {
                   10832:                             $defquota = $quotahash{'quotas'}{$item};
                   10833:                             $settingstatus = $item;
                   10834:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10835:                             $defquota = $quotahash{'quotas'}{$item};
                   10836:                             $settingstatus = $item;
                   10837:                         }
1.536     raeburn  10838:                     }
                   10839:                 }
                   10840:             }
                   10841:         }
                   10842:         if ($defquota eq '') {
1.1134    raeburn  10843:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10844:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10845:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10846:                 $defquota = $quotahash{'quotas'}{'default'};
                   10847:             }
1.536     raeburn  10848:             $settingstatus = 'default';
1.1139    raeburn  10849:             if ($defquota eq '') {
                   10850:                 if ($quotaname eq 'author') {
                   10851:                     $defquota = 500;
                   10852:                 }
                   10853:             }
1.536     raeburn  10854:         }
                   10855:     } else {
                   10856:         $settingstatus = 'default';
1.1134    raeburn  10857:         if ($quotaname eq 'author') {
                   10858:             $defquota = 500;
                   10859:         } else {
                   10860:             $defquota = 20;
                   10861:         }
1.536     raeburn  10862:     }
                   10863:     if (wantarray) {
                   10864:         return ($defquota,$settingstatus);
1.472     raeburn  10865:     } else {
1.536     raeburn  10866:         return $defquota;
1.472     raeburn  10867:     }
                   10868: }
                   10869: 
1.1135    raeburn  10870: ###############################################
                   10871: 
                   10872: =pod
                   10873: 
1.1136    raeburn  10874: =item * &excess_filesize_warning()
1.1135    raeburn  10875: 
                   10876: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10877: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10878: space to be exceeded.
1.1136    raeburn  10879: 
                   10880: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10881: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10882: 
1.1165    raeburn  10883: Inputs: 7 
1.1136    raeburn  10884: 1. username or coursenum
1.1135    raeburn  10885: 2. domain
1.1136    raeburn  10886: 3. context ('author' or 'course')
1.1135    raeburn  10887: 4. filename of file for which action is being requested
                   10888: 5. filesize (kB) of file
                   10889: 6. action being taken: copy or upload.
1.1237    raeburn  10890: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10891: 
                   10892: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10893:          otherwise return null.
                   10894: 
                   10895: =back
1.1135    raeburn  10896: 
                   10897: =cut
                   10898: 
1.1136    raeburn  10899: sub excess_filesize_warning {
1.1165    raeburn  10900:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10901:     my $current_disk_usage = 0;
1.1165    raeburn  10902:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10903:     if ($context eq 'author') {
                   10904:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10905:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10906:     } else {
                   10907:         foreach my $subdir ('docs','supplemental') {
                   10908:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10909:         }
                   10910:     }
1.1135    raeburn  10911:     $disk_quota = int($disk_quota * 1000);
                   10912:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10913:         return '<p class="LC_warning">'.
1.1135    raeburn  10914:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10915:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10916:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10917:                             $disk_quota,$current_disk_usage).
                   10918:                '</p>';
                   10919:     }
                   10920:     return;
                   10921: }
                   10922: 
                   10923: ###############################################
                   10924: 
                   10925: 
1.1136    raeburn  10926: 
                   10927: 
1.384     raeburn  10928: sub get_secgrprole_info {
                   10929:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10930:     my %sections_count = &get_sections($cdom,$cnum);
                   10931:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10932:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10933:     my @groups = sort(keys(%curr_groups));
                   10934:     my $allroles = [];
                   10935:     my $rolehash;
                   10936:     my $accesshash = {
                   10937:                      active => 'Currently has access',
                   10938:                      future => 'Will have future access',
                   10939:                      previous => 'Previously had access',
                   10940:                   };
                   10941:     if ($needroles) {
                   10942:         $rolehash = {'all' => 'all'};
1.385     albertel 10943:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10944: 	if (&Apache::lonnet::error(%user_roles)) {
                   10945: 	    undef(%user_roles);
                   10946: 	}
                   10947:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10948:             my ($role)=split(/\:/,$item,2);
                   10949:             if ($role eq 'cr') { next; }
                   10950:             if ($role =~ /^cr/) {
                   10951:                 $$rolehash{$role} = (split('/',$role))[3];
                   10952:             } else {
                   10953:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10954:             }
                   10955:         }
                   10956:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10957:             push(@{$allroles},$key);
                   10958:         }
                   10959:         push (@{$allroles},'st');
                   10960:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10961:     }
                   10962:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10963: }
                   10964: 
1.555     raeburn  10965: sub user_picker {
1.1279    raeburn  10966:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10967:     my $currdom = $dom;
1.1253    raeburn  10968:     my @alldoms = &Apache::lonnet::all_domains();
                   10969:     if (@alldoms == 1) {
                   10970:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10971:                                                ['directorysrch'],$alldoms[0]);
                   10972:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10973:         my $showdom = $domdesc;
                   10974:         if ($showdom eq '') {
                   10975:             $showdom = $dom;
                   10976:         }
                   10977:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10978:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10979:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10980:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10981:             }
                   10982:         }
                   10983:     }
1.555     raeburn  10984:     my %curr_selected = (
                   10985:                         srchin => 'dom',
1.580     raeburn  10986:                         srchby => 'lastname',
1.555     raeburn  10987:                       );
                   10988:     my $srchterm;
1.625     raeburn  10989:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10990:         if ($srch->{'srchby'} ne '') {
                   10991:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10992:         }
                   10993:         if ($srch->{'srchin'} ne '') {
                   10994:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10995:         }
                   10996:         if ($srch->{'srchtype'} ne '') {
                   10997:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10998:         }
                   10999:         if ($srch->{'srchdomain'} ne '') {
                   11000:             $currdom = $srch->{'srchdomain'};
                   11001:         }
                   11002:         $srchterm = $srch->{'srchterm'};
                   11003:     }
1.1222    damieng  11004:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11005:                     'usr'       => 'Search criteria',
1.563     raeburn  11006:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11007:                     'uname'     => 'username',
                   11008:                     'lastname'  => 'last name',
1.555     raeburn  11009:                     'lastfirst' => 'last name, first name',
1.558     albertel 11010:                     'crs'       => 'in this course',
1.576     raeburn  11011:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11012:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11013:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11014:                     'exact'     => 'is',
                   11015:                     'contains'  => 'contains',
1.569     raeburn  11016:                     'begins'    => 'begins with',
1.1222    damieng  11017:                                        );
                   11018:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11019:                     'youm'      => "You must include some text to search for.",
                   11020:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11021:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11022:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11023:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11024:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11025:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11026:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11027:                                        );
1.1222    damieng  11028:     &html_escape(\%html_lt);
                   11029:     &js_escape(\%js_lt);
1.1255    raeburn  11030:     my $domform;
1.1277    raeburn  11031:     my $allow_blank = 1;
1.1255    raeburn  11032:     if ($fixeddom) {
1.1277    raeburn  11033:         $allow_blank = 0;
                   11034:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11035:     } else {
1.1287    raeburn  11036:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11037:         my ($trusted,$untrusted);
1.1287    raeburn  11038:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11039:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11040:         } elsif ($context eq 'author') {
1.1288    raeburn  11041:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11042:         } elsif ($context eq 'domain') {
1.1288    raeburn  11043:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11044:         }
1.1288    raeburn  11045:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11046:     }
1.563     raeburn  11047:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11048: 
                   11049:     my @srchins = ('crs','dom','alc','instd');
                   11050: 
                   11051:     foreach my $option (@srchins) {
                   11052:         # FIXME 'alc' option unavailable until 
                   11053:         #       loncreateuser::print_user_query_page()
                   11054:         #       has been completed.
                   11055:         next if ($option eq 'alc');
1.880     raeburn  11056:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11057:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11058:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11059:         if ($curr_selected{'srchin'} eq $option) {
                   11060:             $srchinsel .= ' 
1.1222    damieng  11061:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11062:         } else {
                   11063:             $srchinsel .= '
1.1222    damieng  11064:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11065:         }
1.555     raeburn  11066:     }
1.563     raeburn  11067:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11068: 
                   11069:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11070:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11071:         if ($curr_selected{'srchby'} eq $option) {
                   11072:             $srchbysel .= '
1.1222    damieng  11073:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11074:         } else {
                   11075:             $srchbysel .= '
1.1222    damieng  11076:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11077:          }
                   11078:     }
                   11079:     $srchbysel .= "\n  </select>\n";
                   11080: 
                   11081:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11082:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11083:         if ($curr_selected{'srchtype'} eq $option) {
                   11084:             $srchtypesel .= '
1.1222    damieng  11085:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11086:         } else {
                   11087:             $srchtypesel .= '
1.1222    damieng  11088:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11089:         }
                   11090:     }
                   11091:     $srchtypesel .= "\n  </select>\n";
                   11092: 
1.558     albertel 11093:     my ($newuserscript,$new_user_create);
1.994     raeburn  11094:     my $context_dom = $env{'request.role.domain'};
                   11095:     if ($context eq 'requestcrs') {
                   11096:         if ($env{'form.coursedom'} ne '') { 
                   11097:             $context_dom = $env{'form.coursedom'};
                   11098:         }
                   11099:     }
1.556     raeburn  11100:     if ($forcenewuser) {
1.576     raeburn  11101:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11102:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11103:                 if ($cancreate) {
                   11104:                     $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>';
                   11105:                 } else {
1.799     bisitz   11106:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11107:                     my %usertypetext = (
                   11108:                         official   => 'institutional',
                   11109:                         unofficial => 'non-institutional',
                   11110:                     );
1.799     bisitz   11111:                     $new_user_create = '<p class="LC_warning">'
                   11112:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11113:                                       .' '
                   11114:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11115:                                           ,'<a href="'.$helplink.'">','</a>')
                   11116:                                       .'</p><br />';
1.627     raeburn  11117:                 }
1.576     raeburn  11118:             }
                   11119:         }
                   11120: 
1.556     raeburn  11121:         $newuserscript = <<"ENDSCRIPT";
                   11122: 
1.570     raeburn  11123: function setSearch(createnew,callingForm) {
1.556     raeburn  11124:     if (createnew == 1) {
1.570     raeburn  11125:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11126:             if (callingForm.srchby.options[i].value == 'uname') {
                   11127:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11128:             }
                   11129:         }
1.570     raeburn  11130:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11131:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11132: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11133:             }
                   11134:         }
1.570     raeburn  11135:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11136:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11137:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11138:             }
                   11139:         }
1.570     raeburn  11140:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11141:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11142:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11143:             }
                   11144:         }
                   11145:     }
                   11146: }
                   11147: ENDSCRIPT
1.558     albertel 11148: 
1.556     raeburn  11149:     }
                   11150: 
1.555     raeburn  11151:     my $output = <<"END_BLOCK";
1.556     raeburn  11152: <script type="text/javascript">
1.824     bisitz   11153: // <![CDATA[
1.570     raeburn  11154: function validateEntry(callingForm) {
1.558     albertel 11155: 
1.556     raeburn  11156:     var checkok = 1;
1.558     albertel 11157:     var srchin;
1.570     raeburn  11158:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11159: 	if ( callingForm.srchin[i].checked ) {
                   11160: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11161: 	}
                   11162:     }
                   11163: 
1.570     raeburn  11164:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11165:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11166:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11167:     var srchterm =  callingForm.srchterm.value;
                   11168:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11169:     var msg = "";
                   11170: 
                   11171:     if (srchterm == "") {
                   11172:         checkok = 0;
1.1222    damieng  11173:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11174:     }
                   11175: 
1.569     raeburn  11176:     if (srchtype== 'begins') {
                   11177:         if (srchterm.length < 2) {
                   11178:             checkok = 0;
1.1222    damieng  11179:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11180:         }
                   11181:     }
                   11182: 
1.556     raeburn  11183:     if (srchtype== 'contains') {
                   11184:         if (srchterm.length < 3) {
                   11185:             checkok = 0;
1.1222    damieng  11186:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11187:         }
                   11188:     }
                   11189:     if (srchin == 'instd') {
                   11190:         if (srchdomain == '') {
                   11191:             checkok = 0;
1.1222    damieng  11192:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11193:         }
                   11194:     }
                   11195:     if (srchin == 'dom') {
                   11196:         if (srchdomain == '') {
                   11197:             checkok = 0;
1.1222    damieng  11198:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11199:         }
                   11200:     }
                   11201:     if (srchby == 'lastfirst') {
                   11202:         if (srchterm.indexOf(",") == -1) {
                   11203:             checkok = 0;
1.1222    damieng  11204:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11205:         }
                   11206:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11207:             checkok = 0;
1.1222    damieng  11208:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11209:         }
                   11210:     }
                   11211:     if (checkok == 0) {
1.1222    damieng  11212:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11213:         return;
                   11214:     }
                   11215:     if (checkok == 1) {
1.570     raeburn  11216:         callingForm.submit();
1.556     raeburn  11217:     }
                   11218: }
                   11219: 
                   11220: $newuserscript
                   11221: 
1.824     bisitz   11222: // ]]>
1.556     raeburn  11223: </script>
1.558     albertel 11224: 
                   11225: $new_user_create
                   11226: 
1.555     raeburn  11227: END_BLOCK
1.558     albertel 11228: 
1.876     raeburn  11229:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11230:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11231:                $domform.
                   11232:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11233:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11234:                $srchbysel.
                   11235:                $srchtypesel. 
                   11236:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11237:                $srchinsel.
                   11238:                &Apache::lonhtmlcommon::row_closure(1). 
                   11239:                &Apache::lonhtmlcommon::end_pick_box().
                   11240:                '<br />';
1.1253    raeburn  11241:     return ($output,1);
1.555     raeburn  11242: }
                   11243: 
1.612     raeburn  11244: sub user_rule_check {
1.615     raeburn  11245:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11246:     my ($response,%inst_response);
1.612     raeburn  11247:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11248:         if (keys(%{$usershash}) > 1) {
                   11249:             my (%by_username,%by_id,%userdoms);
                   11250:             my $checkid; 
                   11251:             if (ref($checks) eq 'HASH') {
                   11252:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11253:                     $checkid = 1;
                   11254:                 }
                   11255:             }
                   11256:             foreach my $user (keys(%{$usershash})) {
                   11257:                 my ($uname,$udom) = split(/:/,$user);
                   11258:                 if ($checkid) {
                   11259:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11260:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11261:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11262:                             $userdoms{$udom} = 1;
1.1227    raeburn  11263:                             if (ref($inst_results) eq 'HASH') {
                   11264:                                 $inst_results->{$uname.':'.$udom} = {};
                   11265:                             }
1.1226    raeburn  11266:                         }
                   11267:                     }
                   11268:                 } else {
                   11269:                     $by_username{$udom}{$uname} = 1;
                   11270:                     $userdoms{$udom} = 1;
1.1227    raeburn  11271:                     if (ref($inst_results) eq 'HASH') {
                   11272:                         $inst_results->{$uname.':'.$udom} = {};
                   11273:                     }
1.1226    raeburn  11274:                 }
                   11275:             }
                   11276:             foreach my $udom (keys(%userdoms)) {
                   11277:                 if (!$got_rules->{$udom}) {
                   11278:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11279:                                                              ['usercreation'],$udom);
                   11280:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11281:                         foreach my $item ('username','id') {
                   11282:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11283:                                 $$curr_rules{$udom}{$item} =
                   11284:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11285:                             }
                   11286:                         }
                   11287:                     }
                   11288:                     $got_rules->{$udom} = 1;
                   11289:                 }
1.612     raeburn  11290:             }
1.1226    raeburn  11291:             if ($checkid) {
                   11292:                 foreach my $udom (keys(%by_id)) {
                   11293:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11294:                     if ($outcome eq 'ok') {
1.1227    raeburn  11295:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11296:                             my $uname = $by_id{$udom}{$id};
                   11297:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11298:                         }
1.1226    raeburn  11299:                         if (ref($results) eq 'HASH') {
                   11300:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11301:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11302:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11303:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11304:                                 }
1.1226    raeburn  11305:                             }
                   11306:                         }
                   11307:                     }
1.612     raeburn  11308:                 }
1.615     raeburn  11309:             } else {
1.1226    raeburn  11310:                 foreach my $udom (keys(%by_username)) {
                   11311:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11312:                     if ($outcome eq 'ok') {
1.1227    raeburn  11313:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11314:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11315:                         }
1.1226    raeburn  11316:                         if (ref($results) eq 'HASH') {
                   11317:                             foreach my $uname (keys(%{$results})) {
                   11318:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11319:                             }
                   11320:                         }
                   11321:                     }
                   11322:                 }
1.612     raeburn  11323:             }
1.1226    raeburn  11324:         } elsif (keys(%{$usershash}) == 1) {
                   11325:             my $user = (keys(%{$usershash}))[0];
                   11326:             my ($uname,$udom) = split(/:/,$user);
                   11327:             if (($udom ne '') && ($uname ne '')) {
                   11328:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11329:                     if (ref($checks) eq 'HASH') {
                   11330:                         if (defined($checks->{'username'})) {
                   11331:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11332:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11333:                         } elsif (defined($checks->{'id'})) {
                   11334:                             if ($usershash->{$user}->{'id'} ne '') {
                   11335:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11336:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11337:                                                                   $usershash->{$user}->{'id'});
                   11338:                             } else {
                   11339:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11340:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11341:                             }
1.585     raeburn  11342:                         }
1.1226    raeburn  11343:                     } else {
                   11344:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11345:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11346:                        return;
                   11347:                     }
                   11348:                     if (!$got_rules->{$udom}) {
                   11349:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11350:                                                                  ['usercreation'],$udom);
                   11351:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11352:                             foreach my $item ('username','id') {
                   11353:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11354:                                    $$curr_rules{$udom}{$item} = 
                   11355:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11356:                                 }
                   11357:                             }
                   11358:                         }
                   11359:                         $got_rules->{$udom} = 1;
1.585     raeburn  11360:                     }
                   11361:                 }
1.1226    raeburn  11362:             } else {
                   11363:                 return;
                   11364:             }
                   11365:         } else {
                   11366:             return;
                   11367:         }
                   11368:         foreach my $user (keys(%{$usershash})) {
                   11369:             my ($uname,$udom) = split(/:/,$user);
                   11370:             next if (($udom eq '') || ($uname eq ''));
                   11371:             my $id;
1.1227    raeburn  11372:             if (ref($inst_results) eq 'HASH') {
                   11373:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11374:                     $id = $inst_results->{$user}->{'id'};
                   11375:                 }
                   11376:             }
                   11377:             if ($id eq '') { 
                   11378:                 if (ref($usershash->{$user})) {
                   11379:                     $id = $usershash->{$user}->{'id'};
                   11380:                 }
1.585     raeburn  11381:             }
1.612     raeburn  11382:             foreach my $item (keys(%{$checks})) {
                   11383:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11384:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11385:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11386:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11387:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11388:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11389:                                 if ($rule_check{$rule}) {
                   11390:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11391:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11392:                                         if (ref($inst_results) eq 'HASH') {
                   11393:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11394:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11395:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11396:                                                 } elsif ($item eq 'id') {
                   11397:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11398:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11399:                                                     }
1.615     raeburn  11400:                                                 }
1.612     raeburn  11401:                                             }
                   11402:                                         }
1.615     raeburn  11403:                                     }
                   11404:                                     last;
1.585     raeburn  11405:                                 }
                   11406:                             }
                   11407:                         }
                   11408:                     }
                   11409:                 }
                   11410:             }
                   11411:         }
                   11412:     }
1.612     raeburn  11413:     return;
                   11414: }
                   11415: 
                   11416: sub user_rule_formats {
                   11417:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11418:     my %text = ( 
                   11419:                  'username' => 'Usernames',
                   11420:                  'id'       => 'IDs',
                   11421:                );
                   11422:     my $output;
                   11423:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11424:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11425:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11426:             $output = '<br />'.
                   11427:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11428:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11429:                       ' <ul>';
1.612     raeburn  11430:             foreach my $rule (@{$ruleorder}) {
                   11431:                 if (ref($curr_rules) eq 'ARRAY') {
                   11432:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11433:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11434:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11435:                                         $rules->{$rule}{'desc'}.'</li>';
                   11436:                         }
                   11437:                     }
                   11438:                 }
                   11439:             }
                   11440:             $output .= '</ul>';
                   11441:         }
                   11442:     }
                   11443:     return $output;
                   11444: }
                   11445: 
                   11446: sub instrule_disallow_msg {
1.615     raeburn  11447:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11448:     my $response;
                   11449:     my %text = (
                   11450:                   item   => 'username',
                   11451:                   items  => 'usernames',
                   11452:                   match  => 'matches',
                   11453:                   do     => 'does',
                   11454:                   action => 'a username',
                   11455:                   one    => 'one',
                   11456:                );
                   11457:     if ($count > 1) {
                   11458:         $text{'item'} = 'usernames';
                   11459:         $text{'match'} ='match';
                   11460:         $text{'do'} = 'do';
                   11461:         $text{'action'} = 'usernames',
                   11462:         $text{'one'} = 'ones';
                   11463:     }
                   11464:     if ($checkitem eq 'id') {
                   11465:         $text{'items'} = 'IDs';
                   11466:         $text{'item'} = 'ID';
                   11467:         $text{'action'} = 'an ID';
1.615     raeburn  11468:         if ($count > 1) {
                   11469:             $text{'item'} = 'IDs';
                   11470:             $text{'action'} = 'IDs';
                   11471:         }
1.612     raeburn  11472:     }
1.674     bisitz   11473:     $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  11474:     if ($mode eq 'upload') {
                   11475:         if ($checkitem eq 'username') {
                   11476:             $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'}.");
                   11477:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11478:             $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  11479:         }
1.669     raeburn  11480:     } elsif ($mode eq 'selfcreate') {
                   11481:         if ($checkitem eq 'id') {
                   11482:             $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.");
                   11483:         }
1.615     raeburn  11484:     } else {
                   11485:         if ($checkitem eq 'username') {
                   11486:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11487:         } elsif ($checkitem eq 'id') {
                   11488:             $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.");
                   11489:         }
1.612     raeburn  11490:     }
                   11491:     return $response;
1.585     raeburn  11492: }
                   11493: 
1.624     raeburn  11494: sub personal_data_fieldtitles {
                   11495:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11496:                         id => 'Student/Employee ID',
                   11497:                         permanentemail => 'E-mail address',
                   11498:                         lastname => 'Last Name',
                   11499:                         firstname => 'First Name',
                   11500:                         middlename => 'Middle Name',
                   11501:                         generation => 'Generation',
                   11502:                         gen => 'Generation',
1.765     raeburn  11503:                         inststatus => 'Affiliation',
1.624     raeburn  11504:                    );
                   11505:     return %fieldtitles;
                   11506: }
                   11507: 
1.642     raeburn  11508: sub sorted_inst_types {
                   11509:     my ($dom) = @_;
1.1185    raeburn  11510:     my ($usertypes,$order);
                   11511:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11512:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11513:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11514:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11515:     } else {
                   11516:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11517:     }
1.642     raeburn  11518:     my $othertitle = &mt('All users');
                   11519:     if ($env{'request.course.id'}) {
1.668     raeburn  11520:         $othertitle  = &mt('Any users');
1.642     raeburn  11521:     }
                   11522:     my @types;
                   11523:     if (ref($order) eq 'ARRAY') {
                   11524:         @types = @{$order};
                   11525:     }
                   11526:     if (@types == 0) {
                   11527:         if (ref($usertypes) eq 'HASH') {
                   11528:             @types = sort(keys(%{$usertypes}));
                   11529:         }
                   11530:     }
                   11531:     if (keys(%{$usertypes}) > 0) {
                   11532:         $othertitle = &mt('Other users');
                   11533:     }
                   11534:     return ($othertitle,$usertypes,\@types);
                   11535: }
                   11536: 
1.645     raeburn  11537: sub get_institutional_codes {
1.1361    raeburn  11538:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11539: # Get complete list of course sections to update
                   11540:     my @currsections = ();
                   11541:     my @currxlists = ();
1.1361    raeburn  11542:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11543:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11544:     my $crskey = $crs.':'.$coursecode;
                   11545:     @{$unclutteredsec{$crskey}} = ();
                   11546:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11547: 
                   11548:     if ($$settings{'internal.sectionnums'} ne '') {
                   11549:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11550:     }
                   11551: 
                   11552:     if ($$settings{'internal.crosslistings'} ne '') {
                   11553:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11554:     }
                   11555: 
                   11556:     if (@currxlists > 0) {
1.1361    raeburn  11557:         foreach my $xl (@currxlists) {
                   11558:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11559:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11560:                     push(@{$allcourses},$1);
1.645     raeburn  11561:                     $$LC_code{$1} = $2;
                   11562:                 }
                   11563:             }
                   11564:         }
                   11565:     }
1.1361    raeburn  11566: 
1.645     raeburn  11567:     if (@currsections > 0) {
1.1361    raeburn  11568:         foreach my $sec (@currsections) {
                   11569:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11570:                 my $instsec = $1;
1.645     raeburn  11571:                 my $lc_sec = $2;
1.1361    raeburn  11572:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11573:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11574:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11575:                 }
                   11576:             }
                   11577:         }
                   11578:     }
                   11579: 
                   11580:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11581:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11582:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11583:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11584:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11585:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11586:                     push(@{$allcourses},$sec);
1.1361    raeburn  11587:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11588:                 }
                   11589:             }
                   11590:         }
                   11591:     }
                   11592:     return;
                   11593: }
                   11594: 
1.971     raeburn  11595: sub get_standard_codeitems {
                   11596:     return ('Year','Semester','Department','Number','Section');
                   11597: }
                   11598: 
1.112     bowersj2 11599: =pod
                   11600: 
1.780     raeburn  11601: =head1 Slot Helpers
                   11602: 
                   11603: =over 4
                   11604: 
                   11605: =item * sorted_slots()
                   11606: 
1.1040    raeburn  11607: Sorts an array of slot names in order of an optional sort key,
                   11608: default sort is by slot start time (earliest first). 
1.780     raeburn  11609: 
                   11610: Inputs:
                   11611: 
                   11612: =over 4
                   11613: 
                   11614: slotsarr  - Reference to array of unsorted slot names.
                   11615: 
                   11616: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11617: 
1.1040    raeburn  11618: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11619: 
1.549     albertel 11620: =back
                   11621: 
1.780     raeburn  11622: Returns:
                   11623: 
                   11624: =over 4
                   11625: 
1.1040    raeburn  11626: sorted   - An array of slot names sorted by a specified sort key 
                   11627:            (default sort key is start time of the slot).
1.780     raeburn  11628: 
                   11629: =back
                   11630: 
                   11631: =cut
                   11632: 
                   11633: 
                   11634: sub sorted_slots {
1.1040    raeburn  11635:     my ($slotsarr,$slots,$sortkey) = @_;
                   11636:     if ($sortkey eq '') {
                   11637:         $sortkey = 'starttime';
                   11638:     }
1.780     raeburn  11639:     my @sorted;
                   11640:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11641:         @sorted =
                   11642:             sort {
                   11643:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11644:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11645:                      }
                   11646:                      if (ref($slots->{$a})) { return -1;}
                   11647:                      if (ref($slots->{$b})) { return 1;}
                   11648:                      return 0;
                   11649:                  } @{$slotsarr};
                   11650:     }
                   11651:     return @sorted;
                   11652: }
                   11653: 
1.1040    raeburn  11654: =pod
                   11655: 
                   11656: =item * get_future_slots()
                   11657: 
                   11658: Inputs:
                   11659: 
                   11660: =over 4
                   11661: 
                   11662: cnum - course number
                   11663: 
                   11664: cdom - course domain
                   11665: 
                   11666: now - current UNIX time
                   11667: 
                   11668: symb - optional symb
                   11669: 
                   11670: =back
                   11671: 
                   11672: Returns:
                   11673: 
                   11674: =over 4
                   11675: 
                   11676: sorted_reservable - ref to array of student_schedulable slots currently 
                   11677:                     reservable, ordered by end date of reservation period.
                   11678: 
                   11679: reservable_now - ref to hash of student_schedulable slots currently
                   11680:                  reservable.
                   11681: 
                   11682:     Keys in inner hash are:
                   11683:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11684:     (b) endreserve: end date of reservation period.
                   11685:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11686:         selected.
1.1040    raeburn  11687: 
                   11688: sorted_future - ref to array of student_schedulable slots reservable in
                   11689:                 the future, ordered by start date of reservation period.
                   11690: 
                   11691: future_reservable - ref to hash of student_schedulable slots reservable
                   11692:                     in the future.
                   11693: 
                   11694:     Keys in inner hash are:
                   11695:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11696:     (b) startreserve: start date of reservation period.
                   11697:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11698:         selected.
1.1040    raeburn  11699: 
                   11700: =back
                   11701: 
                   11702: =cut
                   11703: 
                   11704: sub get_future_slots {
                   11705:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11706:     my $map;
                   11707:     if ($symb) {
                   11708:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11709:     }
1.1040    raeburn  11710:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11711:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11712:     foreach my $slot (keys(%slots)) {
                   11713:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11714:         if ($symb) {
1.1229    raeburn  11715:             if ($slots{$slot}->{'symb'} ne '') {
                   11716:                 my $canuse;
                   11717:                 my %oksymbs;
                   11718:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11719:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11720:                 if ($oksymbs{$symb}) {
                   11721:                     $canuse = 1;
                   11722:                 } else {
                   11723:                     foreach my $item (@slotsymbs) {
                   11724:                         if ($item =~ /\.(page|sequence)$/) {
                   11725:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11726:                             if (($map ne '') && ($map eq $sloturl)) {
                   11727:                                 $canuse = 1;
                   11728:                                 last;
                   11729:                             }
                   11730:                         }
                   11731:                     }
                   11732:                 }
                   11733:                 next unless ($canuse);
                   11734:             }
1.1040    raeburn  11735:         }
                   11736:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11737:             ($slots{$slot}->{'endtime'} > $now)) {
                   11738:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11739:                 my $userallowed = 0;
                   11740:                 if ($slots{$slot}->{'allowedsections'}) {
                   11741:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11742:                     if (!defined($env{'request.role.sec'})
                   11743:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11744:                         $userallowed=1;
                   11745:                     } else {
                   11746:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11747:                             $userallowed=1;
                   11748:                         }
                   11749:                     }
                   11750:                     unless ($userallowed) {
                   11751:                         if (defined($env{'request.course.groups'})) {
                   11752:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11753:                             foreach my $group (@groups) {
                   11754:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11755:                                     $userallowed=1;
                   11756:                                     last;
                   11757:                                 }
                   11758:                             }
                   11759:                         }
                   11760:                     }
                   11761:                 }
                   11762:                 if ($slots{$slot}->{'allowedusers'}) {
                   11763:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11764:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11765:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11766:                         $userallowed = 1;
                   11767:                     }
                   11768:                 }
                   11769:                 next unless($userallowed);
                   11770:             }
                   11771:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11772:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11773:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11774:             my $uniqueperiod;
                   11775:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11776:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11777:             }
1.1040    raeburn  11778:             if (($startreserve < $now) &&
                   11779:                 (!$endreserve || $endreserve > $now)) {
                   11780:                 my $lastres = $endreserve;
                   11781:                 if (!$lastres) {
                   11782:                     $lastres = $slots{$slot}->{'starttime'};
                   11783:                 }
                   11784:                 $reservable_now{$slot} = {
                   11785:                                            symb       => $symb,
1.1250    raeburn  11786:                                            endreserve => $lastres,
                   11787:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11788:                                          };
                   11789:             } elsif (($startreserve > $now) &&
                   11790:                      (!$endreserve || $endreserve > $startreserve)) {
                   11791:                 $future_reservable{$slot} = {
                   11792:                                               symb         => $symb,
1.1250    raeburn  11793:                                               startreserve => $startreserve,
                   11794:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11795:                                             };
                   11796:             }
                   11797:         }
                   11798:     }
                   11799:     my @unsorted_reservable = keys(%reservable_now);
                   11800:     if (@unsorted_reservable > 0) {
                   11801:         @sorted_reservable = 
                   11802:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11803:     }
                   11804:     my @unsorted_future = keys(%future_reservable);
                   11805:     if (@unsorted_future > 0) {
                   11806:         @sorted_future =
                   11807:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11808:     }
                   11809:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11810: }
1.780     raeburn  11811: 
                   11812: =pod
                   11813: 
1.1057    foxr     11814: =back
                   11815: 
1.549     albertel 11816: =head1 HTTP Helpers
                   11817: 
                   11818: =over 4
                   11819: 
1.648     raeburn  11820: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11821: 
1.258     albertel 11822: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11823: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11824: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11825: 
                   11826: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11827: $possible_names is an ref to an array of form element names.  As an example:
                   11828: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11829: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11830: 
                   11831: =cut
1.1       albertel 11832: 
1.6       albertel 11833: sub get_unprocessed_cgi {
1.25      albertel 11834:   my ($query,$possible_names)= @_;
1.26      matthew  11835:   # $Apache::lonxml::debug=1;
1.356     albertel 11836:   foreach my $pair (split(/&/,$query)) {
                   11837:     my ($name, $value) = split(/=/,$pair);
1.369     www      11838:     $name = &unescape($name);
1.25      albertel 11839:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11840:       $value =~ tr/+/ /;
                   11841:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11842:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11843:     }
1.16      harris41 11844:   }
1.6       albertel 11845: }
                   11846: 
1.112     bowersj2 11847: =pod
                   11848: 
1.648     raeburn  11849: =item * &cacheheader() 
1.112     bowersj2 11850: 
                   11851: returns cache-controlling header code
                   11852: 
                   11853: =cut
                   11854: 
1.7       albertel 11855: sub cacheheader {
1.258     albertel 11856:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11857:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11858:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11859:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11860:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11861:     return $output;
1.7       albertel 11862: }
                   11863: 
1.112     bowersj2 11864: =pod
                   11865: 
1.648     raeburn  11866: =item * &no_cache($r) 
1.112     bowersj2 11867: 
                   11868: specifies header code to not have cache
                   11869: 
                   11870: =cut
                   11871: 
1.9       albertel 11872: sub no_cache {
1.216     albertel 11873:     my ($r) = @_;
                   11874:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11875: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11876:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11877:     $r->no_cache(1);
                   11878:     $r->header_out("Expires" => $date);
                   11879:     $r->header_out("Pragma" => "no-cache");
1.123     www      11880: }
                   11881: 
                   11882: sub content_type {
1.181     albertel 11883:     my ($r,$type,$charset) = @_;
1.299     foxr     11884:     if ($r) {
                   11885: 	#  Note that printout.pl calls this with undef for $r.
                   11886: 	&no_cache($r);
                   11887:     }
1.258     albertel 11888:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11889:     unless ($charset) {
                   11890: 	$charset=&Apache::lonlocal::current_encoding;
                   11891:     }
                   11892:     if ($charset) { $type.='; charset='.$charset; }
                   11893:     if ($r) {
                   11894: 	$r->content_type($type);
                   11895:     } else {
                   11896: 	print("Content-type: $type\n\n");
                   11897:     }
1.9       albertel 11898: }
1.25      albertel 11899: 
1.112     bowersj2 11900: =pod
                   11901: 
1.648     raeburn  11902: =item * &add_to_env($name,$value) 
1.112     bowersj2 11903: 
1.258     albertel 11904: adds $name to the %env hash with value
1.112     bowersj2 11905: $value, if $name already exists, the entry is converted to an array
                   11906: reference and $value is added to the array.
                   11907: 
                   11908: =cut
                   11909: 
1.25      albertel 11910: sub add_to_env {
                   11911:   my ($name,$value)=@_;
1.258     albertel 11912:   if (defined($env{$name})) {
                   11913:     if (ref($env{$name})) {
1.25      albertel 11914:       #already have multiple values
1.258     albertel 11915:       push(@{ $env{$name} },$value);
1.25      albertel 11916:     } else {
                   11917:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11918:       my $first=$env{$name};
                   11919:       undef($env{$name});
                   11920:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11921:     }
                   11922:   } else {
1.258     albertel 11923:     $env{$name}=$value;
1.25      albertel 11924:   }
1.31      albertel 11925: }
1.149     albertel 11926: 
                   11927: =pod
                   11928: 
1.648     raeburn  11929: =item * &get_env_multiple($name) 
1.149     albertel 11930: 
1.258     albertel 11931: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11932: values may be defined and end up as an array ref.
                   11933: 
                   11934: returns an array of values
                   11935: 
                   11936: =cut
                   11937: 
                   11938: sub get_env_multiple {
                   11939:     my ($name) = @_;
                   11940:     my @values;
1.258     albertel 11941:     if (defined($env{$name})) {
1.149     albertel 11942:         # exists is it an array
1.258     albertel 11943:         if (ref($env{$name})) {
                   11944:             @values=@{ $env{$name} };
1.149     albertel 11945:         } else {
1.258     albertel 11946:             $values[0]=$env{$name};
1.149     albertel 11947:         }
                   11948:     }
                   11949:     return(@values);
                   11950: }
                   11951: 
1.1249    damieng  11952: # Looks at given dependencies, and returns something depending on the context.
                   11953: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11954: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11955: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11956: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11957: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   11958: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11959: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11960: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11961: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11962: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11963: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11964: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11965: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   11966: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11967: sub ask_for_embedded_content {
1.1249    damieng  11968:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11969:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11970:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11971:         %currsubfile,%unused,$rem);
1.1071    raeburn  11972:     my $counter = 0;
                   11973:     my $numnew = 0;
1.987     raeburn  11974:     my $numremref = 0;
                   11975:     my $numinvalid = 0;
                   11976:     my $numpathchg = 0;
                   11977:     my $numexisting = 0;
1.1071    raeburn  11978:     my $numunused = 0;
                   11979:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11980:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11981:     my $heading = &mt('Upload embedded files');
                   11982:     my $buttontext = &mt('Upload');
                   11983: 
1.1249    damieng  11984:     # fills these variables based on the context:
                   11985:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11986:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11987:     if ($env{'request.course.id'}) {
1.1123    raeburn  11988:         if ($actionurl eq '/adm/dependencies') {
                   11989:             $navmap = Apache::lonnavmaps::navmap->new();
                   11990:         }
                   11991:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11992:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11993:     }
1.1123    raeburn  11994:     if (($actionurl eq '/adm/portfolio') || 
                   11995:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11996:         my $current_path='/';
                   11997:         if ($env{'form.currentpath'}) {
                   11998:             $current_path = $env{'form.currentpath'};
                   11999:         }
                   12000:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12001:             $udom = $cdom;
                   12002:             $uname = $cnum;
1.984     raeburn  12003:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12004:         } else {
                   12005:             $udom = $env{'user.domain'};
                   12006:             $uname = $env{'user.name'};
                   12007:             $url = '/userfiles/portfolio';
                   12008:         }
1.987     raeburn  12009:         $toplevel = $url.'/';
1.984     raeburn  12010:         $url .= $current_path;
                   12011:         $getpropath = 1;
1.987     raeburn  12012:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12013:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12014:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12015:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12016:         $toplevel = $url;
1.984     raeburn  12017:         if ($rest ne '') {
1.987     raeburn  12018:             $url .= $rest;
                   12019:         }
                   12020:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12021:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12022:             $url = $args->{'docs_url'};
                   12023:             $toplevel = $url;
1.1084    raeburn  12024:             if ($args->{'context'} eq 'paste') {
                   12025:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12026:                 ($path) = 
                   12027:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12028:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12029:                 $fileloc =~ s{^/}{};
                   12030:             }
1.1071    raeburn  12031:         }
1.1084    raeburn  12032:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12033:         if ($env{'request.course.id'} ne '') {
                   12034:             if (ref($args) eq 'HASH') {
                   12035:                 $url = $args->{'docs_url'};
                   12036:                 $title = $args->{'docs_title'};
1.1126    raeburn  12037:                 $toplevel = $url; 
                   12038:                 unless ($toplevel =~ m{^/}) {
                   12039:                     $toplevel = "/$url";
                   12040:                 }
1.1085    raeburn  12041:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12042:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12043:                     $path = $1;
                   12044:                 } else {
                   12045:                     ($path) =
                   12046:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12047:                 }
1.1195    raeburn  12048:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12049:                     $fileloc = $toplevel;
                   12050:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12051:                     my ($udom,$uname,$fname) =
                   12052:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12053:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12054:                 } else {
                   12055:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12056:                 }
1.1071    raeburn  12057:                 $fileloc =~ s{^/}{};
                   12058:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12059:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12060:             }
1.987     raeburn  12061:         }
1.1123    raeburn  12062:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12063:         $udom = $cdom;
                   12064:         $uname = $cnum;
                   12065:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12066:         $toplevel = $url;
                   12067:         $path = $url;
                   12068:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12069:         $fileloc =~ s{^/}{};
1.987     raeburn  12070:     }
1.1249    damieng  12071:     
                   12072:     # parses the dependency paths to get some info
                   12073:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12074:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12075:     # (will be completed later)
                   12076:     # $mapping:
                   12077:     #   for external URLs: external URL -> external URL
                   12078:     #   for relative paths: clean path -> original path
                   12079:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12080:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12081:     foreach my $file (keys(%{$allfiles})) {
                   12082:         my $embed_file;
                   12083:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12084:             $embed_file = $1;
                   12085:         } else {
                   12086:             $embed_file = $file;
                   12087:         }
1.1158    raeburn  12088:         my ($absolutepath,$cleaned_file);
                   12089:         if ($embed_file =~ m{^\w+://}) {
                   12090:             $cleaned_file = $embed_file;
1.1147    raeburn  12091:             $newfiles{$cleaned_file} = 1;
                   12092:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12093:         } else {
1.1158    raeburn  12094:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12095:             if ($embed_file =~ m{^/}) {
                   12096:                 $absolutepath = $embed_file;
                   12097:             }
1.1147    raeburn  12098:             if ($cleaned_file =~ m{/}) {
                   12099:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12100:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12101:                 my $item = $fname;
                   12102:                 if ($path ne '') {
                   12103:                     $item = $path.'/'.$fname;
                   12104:                     $subdependencies{$path}{$fname} = 1;
                   12105:                 } else {
                   12106:                     $dependencies{$item} = 1;
                   12107:                 }
                   12108:                 if ($absolutepath) {
                   12109:                     $mapping{$item} = $absolutepath;
                   12110:                 } else {
                   12111:                     $mapping{$item} = $embed_file;
                   12112:                 }
                   12113:             } else {
                   12114:                 $dependencies{$embed_file} = 1;
                   12115:                 if ($absolutepath) {
1.1147    raeburn  12116:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12117:                 } else {
1.1147    raeburn  12118:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12119:                 }
                   12120:             }
1.984     raeburn  12121:         }
                   12122:     }
1.1249    damieng  12123:     
                   12124:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12125:     # and lists
                   12126:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12127:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12128:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12129:     #                                    the path had to be cleaned up
                   12130:     # $existing: hash clean path -> 1 if the file exists
                   12131:     # $numexisting: number of keys in $existing
                   12132:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12133:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12134:     #                                      dependency subdirectories that are
                   12135:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12136:     my $dirptr = 16384;
1.984     raeburn  12137:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12138:         $currsubfile{$path} = {};
1.1123    raeburn  12139:         if (($actionurl eq '/adm/portfolio') || 
                   12140:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12141:             my ($sublistref,$listerror) =
                   12142:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12143:             if (ref($sublistref) eq 'ARRAY') {
                   12144:                 foreach my $line (@{$sublistref}) {
                   12145:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12146:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12147:                 }
1.984     raeburn  12148:             }
1.987     raeburn  12149:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12150:             if (opendir(my $dir,$url.'/'.$path)) {
                   12151:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12152:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12153:             }
1.1084    raeburn  12154:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12155:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12156:                   ($args->{'context'} eq 'paste')) ||
                   12157:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12158:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12159:                 my $dir;
                   12160:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12161:                     $dir = $fileloc;
                   12162:                 } else {
                   12163:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12164:                 }
1.1071    raeburn  12165:                 if ($dir ne '') {
                   12166:                     my ($sublistref,$listerror) =
                   12167:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12168:                     if (ref($sublistref) eq 'ARRAY') {
                   12169:                         foreach my $line (@{$sublistref}) {
                   12170:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12171:                                 undef,$mtime)=split(/\&/,$line,12);
                   12172:                             unless (($testdir&$dirptr) ||
                   12173:                                     ($file_name =~ /^\.\.?$/)) {
                   12174:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12175:                             }
                   12176:                         }
                   12177:                     }
                   12178:                 }
1.984     raeburn  12179:             }
                   12180:         }
                   12181:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12182:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12183:                 my $item = $path.'/'.$file;
                   12184:                 unless ($mapping{$item} eq $item) {
                   12185:                     $pathchanges{$item} = 1;
                   12186:                 }
                   12187:                 $existing{$item} = 1;
                   12188:                 $numexisting ++;
                   12189:             } else {
                   12190:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12191:             }
                   12192:         }
1.1071    raeburn  12193:         if ($actionurl eq '/adm/dependencies') {
                   12194:             foreach my $path (keys(%currsubfile)) {
                   12195:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12196:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12197:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12198:                              next if (($rem ne '') &&
                   12199:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12200:                                        (ref($navmap) &&
                   12201:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12202:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12203:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12204:                              $unused{$path.'/'.$file} = 1; 
                   12205:                          }
                   12206:                     }
                   12207:                 }
                   12208:             }
                   12209:         }
1.984     raeburn  12210:     }
1.1249    damieng  12211:     
                   12212:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12213:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12214:     my %currfile;
1.1123    raeburn  12215:     if (($actionurl eq '/adm/portfolio') ||
                   12216:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12217:         my ($dirlistref,$listerror) =
                   12218:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12219:         if (ref($dirlistref) eq 'ARRAY') {
                   12220:             foreach my $line (@{$dirlistref}) {
                   12221:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12222:                 $currfile{$file_name} = 1;
                   12223:             }
1.984     raeburn  12224:         }
1.987     raeburn  12225:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12226:         if (opendir(my $dir,$url)) {
1.987     raeburn  12227:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12228:             map {$currfile{$_} = 1;} @dir_list;
                   12229:         }
1.1084    raeburn  12230:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12231:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12232:               ($args->{'context'} eq 'paste')) ||
                   12233:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12234:         if ($env{'request.course.id'} ne '') {
                   12235:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12236:             if ($dir ne '') {
                   12237:                 my ($dirlistref,$listerror) =
                   12238:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12239:                 if (ref($dirlistref) eq 'ARRAY') {
                   12240:                     foreach my $line (@{$dirlistref}) {
                   12241:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12242:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12243:                         unless (($testdir&$dirptr) ||
                   12244:                                 ($file_name =~ /^\.\.?$/)) {
                   12245:                             $currfile{$file_name} = [$size,$mtime];
                   12246:                         }
                   12247:                     }
                   12248:                 }
                   12249:             }
                   12250:         }
1.984     raeburn  12251:     }
1.1249    damieng  12252:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12253:     # are not in subdirectories, using $currfile
1.984     raeburn  12254:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12255:         if (exists($currfile{$file})) {
1.987     raeburn  12256:             unless ($mapping{$file} eq $file) {
                   12257:                 $pathchanges{$file} = 1;
                   12258:             }
                   12259:             $existing{$file} = 1;
                   12260:             $numexisting ++;
                   12261:         } else {
1.984     raeburn  12262:             $newfiles{$file} = 1;
                   12263:         }
                   12264:     }
1.1071    raeburn  12265:     foreach my $file (keys(%currfile)) {
                   12266:         unless (($file eq $filename) ||
                   12267:                 ($file eq $filename.'.bak') ||
                   12268:                 ($dependencies{$file})) {
1.1085    raeburn  12269:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12270:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12271:                     next if (($rem ne '') &&
                   12272:                              (($env{"httpref.$rem".$file} ne '') ||
                   12273:                               (ref($navmap) &&
                   12274:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12275:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12276:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12277:                 }
1.1085    raeburn  12278:             }
1.1071    raeburn  12279:             $unused{$file} = 1;
                   12280:         }
                   12281:     }
1.1249    damieng  12282:     
                   12283:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12284:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12285:         ($args->{'context'} eq 'paste')) {
                   12286:         $counter = scalar(keys(%existing));
                   12287:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12288:         return ($output,$counter,$numpathchg,\%existing);
                   12289:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12290:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12291:         $counter = scalar(keys(%existing));
                   12292:         $numpathchg = scalar(keys(%pathchanges));
                   12293:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12294:     }
1.1249    damieng  12295:     
                   12296:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12297:     
                   12298:     # $upload_output: missing dependencies (with upload form)
                   12299:     # $modify_output: uploaded dependencies (in use)
                   12300:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12301:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12302:         if ($actionurl eq '/adm/dependencies') {
                   12303:             next if ($embed_file =~ m{^\w+://});
                   12304:         }
1.660     raeburn  12305:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12306:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12307:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12308:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12309:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12310:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12311:         }
1.1123    raeburn  12312:         $upload_output .= '</td>';
1.1071    raeburn  12313:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12314:             $upload_output.='<td align="right">'.
                   12315:                             '<span class="LC_info LC_fontsize_medium">'.
                   12316:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12317:             $numremref++;
1.660     raeburn  12318:         } elsif ($args->{'error_on_invalid_names'}
                   12319:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12320:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12321:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12322:             $numinvalid++;
1.660     raeburn  12323:         } else {
1.1123    raeburn  12324:             $upload_output .= '<td>'.
                   12325:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12326:                                                      $embed_file,\%mapping,
1.1071    raeburn  12327:                                                      $allfiles,$codebase,'upload');
                   12328:             $counter ++;
                   12329:             $numnew ++;
1.987     raeburn  12330:         }
                   12331:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12332:     }
                   12333:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12334:         if ($actionurl eq '/adm/dependencies') {
                   12335:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12336:             $modify_output .= &start_data_table_row().
                   12337:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12338:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12339:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12340:                               '<td>'.$size.'</td>'.
                   12341:                               '<td>'.$mtime.'</td>'.
                   12342:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12343:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12344:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12345:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12346:                               &embedded_file_element('upload_embedded',$counter,
                   12347:                                                      $embed_file,\%mapping,
                   12348:                                                      $allfiles,$codebase,'modify').
                   12349:                               '</div></td>'.
                   12350:                               &end_data_table_row()."\n";
                   12351:             $counter ++;
                   12352:         } else {
                   12353:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12354:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12355:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12356:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12357:                               &Apache::loncommon::end_data_table_row()."\n";
                   12358:         }
                   12359:     }
                   12360:     my $delidx = $counter;
                   12361:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12362:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12363:         $delete_output .= &start_data_table_row().
                   12364:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12365:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12366:                           '<td>'.$size.'</td>'.
                   12367:                           '<td>'.$mtime.'</td>'.
                   12368:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12369:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12370:                           &embedded_file_element('upload_embedded',$delidx,
                   12371:                                                  $oldfile,\%mapping,$allfiles,
                   12372:                                                  $codebase,'delete').'</td>'.
                   12373:                           &end_data_table_row()."\n"; 
                   12374:         $numunused ++;
                   12375:         $delidx ++;
1.987     raeburn  12376:     }
                   12377:     if ($upload_output) {
                   12378:         $upload_output = &start_data_table().
                   12379:                          $upload_output.
                   12380:                          &end_data_table()."\n";
                   12381:     }
1.1071    raeburn  12382:     if ($modify_output) {
                   12383:         $modify_output = &start_data_table().
                   12384:                          &start_data_table_header_row().
                   12385:                          '<th>'.&mt('File').'</th>'.
                   12386:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12387:                          '<th>'.&mt('Modified').'</th>'.
                   12388:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12389:                          &end_data_table_header_row().
                   12390:                          $modify_output.
                   12391:                          &end_data_table()."\n";
                   12392:     }
                   12393:     if ($delete_output) {
                   12394:         $delete_output = &start_data_table().
                   12395:                          &start_data_table_header_row().
                   12396:                          '<th>'.&mt('File').'</th>'.
                   12397:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12398:                          '<th>'.&mt('Modified').'</th>'.
                   12399:                          '<th>'.&mt('Delete?').'</th>'.
                   12400:                          &end_data_table_header_row().
                   12401:                          $delete_output.
                   12402:                          &end_data_table()."\n";
                   12403:     }
1.987     raeburn  12404:     my $applies = 0;
                   12405:     if ($numremref) {
                   12406:         $applies ++;
                   12407:     }
                   12408:     if ($numinvalid) {
                   12409:         $applies ++;
                   12410:     }
                   12411:     if ($numexisting) {
                   12412:         $applies ++;
                   12413:     }
1.1071    raeburn  12414:     if ($counter || $numunused) {
1.987     raeburn  12415:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12416:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12417:                   $state.'<h3>'.$heading.'</h3>'; 
                   12418:         if ($actionurl eq '/adm/dependencies') {
                   12419:             if ($numnew) {
                   12420:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12421:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12422:                            $upload_output.'<br />'."\n";
                   12423:             }
                   12424:             if ($numexisting) {
                   12425:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12426:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12427:                            $modify_output.'<br />'."\n";
                   12428:                            $buttontext = &mt('Save changes');
                   12429:             }
                   12430:             if ($numunused) {
                   12431:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12432:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12433:                            $delete_output.'<br />'."\n";
                   12434:                            $buttontext = &mt('Save changes');
                   12435:             }
                   12436:         } else {
                   12437:             $output .= $upload_output.'<br />'."\n";
                   12438:         }
                   12439:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12440:                    $counter.'" />'."\n";
                   12441:         if ($actionurl eq '/adm/dependencies') { 
                   12442:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12443:                        $numnew.'" />'."\n";
                   12444:         } elsif ($actionurl eq '') {
1.987     raeburn  12445:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12446:         }
                   12447:     } elsif ($applies) {
                   12448:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12449:         if ($applies > 1) {
                   12450:             $output .=  
1.1123    raeburn  12451:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12452:             if ($numremref) {
                   12453:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12454:             }
                   12455:             if ($numinvalid) {
                   12456:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12457:             }
                   12458:             if ($numexisting) {
                   12459:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12460:             }
                   12461:             $output .= '</ul><br />';
                   12462:         } elsif ($numremref) {
                   12463:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12464:         } elsif ($numinvalid) {
                   12465:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12466:         } elsif ($numexisting) {
                   12467:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12468:         }
                   12469:         $output .= $upload_output.'<br />';
                   12470:     }
                   12471:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12472:     $chgcount = $counter;
1.987     raeburn  12473:     if (keys(%pathchanges) > 0) {
                   12474:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12475:             if ($counter) {
1.987     raeburn  12476:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12477:                                                   $embed_file,\%mapping,
1.1071    raeburn  12478:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12479:             } else {
                   12480:                 $pathchange_output .= 
                   12481:                     &start_data_table_row().
                   12482:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12483:                     $chgcount.'" checked="checked" /></td>'.
                   12484:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12485:                     '<td>'.$embed_file.
                   12486:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12487:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12488:                     '</td>'.&end_data_table_row();
1.660     raeburn  12489:             }
1.987     raeburn  12490:             $numpathchg ++;
                   12491:             $chgcount ++;
1.660     raeburn  12492:         }
                   12493:     }
1.1127    raeburn  12494:     if (($counter) || ($numunused)) {
1.987     raeburn  12495:         if ($numpathchg) {
                   12496:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12497:                        $numpathchg.'" />'."\n";
                   12498:         }
                   12499:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12500:             ($actionurl eq '/adm/imsimport')) {
                   12501:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12502:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12503:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12504:         } elsif ($actionurl eq '/adm/dependencies') {
                   12505:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12506:         }
1.1123    raeburn  12507:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12508:     } elsif ($numpathchg) {
                   12509:         my %pathchange = ();
                   12510:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12511:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12512:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12513:         }
1.987     raeburn  12514:     }
1.1071    raeburn  12515:     return ($output,$counter,$numpathchg);
1.987     raeburn  12516: }
                   12517: 
1.1147    raeburn  12518: =pod
                   12519: 
                   12520: =item * clean_path($name)
                   12521: 
                   12522: Performs clean-up of directories, subdirectories and filename in an
                   12523: embedded object, referenced in an HTML file which is being uploaded
                   12524: to a course or portfolio, where 
                   12525: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12526: checked.
                   12527: 
                   12528: Clean-up is similar to replacements in lonnet::clean_filename()
                   12529: except each / between sub-directory and next level is preserved.
                   12530: 
                   12531: =cut
                   12532: 
                   12533: sub clean_path {
                   12534:     my ($embed_file) = @_;
                   12535:     $embed_file =~s{^/+}{};
                   12536:     my @contents;
                   12537:     if ($embed_file =~ m{/}) {
                   12538:         @contents = split(/\//,$embed_file);
                   12539:     } else {
                   12540:         @contents = ($embed_file);
                   12541:     }
                   12542:     my $lastidx = scalar(@contents)-1;
                   12543:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12544:         $contents[$i]=~s{\\}{/}g;
                   12545:         $contents[$i]=~s/\s+/\_/g;
                   12546:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12547:         if ($i == $lastidx) {
                   12548:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12549:         }
                   12550:     }
                   12551:     if ($lastidx > 0) {
                   12552:         return join('/',@contents);
                   12553:     } else {
                   12554:         return $contents[0];
                   12555:     }
                   12556: }
                   12557: 
1.987     raeburn  12558: sub embedded_file_element {
1.1071    raeburn  12559:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12560:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12561:                    (ref($codebase) eq 'HASH'));
                   12562:     my $output;
1.1071    raeburn  12563:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12564:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12565:     }
                   12566:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12567:                &escape($embed_file).'" />';
                   12568:     unless (($context eq 'upload_embedded') && 
                   12569:             ($mapping->{$embed_file} eq $embed_file)) {
                   12570:         $output .='
                   12571:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12572:     }
                   12573:     my $attrib;
                   12574:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12575:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12576:     }
                   12577:     $output .=
                   12578:         "\n\t\t".
                   12579:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12580:         $attrib.'" />';
                   12581:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12582:         $output .=
                   12583:             "\n\t\t".
                   12584:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12585:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12586:     }
1.987     raeburn  12587:     return $output;
1.660     raeburn  12588: }
                   12589: 
1.1071    raeburn  12590: sub get_dependency_details {
                   12591:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12592:     my ($size,$mtime,$showsize,$showmtime);
                   12593:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12594:         if ($embed_file =~ m{/}) {
                   12595:             my ($path,$fname) = split(/\//,$embed_file);
                   12596:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12597:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12598:             }
                   12599:         } else {
                   12600:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12601:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12602:             }
                   12603:         }
                   12604:         $showsize = $size/1024.0;
                   12605:         $showsize = sprintf("%.1f",$showsize);
                   12606:         if ($mtime > 0) {
                   12607:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12608:         }
                   12609:     }
                   12610:     return ($showsize,$showmtime);
                   12611: }
                   12612: 
                   12613: sub ask_embedded_js {
                   12614:     return <<"END";
                   12615: <script type="text/javascript"">
                   12616: // <![CDATA[
                   12617: function toggleBrowse(counter) {
                   12618:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12619:     var fileid = document.getElementById('embedded_item_'+counter);
                   12620:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12621:     if (chkboxid.checked == true) {
                   12622:         uploaddivid.style.display='block';
                   12623:     } else {
                   12624:         uploaddivid.style.display='none';
                   12625:         fileid.value = '';
                   12626:     }
                   12627: }
                   12628: // ]]>
                   12629: </script>
                   12630: 
                   12631: END
                   12632: }
                   12633: 
1.661     raeburn  12634: sub upload_embedded {
                   12635:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12636:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12637:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12638:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12639:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12640:         my $orig_uploaded_filename =
                   12641:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12642:         foreach my $type ('orig','ref','attrib','codebase') {
                   12643:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12644:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12645:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12646:             }
                   12647:         }
1.661     raeburn  12648:         my ($path,$fname) =
                   12649:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12650:         # no path, whole string is fname
                   12651:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12652:         $fname = &Apache::lonnet::clean_filename($fname);
                   12653:         # See if there is anything left
                   12654:         next if ($fname eq '');
                   12655: 
                   12656:         # Check if file already exists as a file or directory.
                   12657:         my ($state,$msg);
                   12658:         if ($context eq 'portfolio') {
                   12659:             my $port_path = $dirpath;
                   12660:             if ($group ne '') {
                   12661:                 $port_path = "groups/$group/$port_path";
                   12662:             }
1.987     raeburn  12663:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12664:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12665:                                               $dir_root,$port_path,$disk_quota,
                   12666:                                               $current_disk_usage,$uname,$udom);
                   12667:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12668:                 || $state eq 'file_locked') {
1.661     raeburn  12669:                 $output .= $msg;
                   12670:                 next;
                   12671:             }
                   12672:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12673:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12674:             if ($state eq 'exists') {
                   12675:                 $output .= $msg;
                   12676:                 next;
                   12677:             }
                   12678:         }
                   12679:         # Check if extension is valid
                   12680:         if (($fname =~ /\.(\w+)$/) &&
                   12681:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12682:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12683:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12684:             next;
                   12685:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12686:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12687:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12688:             next;
                   12689:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12690:             $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  12691:             next;
                   12692:         }
                   12693:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12694:         my $subdir = $path;
                   12695:         $subdir =~ s{/+$}{};
1.661     raeburn  12696:         if ($context eq 'portfolio') {
1.984     raeburn  12697:             my $result;
                   12698:             if ($state eq 'existingfile') {
                   12699:                 $result=
                   12700:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12701:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12702:             } else {
1.984     raeburn  12703:                 $result=
                   12704:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12705:                                                     $dirpath.
1.1123    raeburn  12706:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12707:                 if ($result !~ m|^/uploaded/|) {
                   12708:                     $output .= '<span class="LC_error">'
                   12709:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12710:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12711:                                .'</span><br />';
                   12712:                     next;
                   12713:                 } else {
1.987     raeburn  12714:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12715:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12716:                 }
1.661     raeburn  12717:             }
1.1123    raeburn  12718:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12719:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12720:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12721:             my $result =
1.1126    raeburn  12722:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12723:             if ($result !~ m|^/uploaded/|) {
                   12724:                 $output .= '<span class="LC_error">'
                   12725:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12726:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12727:                            .'</span><br />';
                   12728:                     next;
                   12729:             } else {
                   12730:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12731:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12732:                 if ($context eq 'syllabus') {
                   12733:                     &Apache::lonnet::make_public_indefinitely($result);
                   12734:                 }
1.987     raeburn  12735:             }
1.661     raeburn  12736:         } else {
                   12737: # Save the file
                   12738:             my $target = $env{'form.embedded_item_'.$i};
                   12739:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12740:             my $dest = $fullpath.$fname;
                   12741:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12742:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12743:             my $count;
                   12744:             my $filepath = $dir_root;
1.1027    raeburn  12745:             foreach my $subdir (@parts) {
                   12746:                 $filepath .= "/$subdir";
                   12747:                 if (!-e $filepath) {
1.661     raeburn  12748:                     mkdir($filepath,0770);
                   12749:                 }
                   12750:             }
                   12751:             my $fh;
                   12752:             if (!open($fh,'>'.$dest)) {
                   12753:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12754:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12755:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12756:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12757:                            '</span><br />';
                   12758:             } else {
                   12759:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12760:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12761:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12762:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12763:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12764:                               '</span><br />';
                   12765:                 } else {
1.987     raeburn  12766:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12767:                                $url.'</span>').'<br />';
                   12768:                     unless ($context eq 'testbank') {
                   12769:                         $footer .= &mt('View embedded file: [_1]',
                   12770:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12771:                     }
                   12772:                 }
                   12773:                 close($fh);
                   12774:             }
                   12775:         }
                   12776:         if ($env{'form.embedded_ref_'.$i}) {
                   12777:             $pathchange{$i} = 1;
                   12778:         }
                   12779:     }
                   12780:     if ($output) {
                   12781:         $output = '<p>'.$output.'</p>';
                   12782:     }
                   12783:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12784:     $returnflag = 'ok';
1.1071    raeburn  12785:     my $numpathchgs = scalar(keys(%pathchange));
                   12786:     if ($numpathchgs > 0) {
1.987     raeburn  12787:         if ($context eq 'portfolio') {
                   12788:             $output .= '<p>'.&mt('or').'</p>';
                   12789:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12790:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12791:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12792:             $returnflag = 'modify_orightml';
                   12793:         }
                   12794:     }
1.1071    raeburn  12795:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12796: }
                   12797: 
                   12798: sub modify_html_form {
                   12799:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12800:     my $end = 0;
                   12801:     my $modifyform;
                   12802:     if ($context eq 'upload_embedded') {
                   12803:         return unless (ref($pathchange) eq 'HASH');
                   12804:         if ($env{'form.number_embedded_items'}) {
                   12805:             $end += $env{'form.number_embedded_items'};
                   12806:         }
                   12807:         if ($env{'form.number_pathchange_items'}) {
                   12808:             $end += $env{'form.number_pathchange_items'};
                   12809:         }
                   12810:         if ($end) {
                   12811:             for (my $i=0; $i<$end; $i++) {
                   12812:                 if ($i < $env{'form.number_embedded_items'}) {
                   12813:                     next unless($pathchange->{$i});
                   12814:                 }
                   12815:                 $modifyform .=
                   12816:                     &start_data_table_row().
                   12817:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12818:                     'checked="checked" /></td>'.
                   12819:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12820:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12821:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12822:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12823:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12824:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12825:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12826:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12827:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12828:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12829:                     &end_data_table_row();
1.1071    raeburn  12830:             }
1.987     raeburn  12831:         }
                   12832:     } else {
                   12833:         $modifyform = $pathchgtable;
                   12834:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12835:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12836:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12837:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12838:         }
                   12839:     }
                   12840:     if ($modifyform) {
1.1071    raeburn  12841:         if ($actionurl eq '/adm/dependencies') {
                   12842:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12843:         }
1.987     raeburn  12844:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12845:                '<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".
                   12846:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12847:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12848:                '</ol></p>'."\n".'<p>'.
                   12849:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12850:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12851:                &start_data_table()."\n".
                   12852:                &start_data_table_header_row().
                   12853:                '<th>'.&mt('Change?').'</th>'.
                   12854:                '<th>'.&mt('Current reference').'</th>'.
                   12855:                '<th>'.&mt('Required reference').'</th>'.
                   12856:                &end_data_table_header_row()."\n".
                   12857:                $modifyform.
                   12858:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12859:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12860:                '</form>'."\n";
                   12861:     }
                   12862:     return;
                   12863: }
                   12864: 
                   12865: sub modify_html_refs {
1.1123    raeburn  12866:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12867:     my $container;
                   12868:     if ($context eq 'portfolio') {
                   12869:         $container = $env{'form.container'};
                   12870:     } elsif ($context eq 'coursedoc') {
                   12871:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12872:     } elsif ($context eq 'manage_dependencies') {
                   12873:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12874:         $container = "/$container";
1.1123    raeburn  12875:     } elsif ($context eq 'syllabus') {
                   12876:         $container = $url;
1.987     raeburn  12877:     } else {
1.1027    raeburn  12878:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12879:     }
                   12880:     my (%allfiles,%codebase,$output,$content);
                   12881:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12882:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12883:         if (wantarray) {
                   12884:             return ('',0,0); 
                   12885:         } else {
                   12886:             return;
                   12887:         }
                   12888:     }
                   12889:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12890:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12891:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12892:             if (wantarray) {
                   12893:                 return ('',0,0);
                   12894:             } else {
                   12895:                 return;
                   12896:             }
                   12897:         } 
1.987     raeburn  12898:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12899:         if ($content eq '-1') {
                   12900:             if (wantarray) {
                   12901:                 return ('',0,0);
                   12902:             } else {
                   12903:                 return;
                   12904:             }
                   12905:         }
1.987     raeburn  12906:     } else {
1.1071    raeburn  12907:         unless ($container =~ /^\Q$dir_root\E/) {
                   12908:             if (wantarray) {
                   12909:                 return ('',0,0);
                   12910:             } else {
                   12911:                 return;
                   12912:             }
                   12913:         } 
1.1317    raeburn  12914:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12915:             $content = join('', <$fh>);
                   12916:             close($fh);
                   12917:         } else {
1.1071    raeburn  12918:             if (wantarray) {
                   12919:                 return ('',0,0);
                   12920:             } else {
                   12921:                 return;
                   12922:             }
1.987     raeburn  12923:         }
                   12924:     }
                   12925:     my ($count,$codebasecount) = (0,0);
                   12926:     my $mm = new File::MMagic;
                   12927:     my $mime_type = $mm->checktype_contents($content);
                   12928:     if ($mime_type eq 'text/html') {
                   12929:         my $parse_result = 
                   12930:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12931:                                                     \%codebase,\$content);
                   12932:         if ($parse_result eq 'ok') {
                   12933:             foreach my $i (@changes) {
                   12934:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12935:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12936:                 if ($allfiles{$ref}) {
                   12937:                     my $newname =  $orig;
                   12938:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12939:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12940:                     if ($attrib_regexp =~ /:/) {
                   12941:                         $attrib_regexp =~ s/\:/|/g;
                   12942:                     }
                   12943:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12944:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12945:                         $count += $numchg;
1.1123    raeburn  12946:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12947:                         delete($allfiles{$ref});
1.987     raeburn  12948:                     }
                   12949:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12950:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12951:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12952:                         $codebasecount ++;
                   12953:                     }
                   12954:                 }
                   12955:             }
1.1123    raeburn  12956:             my $skiprewrites;
1.987     raeburn  12957:             if ($count || $codebasecount) {
                   12958:                 my $saveresult;
1.1071    raeburn  12959:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12960:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12961:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12962:                     if ($url eq $container) {
                   12963:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12964:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12965:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12966:                                             $fname.'</span>').'</p>';
1.987     raeburn  12967:                     } else {
                   12968:                          $output = '<p class="LC_error">'.
                   12969:                                    &mt('Error: update failed for: [_1].',
                   12970:                                    '<span class="LC_filename">'.
                   12971:                                    $container.'</span>').'</p>';
                   12972:                     }
1.1123    raeburn  12973:                     if ($context eq 'syllabus') {
                   12974:                         unless ($saveresult eq 'ok') {
                   12975:                             $skiprewrites = 1;
                   12976:                         }
                   12977:                     }
1.987     raeburn  12978:                 } else {
1.1317    raeburn  12979:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12980:                         print $fh $content;
                   12981:                         close($fh);
                   12982:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12983:                                   $count,'<span class="LC_filename">'.
                   12984:                                   $container.'</span>').'</p>';
1.661     raeburn  12985:                     } else {
1.987     raeburn  12986:                          $output = '<p class="LC_error">'.
                   12987:                                    &mt('Error: could not update [_1].',
                   12988:                                    '<span class="LC_filename">'.
                   12989:                                    $container.'</span>').'</p>';
1.661     raeburn  12990:                     }
                   12991:                 }
                   12992:             }
1.1123    raeburn  12993:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12994:                 my ($actionurl,$state);
                   12995:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12996:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12997:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12998:                                               \%codebase,
                   12999:                                               {'context' => 'rewrites',
                   13000:                                                'ignore_remote_references' => 1,});
                   13001:                 if (ref($mapping) eq 'HASH') {
                   13002:                     my $rewrites = 0;
                   13003:                     foreach my $key (keys(%{$mapping})) {
                   13004:                         next if ($key =~ m{^https?://});
                   13005:                         my $ref = $mapping->{$key};
                   13006:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13007:                         my $attrib;
                   13008:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13009:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13010:                         }
                   13011:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13012:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13013:                             $rewrites += $numchg;
                   13014:                         }
                   13015:                     }
                   13016:                     if ($rewrites) {
                   13017:                         my $saveresult; 
                   13018:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13019:                         if ($url eq $container) {
                   13020:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13021:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13022:                                             $count,'<span class="LC_filename">'.
                   13023:                                             $fname.'</span>').'</p>';
                   13024:                         } else {
                   13025:                             $output .= '<p class="LC_error">'.
                   13026:                                        &mt('Error: could not update links in [_1].',
                   13027:                                        '<span class="LC_filename">'.
                   13028:                                        $container.'</span>').'</p>';
                   13029: 
                   13030:                         }
                   13031:                     }
                   13032:                 }
                   13033:             }
1.987     raeburn  13034:         } else {
                   13035:             &logthis('Failed to parse '.$container.
                   13036:                      ' to modify references: '.$parse_result);
1.661     raeburn  13037:         }
                   13038:     }
1.1071    raeburn  13039:     if (wantarray) {
                   13040:         return ($output,$count,$codebasecount);
                   13041:     } else {
                   13042:         return $output;
                   13043:     }
1.661     raeburn  13044: }
                   13045: 
                   13046: sub check_for_existing {
                   13047:     my ($path,$fname,$element) = @_;
                   13048:     my ($state,$msg);
                   13049:     if (-d $path.'/'.$fname) {
                   13050:         $state = 'exists';
                   13051:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13052:     } elsif (-e $path.'/'.$fname) {
                   13053:         $state = 'exists';
                   13054:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13055:     }
                   13056:     if ($state eq 'exists') {
                   13057:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13058:     }
                   13059:     return ($state,$msg);
                   13060: }
                   13061: 
                   13062: sub check_for_upload {
                   13063:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13064:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13065:     my $filesize = length($env{'form.'.$element});
                   13066:     if (!$filesize) {
                   13067:         my $msg = '<span class="LC_error">'.
                   13068:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13069:                       '<span class="LC_filename">'.$fname.'</span>',
                   13070:                       $filesize).'<br />'.
1.1007    raeburn  13071:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13072:                   '</span>';
                   13073:         return ('zero_bytes',$msg);
                   13074:     }
                   13075:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13076:     my $getpropath = 1;
1.1021    raeburn  13077:     my ($dirlistref,$listerror) =
                   13078:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13079:     my $found_file = 0;
                   13080:     my $locked_file = 0;
1.991     raeburn  13081:     my @lockers;
                   13082:     my $navmap;
                   13083:     if ($env{'request.course.id'}) {
                   13084:         $navmap = Apache::lonnavmaps::navmap->new();
                   13085:     }
1.1021    raeburn  13086:     if (ref($dirlistref) eq 'ARRAY') {
                   13087:         foreach my $line (@{$dirlistref}) {
                   13088:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13089:             if ($file_name eq $fname){
                   13090:                 $file_name = $path.$file_name;
                   13091:                 if ($group ne '') {
                   13092:                     $file_name = $group.$file_name;
                   13093:                 }
                   13094:                 $found_file = 1;
                   13095:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13096:                     foreach my $lock (@lockers) {
                   13097:                         if (ref($lock) eq 'ARRAY') {
                   13098:                             my ($symb,$crsid) = @{$lock};
                   13099:                             if ($crsid eq $env{'request.course.id'}) {
                   13100:                                 if (ref($navmap)) {
                   13101:                                     my $res = $navmap->getBySymb($symb);
                   13102:                                     foreach my $part (@{$res->parts()}) { 
                   13103:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13104:                                         unless (($slot_status == $res->RESERVED) ||
                   13105:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13106:                                             $locked_file = 1;
                   13107:                                         }
1.991     raeburn  13108:                                     }
1.1021    raeburn  13109:                                 } else {
                   13110:                                     $locked_file = 1;
1.991     raeburn  13111:                                 }
                   13112:                             } else {
                   13113:                                 $locked_file = 1;
                   13114:                             }
                   13115:                         }
1.1021    raeburn  13116:                    }
                   13117:                 } else {
                   13118:                     my @info = split(/\&/,$rest);
                   13119:                     my $currsize = $info[6]/1000;
                   13120:                     if ($currsize < $filesize) {
                   13121:                         my $extra = $filesize - $currsize;
                   13122:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13123:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13124:                                       &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   13125:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13126:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13127:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13128:                             return ('will_exceed_quota',$msg);
                   13129:                         }
1.984     raeburn  13130:                     }
                   13131:                 }
1.661     raeburn  13132:             }
                   13133:         }
                   13134:     }
                   13135:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13136:         my $msg = '<p class="LC_warning">'.
                   13137:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13138:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13139:         return ('will_exceed_quota',$msg);
                   13140:     } elsif ($found_file) {
                   13141:         if ($locked_file) {
1.1179    bisitz   13142:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13143:             $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   13144:             $msg .= '</p>';
1.661     raeburn  13145:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13146:             return ('file_locked',$msg);
                   13147:         } else {
1.1179    bisitz   13148:             my $msg = '<p class="LC_error">';
1.984     raeburn  13149:             $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   13150:             $msg .= '</p>';
1.984     raeburn  13151:             return ('existingfile',$msg);
1.661     raeburn  13152:         }
                   13153:     }
                   13154: }
                   13155: 
1.987     raeburn  13156: sub check_for_traversal {
                   13157:     my ($path,$url,$toplevel) = @_;
                   13158:     my @parts=split(/\//,$path);
                   13159:     my $cleanpath;
                   13160:     my $fullpath = $url;
                   13161:     for (my $i=0;$i<@parts;$i++) {
                   13162:         next if ($parts[$i] eq '.');
                   13163:         if ($parts[$i] eq '..') {
                   13164:             $fullpath =~ s{([^/]+/)$}{};
                   13165:         } else {
                   13166:             $fullpath .= $parts[$i].'/';
                   13167:         }
                   13168:     }
                   13169:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13170:         $cleanpath = $1;
                   13171:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13172:         my $curr_toprel = $1;
                   13173:         my @parts = split(/\//,$curr_toprel);
                   13174:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13175:         my @urlparts = split(/\//,$url_toprel);
                   13176:         my $doubledots;
                   13177:         my $startdiff = -1;
                   13178:         for (my $i=0; $i<@urlparts; $i++) {
                   13179:             if ($startdiff == -1) {
                   13180:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13181:                     $startdiff = $i;
                   13182:                     $doubledots .= '../';
                   13183:                 }
                   13184:             } else {
                   13185:                 $doubledots .= '../';
                   13186:             }
                   13187:         }
                   13188:         if ($startdiff > -1) {
                   13189:             $cleanpath = $doubledots;
                   13190:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13191:                 $cleanpath .= $parts[$i].'/';
                   13192:             }
                   13193:         }
                   13194:     }
                   13195:     $cleanpath =~ s{(/)$}{};
                   13196:     return $cleanpath;
                   13197: }
1.31      albertel 13198: 
1.1053    raeburn  13199: sub is_archive_file {
                   13200:     my ($mimetype) = @_;
                   13201:     if (($mimetype eq 'application/octet-stream') ||
                   13202:         ($mimetype eq 'application/x-stuffit') ||
                   13203:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13204:         return 1;
                   13205:     }
                   13206:     return;
                   13207: }
                   13208: 
                   13209: sub decompress_form {
1.1065    raeburn  13210:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13211:     my %lt = &Apache::lonlocal::texthash (
                   13212:         this => 'This file is an archive file.',
1.1067    raeburn  13213:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13214:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13215:         youm => 'You may wish to extract its contents.',
                   13216:         extr => 'Extract contents',
1.1067    raeburn  13217:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13218:         proa => 'Process automatically?',
1.1053    raeburn  13219:         yes  => 'Yes',
                   13220:         no   => 'No',
1.1067    raeburn  13221:         fold => 'Title for folder containing movie',
                   13222:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13223:     );
1.1065    raeburn  13224:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13225:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13226:     my $info = &list_archive_contents($fileloc,\@paths);
                   13227:     if (@paths) {
                   13228:         foreach my $path (@paths) {
                   13229:             $path =~ s{^/}{};
1.1067    raeburn  13230:             if ($path =~ m{^([^/]+)/$}) {
                   13231:                 $topdir = $1;
                   13232:             }
1.1065    raeburn  13233:             if ($path =~ m{^([^/]+)/}) {
                   13234:                 $toplevel{$1} = $path;
                   13235:             } else {
                   13236:                 $toplevel{$path} = $path;
                   13237:             }
                   13238:         }
                   13239:     }
1.1067    raeburn  13240:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13241:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13242:                         "$topdir/media/",
                   13243:                         "$topdir/media/$topdir.mp4",
                   13244:                         "$topdir/media/FirstFrame.png",
                   13245:                         "$topdir/media/player.swf",
                   13246:                         "$topdir/media/swfobject.js",
                   13247:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13248:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13249:                          "$topdir/$topdir.mp4",
                   13250:                          "$topdir/$topdir\_config.xml",
                   13251:                          "$topdir/$topdir\_controller.swf",
                   13252:                          "$topdir/$topdir\_embed.css",
                   13253:                          "$topdir/$topdir\_First_Frame.png",
                   13254:                          "$topdir/$topdir\_player.html",
                   13255:                          "$topdir/$topdir\_Thumbnails.png",
                   13256:                          "$topdir/playerProductInstall.swf",
                   13257:                          "$topdir/scripts/",
                   13258:                          "$topdir/scripts/config_xml.js",
                   13259:                          "$topdir/scripts/handlebars.js",
                   13260:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13261:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13262:                          "$topdir/scripts/modernizr.js",
                   13263:                          "$topdir/scripts/player-min.js",
                   13264:                          "$topdir/scripts/swfobject.js",
                   13265:                          "$topdir/skins/",
                   13266:                          "$topdir/skins/configuration_express.xml",
                   13267:                          "$topdir/skins/express_show/",
                   13268:                          "$topdir/skins/express_show/player-min.css",
                   13269:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13270:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13271:                          "$topdir/$topdir.mp4",
                   13272:                          "$topdir/$topdir\_config.xml",
                   13273:                          "$topdir/$topdir\_controller.swf",
                   13274:                          "$topdir/$topdir\_embed.css",
                   13275:                          "$topdir/$topdir\_First_Frame.png",
                   13276:                          "$topdir/$topdir\_player.html",
                   13277:                          "$topdir/$topdir\_Thumbnails.png",
                   13278:                          "$topdir/playerProductInstall.swf",
                   13279:                          "$topdir/scripts/",
                   13280:                          "$topdir/scripts/config_xml.js",
                   13281:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13282:                          "$topdir/skins/",
                   13283:                          "$topdir/skins/configuration_express.xml",
                   13284:                          "$topdir/skins/express_show/",
                   13285:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13286:                          "$topdir/skins/express_show/spritesheet.png",
                   13287:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13288:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13289:         if (@diffs == 0) {
1.1164    raeburn  13290:             $is_camtasia = 6;
                   13291:         } else {
1.1197    raeburn  13292:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13293:             if (@diffs == 0) {
                   13294:                 $is_camtasia = 8;
1.1197    raeburn  13295:             } else {
                   13296:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13297:                 if (@diffs == 0) {
                   13298:                     $is_camtasia = 8;
                   13299:                 }
1.1164    raeburn  13300:             }
1.1067    raeburn  13301:         }
                   13302:     }
                   13303:     my $output;
                   13304:     if ($is_camtasia) {
                   13305:         $output = <<"ENDCAM";
                   13306: <script type="text/javascript" language="Javascript">
                   13307: // <![CDATA[
                   13308: 
                   13309: function camtasiaToggle() {
                   13310:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13311:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13312:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13313:                 document.getElementById('camtasia_titles').style.display='block';
                   13314:             } else {
                   13315:                 document.getElementById('camtasia_titles').style.display='none';
                   13316:             }
                   13317:         }
                   13318:     }
                   13319:     return;
                   13320: }
                   13321: 
                   13322: // ]]>
                   13323: </script>
                   13324: <p>$lt{'camt'}</p>
                   13325: ENDCAM
1.1065    raeburn  13326:     } else {
1.1067    raeburn  13327:         $output = '<p>'.$lt{'this'};
                   13328:         if ($info eq '') {
                   13329:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13330:         } else {
                   13331:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13332:                        '<div><pre>'.$info.'</pre></div>';
                   13333:         }
1.1065    raeburn  13334:     }
1.1067    raeburn  13335:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13336:     my $duplicates;
                   13337:     my $num = 0;
                   13338:     if (ref($dirlist) eq 'ARRAY') {
                   13339:         foreach my $item (@{$dirlist}) {
                   13340:             if (ref($item) eq 'ARRAY') {
                   13341:                 if (exists($toplevel{$item->[0]})) {
                   13342:                     $duplicates .= 
                   13343:                         &start_data_table_row().
                   13344:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13345:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13346:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13347:                         'value="1" />'.&mt('Yes').'</label>'.
                   13348:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13349:                         '<td>'.$item->[0].'</td>';
                   13350:                     if ($item->[2]) {
                   13351:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13352:                     } else {
                   13353:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13354:                     }
                   13355:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13356:                                    '<td>'.
                   13357:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13358:                                    '</td>'.
                   13359:                                    &end_data_table_row();
                   13360:                     $num ++;
                   13361:                 }
                   13362:             }
                   13363:         }
                   13364:     }
                   13365:     my $itemcount;
                   13366:     if (@paths > 0) {
                   13367:         $itemcount = scalar(@paths);
                   13368:     } else {
                   13369:         $itemcount = 1;
                   13370:     }
1.1067    raeburn  13371:     if ($is_camtasia) {
                   13372:         $output .= $lt{'auto'}.'<br />'.
                   13373:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13374:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13375:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13376:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13377:                    $lt{'no'}.'</label></span><br />'.
                   13378:                    '<div id="camtasia_titles" style="display:block">'.
                   13379:                    &Apache::lonhtmlcommon::start_pick_box().
                   13380:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13381:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13382:                    &Apache::lonhtmlcommon::row_closure().
                   13383:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13384:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13385:                    &Apache::lonhtmlcommon::row_closure(1).
                   13386:                    &Apache::lonhtmlcommon::end_pick_box().
                   13387:                    '</div>';
                   13388:     }
1.1065    raeburn  13389:     $output .= 
                   13390:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13391:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13392:         "\n";
1.1065    raeburn  13393:     if ($duplicates ne '') {
                   13394:         $output .= '<p><span class="LC_warning">'.
                   13395:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13396:                    &start_data_table().
                   13397:                    &start_data_table_header_row().
                   13398:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13399:                    '<th>'.&mt('Name').'</th>'.
                   13400:                    '<th>'.&mt('Type').'</th>'.
                   13401:                    '<th>'.&mt('Size').'</th>'.
                   13402:                    '<th>'.&mt('Last modified').'</th>'.
                   13403:                    &end_data_table_header_row().
                   13404:                    $duplicates.
                   13405:                    &end_data_table().
                   13406:                    '</p>';
                   13407:     }
1.1067    raeburn  13408:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13409:     if (ref($hiddenelements) eq 'HASH') {
                   13410:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13411:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13412:         }
                   13413:     }
                   13414:     $output .= <<"END";
1.1067    raeburn  13415: <br />
1.1053    raeburn  13416: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13417: </form>
                   13418: $noextract
                   13419: END
                   13420:     return $output;
                   13421: }
                   13422: 
1.1065    raeburn  13423: sub decompression_utility {
                   13424:     my ($program) = @_;
                   13425:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13426:     my $location;
                   13427:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13428:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13429:                          '/usr/sbin/') {
                   13430:             if (-x $dir.$program) {
                   13431:                 $location = $dir.$program;
                   13432:                 last;
                   13433:             }
                   13434:         }
                   13435:     }
                   13436:     return $location;
                   13437: }
                   13438: 
                   13439: sub list_archive_contents {
                   13440:     my ($file,$pathsref) = @_;
                   13441:     my (@cmd,$output);
                   13442:     my $needsregexp;
                   13443:     if ($file =~ /\.zip$/) {
                   13444:         @cmd = (&decompression_utility('unzip'),"-l");
                   13445:         $needsregexp = 1;
                   13446:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13447:              ($file =~ /\.tgz$/)) {
                   13448:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13449:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13450:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13451:     } elsif ($file =~ m|\.tar$|) {
                   13452:         @cmd = (&decompression_utility('tar'),"-tf");
                   13453:     }
                   13454:     if (@cmd) {
                   13455:         undef($!);
                   13456:         undef($@);
                   13457:         if (open(my $fh,"-|", @cmd, $file)) {
                   13458:             while (my $line = <$fh>) {
                   13459:                 $output .= $line;
                   13460:                 chomp($line);
                   13461:                 my $item;
                   13462:                 if ($needsregexp) {
                   13463:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13464:                 } else {
                   13465:                     $item = $line;
                   13466:                 }
                   13467:                 if ($item ne '') {
                   13468:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13469:                         push(@{$pathsref},$item);
                   13470:                     } 
                   13471:                 }
                   13472:             }
                   13473:             close($fh);
                   13474:         }
                   13475:     }
                   13476:     return $output;
                   13477: }
                   13478: 
1.1053    raeburn  13479: sub decompress_uploaded_file {
                   13480:     my ($file,$dir) = @_;
                   13481:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13482:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13483:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13484:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13485:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13486:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13487:     my $decompressed = $env{'cgi.decompressed'};
                   13488:     &Apache::lonnet::delenv('cgi.file');
                   13489:     &Apache::lonnet::delenv('cgi.dir');
                   13490:     &Apache::lonnet::delenv('cgi.decompressed');
                   13491:     return ($decompressed,$result);
                   13492: }
                   13493: 
1.1055    raeburn  13494: sub process_decompression {
                   13495:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13496:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13497:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13498:                &mt('Unexpected file path.').'</p>'."\n";
                   13499:     }
                   13500:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13501:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13502:                &mt('Unexpected course context.').'</p>'."\n";
                   13503:     }
1.1293    raeburn  13504:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13505:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13506:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13507:     }
1.1055    raeburn  13508:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13509:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13510:         $error = &mt('Filename not a supported archive file type.').
                   13511:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13512:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13513:     } else {
                   13514:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13515:         if ($docuhome eq 'no_host') {
                   13516:             $error = &mt('Could not determine home server for course.');
                   13517:         } else {
                   13518:             my @ids=&Apache::lonnet::current_machine_ids();
                   13519:             my $currdir = "$dir_root/$destination";
                   13520:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13521:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13522:                        "$dir_root/$destination";
                   13523:             } else {
                   13524:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13525:                        "$dir_root/$docudom/$docuname/$destination";
                   13526:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13527:                     $error = &mt('Archive file not found.');
                   13528:                 }
                   13529:             }
1.1065    raeburn  13530:             my (@to_overwrite,@to_skip);
                   13531:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13532:                 my $total = $env{'form.archive_overwrite_total'};
                   13533:                 for (my $i=0; $i<$total; $i++) {
                   13534:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13535:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13536:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13537:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13538:                     }
                   13539:                 }
                   13540:             }
                   13541:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13542:             my $numoverwrite = scalar(@to_overwrite);
                   13543:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13544:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13545:             } elsif ($dir eq '') {
1.1055    raeburn  13546:                 $error = &mt('Directory containing archive file unavailable.');
                   13547:             } elsif (!$error) {
1.1065    raeburn  13548:                 my ($decompressed,$display);
1.1292    raeburn  13549:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13550:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13551:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13552:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13553:                         ($decompressed,$display) = 
                   13554:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13555:                         foreach my $item (@to_skip) {
                   13556:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13557:                                 if (-f "$dir/$tempdir/$item") { 
                   13558:                                     unlink("$dir/$tempdir/$item");
                   13559:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13560:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13561:                                 }
                   13562:                             }
                   13563:                         }
                   13564:                         foreach my $item (@to_overwrite) {
                   13565:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13566:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13567:                                     if (-f "$dir/$item") {
                   13568:                                         unlink("$dir/$item");
                   13569:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13570:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13571:                                     }
                   13572:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13573:                                 }
1.1065    raeburn  13574:                             }
                   13575:                         }
1.1292    raeburn  13576:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13577:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13578:                         }
1.1065    raeburn  13579:                     }
                   13580:                 } else {
                   13581:                     ($decompressed,$display) = 
                   13582:                         &decompress_uploaded_file($file,$dir);
                   13583:                 }
1.1055    raeburn  13584:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13585:                     $output = '<p class="LC_info">'.
                   13586:                               &mt('Files extracted successfully from archive.').
                   13587:                               '</p>'."\n";
1.1055    raeburn  13588:                     my ($warning,$result,@contents);
                   13589:                     my ($newdirlistref,$newlisterror) =
                   13590:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13591:                                                  $docuname,1);
                   13592:                     my (%is_dir,%changes,@newitems);
                   13593:                     my $dirptr = 16384;
1.1065    raeburn  13594:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13595:                         foreach my $dir_line (@{$newdirlistref}) {
                   13596:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13597:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13598:                                 push(@newitems,$item);
                   13599:                                 if ($dirptr&$testdir) {
                   13600:                                     $is_dir{$item} = 1;
                   13601:                                 }
                   13602:                                 $changes{$item} = 1;
                   13603:                             }
                   13604:                         }
                   13605:                     }
                   13606:                     if (keys(%changes) > 0) {
                   13607:                         foreach my $item (sort(@newitems)) {
                   13608:                             if ($changes{$item}) {
                   13609:                                 push(@contents,$item);
                   13610:                             }
                   13611:                         }
                   13612:                     }
                   13613:                     if (@contents > 0) {
1.1067    raeburn  13614:                         my $wantform;
                   13615:                         unless ($env{'form.autoextract_camtasia'}) {
                   13616:                             $wantform = 1;
                   13617:                         }
1.1056    raeburn  13618:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13619:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13620:                                                                 $currdir,\%is_dir,
                   13621:                                                                 \%children,\%parent,
1.1056    raeburn  13622:                                                                 \@contents,\%dirorder,
                   13623:                                                                 \%titles,$wantform);
1.1055    raeburn  13624:                         if ($datatable ne '') {
                   13625:                             $output .= &archive_options_form('decompressed',$datatable,
                   13626:                                                              $count,$hiddenelem);
1.1065    raeburn  13627:                             my $startcount = 6;
1.1055    raeburn  13628:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13629:                                                            \%titles,\%children);
1.1055    raeburn  13630:                         }
1.1067    raeburn  13631:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13632:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13633:                             my %displayed;
                   13634:                             my $total = 1;
                   13635:                             $env{'form.archive_directory'} = [];
                   13636:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13637:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13638:                                 $path =~ s{/$}{};
                   13639:                                 my $item;
                   13640:                                 if ($path ne '') {
                   13641:                                     $item = "$path/$titles{$i}";
                   13642:                                 } else {
                   13643:                                     $item = $titles{$i};
                   13644:                                 }
                   13645:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13646:                                 if ($item eq $contents[0]) {
                   13647:                                     push(@{$env{'form.archive_directory'}},$i);
                   13648:                                     $env{'form.archive_'.$i} = 'display';
                   13649:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13650:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13651:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13652:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13653:                                     $env{'form.archive_'.$i} = 'display';
                   13654:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13655:                                     $displayed{'web'} = $i;
                   13656:                                 } else {
1.1164    raeburn  13657:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13658:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13659:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13660:                                         push(@{$env{'form.archive_directory'}},$i);
                   13661:                                     }
                   13662:                                     $env{'form.archive_'.$i} = 'dependency';
                   13663:                                 }
                   13664:                                 $total ++;
                   13665:                             }
                   13666:                             for (my $i=1; $i<$total; $i++) {
                   13667:                                 next if ($i == $displayed{'web'});
                   13668:                                 next if ($i == $displayed{'folder'});
                   13669:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13670:                             }
                   13671:                             $env{'form.phase'} = 'decompress_cleanup';
                   13672:                             $env{'form.archivedelete'} = 1;
                   13673:                             $env{'form.archive_count'} = $total-1;
                   13674:                             $output .=
                   13675:                                 &process_extracted_files('coursedocs',$docudom,
                   13676:                                                          $docuname,$destination,
                   13677:                                                          $dir_root,$hiddenelem);
                   13678:                         }
1.1055    raeburn  13679:                     } else {
                   13680:                         $warning = &mt('No new items extracted from archive file.');
                   13681:                     }
                   13682:                 } else {
                   13683:                     $output = $display;
                   13684:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13685:                 }
                   13686:             }
                   13687:         }
                   13688:     }
                   13689:     if ($error) {
                   13690:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13691:                    $error.'</p>'."\n";
                   13692:     }
                   13693:     if ($warning) {
                   13694:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13695:     }
                   13696:     return $output;
                   13697: }
                   13698: 
                   13699: sub get_extracted {
1.1056    raeburn  13700:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13701:         $titles,$wantform) = @_;
1.1055    raeburn  13702:     my $count = 0;
                   13703:     my $depth = 0;
                   13704:     my $datatable;
1.1056    raeburn  13705:     my @hierarchy;
1.1055    raeburn  13706:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13707:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13708:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13709:     foreach my $item (@{$contents}) {
                   13710:         $count ++;
1.1056    raeburn  13711:         @{$dirorder->{$count}} = @hierarchy;
                   13712:         $titles->{$count} = $item;
1.1055    raeburn  13713:         &archive_hierarchy($depth,$count,$parent,$children);
                   13714:         if ($wantform) {
                   13715:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13716:                                        $currdir,$depth,$count);
                   13717:         }
                   13718:         if ($is_dir->{$item}) {
                   13719:             $depth ++;
1.1056    raeburn  13720:             push(@hierarchy,$count);
                   13721:             $parent->{$depth} = $count;
1.1055    raeburn  13722:             $datatable .=
                   13723:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13724:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13725:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13726:             $depth --;
1.1056    raeburn  13727:             pop(@hierarchy);
1.1055    raeburn  13728:         }
                   13729:     }
                   13730:     return ($count,$datatable);
                   13731: }
                   13732: 
                   13733: sub recurse_extracted_archive {
1.1056    raeburn  13734:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13735:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13736:     my $result='';
1.1056    raeburn  13737:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13738:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13739:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13740:         return $result;
                   13741:     }
                   13742:     my $dirptr = 16384;
                   13743:     my ($newdirlistref,$newlisterror) =
                   13744:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13745:     if (ref($newdirlistref) eq 'ARRAY') {
                   13746:         foreach my $dir_line (@{$newdirlistref}) {
                   13747:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13748:             unless ($item =~ /^\.+$/) {
                   13749:                 $$count ++;
1.1056    raeburn  13750:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13751:                 $titles->{$$count} = $item;
1.1055    raeburn  13752:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13753: 
1.1055    raeburn  13754:                 my $is_dir;
                   13755:                 if ($dirptr&$testdir) {
                   13756:                     $is_dir = 1;
                   13757:                 }
                   13758:                 if ($wantform) {
                   13759:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13760:                 }
                   13761:                 if ($is_dir) {
                   13762:                     $$depth ++;
1.1056    raeburn  13763:                     push(@{$hierarchy},$$count);
                   13764:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13765:                     $result .=
                   13766:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13767:                                                    $docuname,$depth,$count,
1.1056    raeburn  13768:                                                    $hierarchy,$dirorder,$children,
                   13769:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13770:                     $$depth --;
1.1056    raeburn  13771:                     pop(@{$hierarchy});
1.1055    raeburn  13772:                 }
                   13773:             }
                   13774:         }
                   13775:     }
                   13776:     return $result;
                   13777: }
                   13778: 
                   13779: sub archive_hierarchy {
                   13780:     my ($depth,$count,$parent,$children) =@_;
                   13781:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13782:         if (exists($parent->{$depth})) {
                   13783:              $children->{$parent->{$depth}} .= $count.':';
                   13784:         }
                   13785:     }
                   13786:     return;
                   13787: }
                   13788: 
                   13789: sub archive_row {
                   13790:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13791:     my ($name) = ($item =~ m{([^/]+)$});
                   13792:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13793:                                        'display'    => 'Add as file',
1.1055    raeburn  13794:                                        'dependency' => 'Include as dependency',
                   13795:                                        'discard'    => 'Discard',
                   13796:                                       );
                   13797:     if ($is_dir) {
1.1059    raeburn  13798:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13799:     }
1.1056    raeburn  13800:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13801:     my $offset = 0;
1.1055    raeburn  13802:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13803:         $offset ++;
1.1065    raeburn  13804:         if ($action ne 'display') {
                   13805:             $offset ++;
                   13806:         }  
1.1055    raeburn  13807:         $output .= '<td><span class="LC_nobreak">'.
                   13808:                    '<label><input type="radio" name="archive_'.$count.
                   13809:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13810:         my $text = $choices{$action};
                   13811:         if ($is_dir) {
                   13812:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13813:             if ($action eq 'display') {
1.1059    raeburn  13814:                 $text = &mt('Add as folder');
1.1055    raeburn  13815:             }
1.1056    raeburn  13816:         } else {
                   13817:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13818: 
                   13819:         }
                   13820:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13821:         if ($action eq 'dependency') {
                   13822:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13823:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13824:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13825:                        '<option value=""></option>'."\n".
                   13826:                        '</select>'."\n".
                   13827:                        '</div>';
1.1059    raeburn  13828:         } elsif ($action eq 'display') {
                   13829:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13830:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13831:                        '</div>';
1.1055    raeburn  13832:         }
1.1056    raeburn  13833:         $output .= '</td>';
1.1055    raeburn  13834:     }
                   13835:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13836:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13837:     for (my $i=0; $i<$depth; $i++) {
                   13838:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13839:     }
                   13840:     if ($is_dir) {
                   13841:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13842:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13843:     } else {
                   13844:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13845:     }
                   13846:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13847:                &end_data_table_row();
                   13848:     return $output;
                   13849: }
                   13850: 
                   13851: sub archive_options_form {
1.1065    raeburn  13852:     my ($form,$display,$count,$hiddenelem) = @_;
                   13853:     my %lt = &Apache::lonlocal::texthash(
                   13854:                perm => 'Permanently remove archive file?',
                   13855:                hows => 'How should each extracted item be incorporated in the course?',
                   13856:                cont => 'Content actions for all',
                   13857:                addf => 'Add as folder/file',
                   13858:                incd => 'Include as dependency for a displayed file',
                   13859:                disc => 'Discard',
                   13860:                no   => 'No',
                   13861:                yes  => 'Yes',
                   13862:                save => 'Save',
                   13863:     );
                   13864:     my $output = <<"END";
                   13865: <form name="$form" method="post" action="">
                   13866: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13867: <label>
                   13868:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13869: </label>
                   13870: &nbsp;
                   13871: <label>
                   13872:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13873: </span>
                   13874: </p>
                   13875: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13876: <br />$lt{'hows'}
                   13877: <div class="LC_columnSection">
                   13878:   <fieldset>
                   13879:     <legend>$lt{'cont'}</legend>
                   13880:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13881:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13882:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13883:   </fieldset>
                   13884: </div>
                   13885: END
                   13886:     return $output.
1.1055    raeburn  13887:            &start_data_table()."\n".
1.1065    raeburn  13888:            $display."\n".
1.1055    raeburn  13889:            &end_data_table()."\n".
                   13890:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13891:            $hiddenelem.
1.1065    raeburn  13892:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13893:            '</form>';
                   13894: }
                   13895: 
                   13896: sub archive_javascript {
1.1056    raeburn  13897:     my ($startcount,$numitems,$titles,$children) = @_;
                   13898:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13899:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13900:     my $scripttag = <<START;
                   13901: <script type="text/javascript">
                   13902: // <![CDATA[
                   13903: 
                   13904: function checkAll(form,prefix) {
                   13905:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13906:     for (var i=0; i < form.elements.length; i++) {
                   13907:         var id = form.elements[i].id;
                   13908:         if ((id != '') && (id != undefined)) {
                   13909:             if (idstr.test(id)) {
                   13910:                 if (form.elements[i].type == 'radio') {
                   13911:                     form.elements[i].checked = true;
1.1056    raeburn  13912:                     var nostart = i-$startcount;
1.1059    raeburn  13913:                     var offset = nostart%7;
                   13914:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13915:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13916:                 }
                   13917:             }
                   13918:         }
                   13919:     }
                   13920: }
                   13921: 
                   13922: function propagateCheck(form,count) {
                   13923:     if (count > 0) {
1.1059    raeburn  13924:         var startelement = $startcount + ((count-1) * 7);
                   13925:         for (var j=1; j<6; j++) {
                   13926:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13927:                 var item = startelement + j; 
                   13928:                 if (form.elements[item].type == 'radio') {
                   13929:                     if (form.elements[item].checked) {
                   13930:                         containerCheck(form,count,j);
                   13931:                         break;
                   13932:                     }
1.1055    raeburn  13933:                 }
                   13934:             }
                   13935:         }
                   13936:     }
                   13937: }
                   13938: 
                   13939: numitems = $numitems
1.1056    raeburn  13940: var titles = new Array(numitems);
                   13941: var parents = new Array(numitems);
1.1055    raeburn  13942: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13943:     parents[i] = new Array;
1.1055    raeburn  13944: }
1.1059    raeburn  13945: var maintitle = '$maintitle';
1.1055    raeburn  13946: 
                   13947: START
                   13948: 
1.1056    raeburn  13949:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13950:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13951:         for (my $i=0; $i<@contents; $i ++) {
                   13952:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13953:         }
                   13954:     }
                   13955: 
1.1056    raeburn  13956:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13957:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13958:     }
                   13959: 
1.1055    raeburn  13960:     $scripttag .= <<END;
                   13961: 
                   13962: function containerCheck(form,count,offset) {
                   13963:     if (count > 0) {
1.1056    raeburn  13964:         dependencyCheck(form,count,offset);
1.1059    raeburn  13965:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13966:         form.elements[item].checked = true;
                   13967:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13968:             if (parents[count].length > 0) {
                   13969:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13970:                     containerCheck(form,parents[count][j],offset);
                   13971:                 }
                   13972:             }
                   13973:         }
                   13974:     }
                   13975: }
                   13976: 
                   13977: function dependencyCheck(form,count,offset) {
                   13978:     if (count > 0) {
1.1059    raeburn  13979:         var chosen = (offset+$startcount)+7*(count-1);
                   13980:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13981:         var currtype = form.elements[depitem].type;
                   13982:         if (form.elements[chosen].value == 'dependency') {
                   13983:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13984:             form.elements[depitem].options.length = 0;
                   13985:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13986:             for (var i=1; i<=numitems; i++) {
                   13987:                 if (i == count) {
                   13988:                     continue;
                   13989:                 }
1.1059    raeburn  13990:                 var startelement = $startcount + (i-1) * 7;
                   13991:                 for (var j=1; j<6; j++) {
                   13992:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13993:                         var item = startelement + j;
                   13994:                         if (form.elements[item].type == 'radio') {
                   13995:                             if (form.elements[item].checked) {
                   13996:                                 if (form.elements[item].value == 'display') {
                   13997:                                     var n = form.elements[depitem].options.length;
                   13998:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13999:                                 }
                   14000:                             }
                   14001:                         }
                   14002:                     }
                   14003:                 }
                   14004:             }
                   14005:         } else {
                   14006:             document.getElementById('arc_depon_'+count).style.display='none';
                   14007:             form.elements[depitem].options.length = 0;
                   14008:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14009:         }
1.1059    raeburn  14010:         titleCheck(form,count,offset);
1.1056    raeburn  14011:     }
                   14012: }
                   14013: 
                   14014: function propagateSelect(form,count,offset) {
                   14015:     if (count > 0) {
1.1065    raeburn  14016:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14017:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14018:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14019:             if (parents[count].length > 0) {
                   14020:                 for (var j=0; j<parents[count].length; j++) {
                   14021:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14022:                 }
                   14023:             }
                   14024:         }
                   14025:     }
                   14026: }
1.1056    raeburn  14027: 
                   14028: function containerSelect(form,count,offset,picked) {
                   14029:     if (count > 0) {
1.1065    raeburn  14030:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14031:         if (form.elements[item].type == 'radio') {
                   14032:             if (form.elements[item].value == 'dependency') {
                   14033:                 if (form.elements[item+1].type == 'select-one') {
                   14034:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14035:                         if (form.elements[item+1].options[i].value == picked) {
                   14036:                             form.elements[item+1].selectedIndex = i;
                   14037:                             break;
                   14038:                         }
                   14039:                     }
                   14040:                 }
                   14041:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14042:                     if (parents[count].length > 0) {
                   14043:                         for (var j=0; j<parents[count].length; j++) {
                   14044:                             containerSelect(form,parents[count][j],offset,picked);
                   14045:                         }
                   14046:                     }
                   14047:                 }
                   14048:             }
                   14049:         }
                   14050:     }
                   14051: }
                   14052: 
1.1059    raeburn  14053: function titleCheck(form,count,offset) {
                   14054:     if (count > 0) {
                   14055:         var chosen = (offset+$startcount)+7*(count-1);
                   14056:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14057:         var currtype = form.elements[depitem].type;
                   14058:         if (form.elements[chosen].value == 'display') {
                   14059:             document.getElementById('arc_title_'+count).style.display='block';
                   14060:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14061:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14062:             }
                   14063:         } else {
                   14064:             document.getElementById('arc_title_'+count).style.display='none';
                   14065:             if (currtype == 'text') { 
                   14066:                 document.getElementById('archive_title_'+count).value='';
                   14067:             }
                   14068:         }
                   14069:     }
                   14070:     return;
                   14071: }
                   14072: 
1.1055    raeburn  14073: // ]]>
                   14074: </script>
                   14075: END
                   14076:     return $scripttag;
                   14077: }
                   14078: 
                   14079: sub process_extracted_files {
1.1067    raeburn  14080:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14081:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14082:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14083:     my @ids=&Apache::lonnet::current_machine_ids();
                   14084:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14085:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14086:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14087:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14088:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14089:         $pathtocheck = "$dir_root/$destination";
                   14090:         $dir = $dir_root;
                   14091:         $ishome = 1;
                   14092:     } else {
                   14093:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14094:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14095:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14096:     }
                   14097:     my $currdir = "$dir_root/$destination";
                   14098:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14099:     if ($env{'form.folderpath'}) {
                   14100:         my @items = split('&',$env{'form.folderpath'});
                   14101:         $folders{'0'} = $items[-2];
1.1099    raeburn  14102:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14103:             $containers{'0'}='page';
                   14104:         } else {  
                   14105:             $containers{'0'}='sequence';
                   14106:         }
1.1055    raeburn  14107:     }
                   14108:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14109:     if ($numitems) {
                   14110:         for (my $i=1; $i<=$numitems; $i++) {
                   14111:             my $path = $env{'form.archive_content_'.$i};
                   14112:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14113:                 my $item = $1;
                   14114:                 $toplevelitems{$item} = $i;
                   14115:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14116:                     $is_dir{$item} = 1;
                   14117:                 }
                   14118:             }
                   14119:         }
                   14120:     }
1.1067    raeburn  14121:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14122:     if (keys(%toplevelitems) > 0) {
                   14123:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14124:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14125:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14126:     }
1.1066    raeburn  14127:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14128:     if ($numitems) {
                   14129:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14130:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14131:             my $path = $env{'form.archive_content_'.$i};
                   14132:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14133:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14134:                     if ($prefix ne '' && $path ne '') {
                   14135:                         if (-e $prefix.$path) {
1.1066    raeburn  14136:                             if ((@archdirs > 0) && 
                   14137:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14138:                                 $todeletedir{$prefix.$path} = 1;
                   14139:                             } else {
                   14140:                                 $todelete{$prefix.$path} = 1;
                   14141:                             }
1.1055    raeburn  14142:                         }
                   14143:                     }
                   14144:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14145:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14146:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14147:                     $docstitle = $env{'form.archive_title_'.$i};
                   14148:                     if ($docstitle eq '') {
                   14149:                         $docstitle = $title;
                   14150:                     }
1.1055    raeburn  14151:                     $outer = 0;
1.1056    raeburn  14152:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14153:                         if (@{$dirorder{$i}} > 0) {
                   14154:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14155:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14156:                                     $outer = $item;
                   14157:                                     last;
                   14158:                                 }
                   14159:                             }
                   14160:                         }
                   14161:                     }
                   14162:                     my ($errtext,$fatal) = 
                   14163:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14164:                                                '/'.$folders{$outer}.'.'.
                   14165:                                                $containers{$outer});
                   14166:                     next if ($fatal);
                   14167:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14168:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14169:                             $mapinner{$i} = time;
1.1055    raeburn  14170:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14171:                             $containers{$i} = 'sequence';
                   14172:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14173:                                       $folders{$i}.'.'.$containers{$i};
                   14174:                             my $newidx = &LONCAPA::map::getresidx();
                   14175:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14176:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14177:                             push(@LONCAPA::map::order,$newidx);
                   14178:                             my ($outtext,$errtext) =
                   14179:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14180:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14181:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14182:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14183:                             unless ($errtext) {
1.1294    raeburn  14184:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14185:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14186:                                             '</li>'."\n";
1.1067    raeburn  14187:                             }
1.1055    raeburn  14188:                         }
                   14189:                     } else {
                   14190:                         if ($context eq 'coursedocs') {
                   14191:                             my $newidx=&LONCAPA::map::getresidx();
                   14192:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14193:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14194:                                       $title;
1.1294    raeburn  14195:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   14196:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14197:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14198:                                 }
                   14199:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14200:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14201:                                 }
                   14202:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14203:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14204:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14205:                                         unless ($ishome) {
                   14206:                                             my $fetch = "$newdest{$i}/$title";
                   14207:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14208:                                             $prompttofetch{$fetch} = 1;
                   14209:                                         }
1.1292    raeburn  14210:                                     }
1.1067    raeburn  14211:                                 }
1.1294    raeburn  14212:                                 $LONCAPA::map::resources[$newidx]=
                   14213:                                     $docstitle.':'.$url.':false:normal:res';
                   14214:                                 push(@LONCAPA::map::order, $newidx);
                   14215:                                 my ($outtext,$errtext)=
                   14216:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14217:                                                             $docuname.'/'.$folders{$outer}.
                   14218:                                                             '.'.$containers{$outer},1,1);
                   14219:                                 unless ($errtext) {
                   14220:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14221:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14222:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14223:                                                    '</li>'."\n";
                   14224:                                     }
1.1067    raeburn  14225:                                 }
1.1294    raeburn  14226:                             } else {
                   14227:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14228:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14229:                             }
1.1055    raeburn  14230:                         }
                   14231:                     }
1.1086    raeburn  14232:                 }
                   14233:             } else {
1.1294    raeburn  14234:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14235:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14236:             }
                   14237:         }
                   14238:         for (my $i=1; $i<=$numitems; $i++) {
                   14239:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14240:             my $path = $env{'form.archive_content_'.$i};
                   14241:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14242:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14243:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14244:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14245:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14246:                         my ($itemidx,$fullpath,$relpath);
                   14247:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14248:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14249:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14250:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14251:                                     $itemidx = $j;
1.1056    raeburn  14252:                                 }
                   14253:                             }
1.1086    raeburn  14254:                         }
                   14255:                         if ($itemidx eq '') {
                   14256:                             $itemidx =  0;
                   14257:                         } 
                   14258:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14259:                             if ($mapinner{$referrer{$i}}) {
                   14260:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14261:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14262:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14263:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14264:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14265:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14266:                                             if (!-e $fullpath) {
                   14267:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14268:                                             }
                   14269:                                         }
1.1086    raeburn  14270:                                     } else {
                   14271:                                         last;
1.1056    raeburn  14272:                                     }
1.1086    raeburn  14273:                                 }
                   14274:                             }
                   14275:                         } elsif ($newdest{$referrer{$i}}) {
                   14276:                             $fullpath = $newdest{$referrer{$i}};
                   14277:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14278:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14279:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14280:                                     last;
                   14281:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14282:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14283:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14284:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14285:                                         if (!-e $fullpath) {
                   14286:                                             mkdir($fullpath,0755);
1.1056    raeburn  14287:                                         }
                   14288:                                     }
1.1086    raeburn  14289:                                 } else {
                   14290:                                     last;
1.1056    raeburn  14291:                                 }
1.1055    raeburn  14292:                             }
                   14293:                         }
1.1086    raeburn  14294:                         if ($fullpath ne '') {
                   14295:                             if (-e "$prefix$path") {
1.1292    raeburn  14296:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14297:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14298:                                 }
1.1086    raeburn  14299:                             }
                   14300:                             if (-e "$fullpath/$title") {
                   14301:                                 my $showpath;
                   14302:                                 if ($relpath ne '') {
                   14303:                                     $showpath = "$relpath/$title";
                   14304:                                 } else {
                   14305:                                     $showpath = "/$title";
                   14306:                                 } 
1.1294    raeburn  14307:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14308:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14309:                                            '</li>'."\n";
1.1292    raeburn  14310:                                 unless ($ishome) {
                   14311:                                     my $fetch = "$fullpath/$title";
                   14312:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14313:                                     $prompttofetch{$fetch} = 1;
                   14314:                                 }
1.1086    raeburn  14315:                             }
                   14316:                         }
1.1055    raeburn  14317:                     }
1.1086    raeburn  14318:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14319:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14320:                                     &HTML::Entities::encode($path,'<>&"'),
                   14321:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14322:                                 '<br />';
1.1055    raeburn  14323:                 }
                   14324:             } else {
1.1294    raeburn  14325:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14326:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14327:             }
                   14328:         }
                   14329:         if (keys(%todelete)) {
                   14330:             foreach my $key (keys(%todelete)) {
                   14331:                 unlink($key);
1.1066    raeburn  14332:             }
                   14333:         }
                   14334:         if (keys(%todeletedir)) {
                   14335:             foreach my $key (keys(%todeletedir)) {
                   14336:                 rmdir($key);
                   14337:             }
                   14338:         }
                   14339:         foreach my $dir (sort(keys(%is_dir))) {
                   14340:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14341:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14342:             }
                   14343:         }
1.1067    raeburn  14344:         if ($result ne '') {
                   14345:             $output .= '<ul>'."\n".
                   14346:                        $result."\n".
                   14347:                        '</ul>';
                   14348:         }
                   14349:         unless ($ishome) {
                   14350:             my $replicationfail;
                   14351:             foreach my $item (keys(%prompttofetch)) {
                   14352:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14353:                 unless ($fetchresult eq 'ok') {
                   14354:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14355:                 }
                   14356:             }
                   14357:             if ($replicationfail) {
                   14358:                 $output .= '<p class="LC_error">'.
                   14359:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14360:                            $replicationfail.
                   14361:                            '</ul></p>';
                   14362:             }
                   14363:         }
1.1055    raeburn  14364:     } else {
                   14365:         $warning = &mt('No items found in archive.');
                   14366:     }
                   14367:     if ($error) {
                   14368:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14369:                    $error.'</p>'."\n";
                   14370:     }
                   14371:     if ($warning) {
                   14372:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14373:     }
                   14374:     return $output;
                   14375: }
                   14376: 
1.1066    raeburn  14377: sub cleanup_empty_dirs {
                   14378:     my ($path) = @_;
                   14379:     if (($path ne '') && (-d $path)) {
                   14380:         if (opendir(my $dirh,$path)) {
                   14381:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14382:             my $numitems = 0;
                   14383:             foreach my $item (@dircontents) {
                   14384:                 if (-d "$path/$item") {
1.1111    raeburn  14385:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14386:                     if (-e "$path/$item") {
                   14387:                         $numitems ++;
                   14388:                     }
                   14389:                 } else {
                   14390:                     $numitems ++;
                   14391:                 }
                   14392:             }
                   14393:             if ($numitems == 0) {
                   14394:                 rmdir($path);
                   14395:             }
                   14396:             closedir($dirh);
                   14397:         }
                   14398:     }
                   14399:     return;
                   14400: }
                   14401: 
1.41      ng       14402: =pod
1.45      matthew  14403: 
1.1162    raeburn  14404: =item * &get_folder_hierarchy()
1.1068    raeburn  14405: 
                   14406: Provides hierarchy of names of folders/sub-folders containing the current
                   14407: item,
                   14408: 
                   14409: Inputs: 3
                   14410:      - $navmap - navmaps object
                   14411: 
                   14412:      - $map - url for map (either the trigger itself, or map containing
                   14413:                            the resource, which is the trigger).
                   14414: 
                   14415:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14416: 
                   14417: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14418: 
                   14419: =cut
                   14420: 
                   14421: sub get_folder_hierarchy {
                   14422:     my ($navmap,$map,$showitem) = @_;
                   14423:     my @pathitems;
                   14424:     if (ref($navmap)) {
                   14425:         my $mapres = $navmap->getResourceByUrl($map);
                   14426:         if (ref($mapres)) {
                   14427:             my $pcslist = $mapres->map_hierarchy();
                   14428:             if ($pcslist ne '') {
                   14429:                 my @pcs = split(/,/,$pcslist);
                   14430:                 foreach my $pc (@pcs) {
                   14431:                     if ($pc == 1) {
1.1129    raeburn  14432:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14433:                     } else {
                   14434:                         my $res = $navmap->getByMapPc($pc);
                   14435:                         if (ref($res)) {
                   14436:                             my $title = $res->compTitle();
                   14437:                             $title =~ s/\W+/_/g;
                   14438:                             if ($title ne '') {
                   14439:                                 push(@pathitems,$title);
                   14440:                             }
                   14441:                         }
                   14442:                     }
                   14443:                 }
                   14444:             }
1.1071    raeburn  14445:             if ($showitem) {
                   14446:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14447:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14448:                 } else {
                   14449:                     my $maptitle = $mapres->compTitle();
                   14450:                     $maptitle =~ s/\W+/_/g;
                   14451:                     if ($maptitle ne '') {
                   14452:                         push(@pathitems,$maptitle);
                   14453:                     }
1.1068    raeburn  14454:                 }
                   14455:             }
                   14456:         }
                   14457:     }
                   14458:     return @pathitems;
                   14459: }
                   14460: 
                   14461: =pod
                   14462: 
1.1015    raeburn  14463: =item * &get_turnedin_filepath()
                   14464: 
                   14465: Determines path in a user's portfolio file for storage of files uploaded
                   14466: to a specific essayresponse or dropbox item.
                   14467: 
                   14468: Inputs: 3 required + 1 optional.
                   14469: $symb is symb for resource, $uname and $udom are for current user (required).
                   14470: $caller is optional (can be "submission", if routine is called when storing
                   14471: an upoaded file when "Submit Answer" button was pressed).
                   14472: 
                   14473: Returns array containing $path and $multiresp. 
                   14474: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14475: than one file upload item.  Callers of routine should append partid as a 
                   14476: subdirectory to $path in cases where $multiresp is 1.
                   14477: 
                   14478: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14479: 
                   14480: =cut
                   14481: 
                   14482: sub get_turnedin_filepath {
                   14483:     my ($symb,$uname,$udom,$caller) = @_;
                   14484:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14485:     my $turnindir;
                   14486:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14487:     $turnindir = $userhash{'turnindir'};
                   14488:     my ($path,$multiresp);
                   14489:     if ($turnindir eq '') {
                   14490:         if ($caller eq 'submission') {
                   14491:             $turnindir = &mt('turned in');
                   14492:             $turnindir =~ s/\W+/_/g;
                   14493:             my %newhash = (
                   14494:                             'turnindir' => $turnindir,
                   14495:                           );
                   14496:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14497:         }
                   14498:     }
                   14499:     if ($turnindir ne '') {
                   14500:         $path = '/'.$turnindir.'/';
                   14501:         my ($multipart,$turnin,@pathitems);
                   14502:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14503:         if (defined($navmap)) {
                   14504:             my $mapres = $navmap->getResourceByUrl($map);
                   14505:             if (ref($mapres)) {
                   14506:                 my $pcslist = $mapres->map_hierarchy();
                   14507:                 if ($pcslist ne '') {
                   14508:                     foreach my $pc (split(/,/,$pcslist)) {
                   14509:                         my $res = $navmap->getByMapPc($pc);
                   14510:                         if (ref($res)) {
                   14511:                             my $title = $res->compTitle();
                   14512:                             $title =~ s/\W+/_/g;
                   14513:                             if ($title ne '') {
1.1149    raeburn  14514:                                 if (($pc > 1) && (length($title) > 12)) {
                   14515:                                     $title = substr($title,0,12);
                   14516:                                 }
1.1015    raeburn  14517:                                 push(@pathitems,$title);
                   14518:                             }
                   14519:                         }
                   14520:                     }
                   14521:                 }
                   14522:                 my $maptitle = $mapres->compTitle();
                   14523:                 $maptitle =~ s/\W+/_/g;
                   14524:                 if ($maptitle ne '') {
1.1149    raeburn  14525:                     if (length($maptitle) > 12) {
                   14526:                         $maptitle = substr($maptitle,0,12);
                   14527:                     }
1.1015    raeburn  14528:                     push(@pathitems,$maptitle);
                   14529:                 }
                   14530:                 unless ($env{'request.state'} eq 'construct') {
                   14531:                     my $res = $navmap->getBySymb($symb);
                   14532:                     if (ref($res)) {
                   14533:                         my $partlist = $res->parts();
                   14534:                         my $totaluploads = 0;
                   14535:                         if (ref($partlist) eq 'ARRAY') {
                   14536:                             foreach my $part (@{$partlist}) {
                   14537:                                 my @types = $res->responseType($part);
                   14538:                                 my @ids = $res->responseIds($part);
                   14539:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14540:                                     if ($types[$i] eq 'essay') {
                   14541:                                         my $partid = $part.'_'.$ids[$i];
                   14542:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14543:                                             $totaluploads ++;
                   14544:                                         }
                   14545:                                     }
                   14546:                                 }
                   14547:                             }
                   14548:                             if ($totaluploads > 1) {
                   14549:                                 $multiresp = 1;
                   14550:                             }
                   14551:                         }
                   14552:                     }
                   14553:                 }
                   14554:             } else {
                   14555:                 return;
                   14556:             }
                   14557:         } else {
                   14558:             return;
                   14559:         }
                   14560:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14561:         $restitle =~ s/\W+/_/g;
                   14562:         if ($restitle eq '') {
                   14563:             $restitle = ($resurl =~ m{/[^/]+$});
                   14564:             if ($restitle eq '') {
                   14565:                 $restitle = time;
                   14566:             }
                   14567:         }
1.1149    raeburn  14568:         if (length($restitle) > 12) {
                   14569:             $restitle = substr($restitle,0,12);
                   14570:         }
1.1015    raeburn  14571:         push(@pathitems,$restitle);
                   14572:         $path .= join('/',@pathitems);
                   14573:     }
                   14574:     return ($path,$multiresp);
                   14575: }
                   14576: 
                   14577: =pod
                   14578: 
1.464     albertel 14579: =back
1.41      ng       14580: 
1.112     bowersj2 14581: =head1 CSV Upload/Handling functions
1.38      albertel 14582: 
1.41      ng       14583: =over 4
                   14584: 
1.648     raeburn  14585: =item * &upfile_store($r)
1.41      ng       14586: 
                   14587: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14588: needs $env{'form.upfile'}
1.41      ng       14589: returns $datatoken to be put into hidden field
                   14590: 
                   14591: =cut
1.31      albertel 14592: 
                   14593: sub upfile_store {
                   14594:     my $r=shift;
1.258     albertel 14595:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14596:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14597:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14598:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14599: 
1.1299    raeburn  14600:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14601:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14602:                                      time.'_'.$$);
                   14603:     return if ($datatoken eq '');
                   14604: 
1.31      albertel 14605:     {
1.158     raeburn  14606:         my $datafile = $r->dir_config('lonDaemons').
                   14607:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14608:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14609:             print $fh $env{'form.upfile'};
1.158     raeburn  14610:             close($fh);
                   14611:         }
1.31      albertel 14612:     }
                   14613:     return $datatoken;
                   14614: }
                   14615: 
1.56      matthew  14616: =pod
                   14617: 
1.1290    raeburn  14618: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14619: 
                   14620: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14621: $datatoken is the name to assign to the temporary file.
1.258     albertel 14622: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14623: 
                   14624: =cut
1.31      albertel 14625: 
                   14626: sub load_tmp_file {
1.1290    raeburn  14627:     my ($r,$datatoken) = @_;
                   14628:     return if ($datatoken eq '');
1.31      albertel 14629:     my @studentdata=();
                   14630:     {
1.158     raeburn  14631:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14632:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14633:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14634:             @studentdata=<$fh>;
                   14635:             close($fh);
                   14636:         }
1.31      albertel 14637:     }
1.258     albertel 14638:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14639: }
                   14640: 
1.1290    raeburn  14641: sub valid_datatoken {
                   14642:     my ($datatoken) = @_;
1.1325    raeburn  14643:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14644:         return $datatoken;
                   14645:     }
                   14646:     return;
                   14647: }
                   14648: 
1.56      matthew  14649: =pod
                   14650: 
1.648     raeburn  14651: =item * &upfile_record_sep()
1.41      ng       14652: 
                   14653: Separate uploaded file into records
                   14654: returns array of records,
1.258     albertel 14655: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14656: 
                   14657: =cut
1.31      albertel 14658: 
                   14659: sub upfile_record_sep {
1.258     albertel 14660:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14661:     } else {
1.248     albertel 14662: 	my @records;
1.258     albertel 14663: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14664: 	    if ($line=~/^\s*$/) { next; }
                   14665: 	    push(@records,$line);
                   14666: 	}
                   14667: 	return @records;
1.31      albertel 14668:     }
                   14669: }
                   14670: 
1.56      matthew  14671: =pod
                   14672: 
1.648     raeburn  14673: =item * &record_sep($record)
1.41      ng       14674: 
1.258     albertel 14675: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14676: 
                   14677: =cut
                   14678: 
1.263     www      14679: sub takeleft {
                   14680:     my $index=shift;
                   14681:     return substr('0000'.$index,-4,4);
                   14682: }
                   14683: 
1.31      albertel 14684: sub record_sep {
                   14685:     my $record=shift;
                   14686:     my %components=();
1.258     albertel 14687:     if ($env{'form.upfiletype'} eq 'xml') {
                   14688:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14689:         my $i=0;
1.356     albertel 14690:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14691:             $field=~s/^(\"|\')//;
                   14692:             $field=~s/(\"|\')$//;
1.263     www      14693:             $components{&takeleft($i)}=$field;
1.31      albertel 14694:             $i++;
                   14695:         }
1.258     albertel 14696:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14697:         my $i=0;
1.356     albertel 14698:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14699:             $field=~s/^(\"|\')//;
                   14700:             $field=~s/(\"|\')$//;
1.263     www      14701:             $components{&takeleft($i)}=$field;
1.31      albertel 14702:             $i++;
                   14703:         }
                   14704:     } else {
1.561     www      14705:         my $separator=',';
1.480     banghart 14706:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14707:             $separator=';';
1.480     banghart 14708:         }
1.31      albertel 14709:         my $i=0;
1.561     www      14710: # the character we are looking for to indicate the end of a quote or a record 
                   14711:         my $looking_for=$separator;
                   14712: # do not add the characters to the fields
                   14713:         my $ignore=0;
                   14714: # we just encountered a separator (or the beginning of the record)
                   14715:         my $just_found_separator=1;
                   14716: # store the field we are working on here
                   14717:         my $field='';
                   14718: # work our way through all characters in record
                   14719:         foreach my $character ($record=~/(.)/g) {
                   14720:             if ($character eq $looking_for) {
                   14721:                if ($character ne $separator) {
                   14722: # Found the end of a quote, again looking for separator
                   14723:                   $looking_for=$separator;
                   14724:                   $ignore=1;
                   14725:                } else {
                   14726: # Found a separator, store away what we got
                   14727:                   $components{&takeleft($i)}=$field;
                   14728: 	          $i++;
                   14729:                   $just_found_separator=1;
                   14730:                   $ignore=0;
                   14731:                   $field='';
                   14732:                }
                   14733:                next;
                   14734:             }
                   14735: # single or double quotation marks after a separator indicate beginning of a quote
                   14736: # we are now looking for the end of the quote and need to ignore separators
                   14737:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14738:                $looking_for=$character;
                   14739:                next;
                   14740:             }
                   14741: # ignore would be true after we reached the end of a quote
                   14742:             if ($ignore) { next; }
                   14743:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14744:             $field.=$character;
                   14745:             $just_found_separator=0; 
1.31      albertel 14746:         }
1.561     www      14747: # catch the very last entry, since we never encountered the separator
                   14748:         $components{&takeleft($i)}=$field;
1.31      albertel 14749:     }
                   14750:     return %components;
                   14751: }
                   14752: 
1.144     matthew  14753: ######################################################
                   14754: ######################################################
                   14755: 
1.56      matthew  14756: =pod
                   14757: 
1.648     raeburn  14758: =item * &upfile_select_html()
1.41      ng       14759: 
1.144     matthew  14760: Return HTML code to select a file from the users machine and specify 
                   14761: the file type.
1.41      ng       14762: 
                   14763: =cut
                   14764: 
1.144     matthew  14765: ######################################################
                   14766: ######################################################
1.31      albertel 14767: sub upfile_select_html {
1.144     matthew  14768:     my %Types = (
                   14769:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14770:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14771:                  space => &mt('Space separated'),
                   14772:                  tab   => &mt('Tabulator separated'),
                   14773: #                 xml   => &mt('HTML/XML'),
                   14774:                  );
                   14775:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14776:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14777:     foreach my $type (sort(keys(%Types))) {
                   14778:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14779:     }
                   14780:     $Str .= "</select>\n";
                   14781:     return $Str;
1.31      albertel 14782: }
                   14783: 
1.301     albertel 14784: sub get_samples {
                   14785:     my ($records,$toget) = @_;
                   14786:     my @samples=({});
                   14787:     my $got=0;
                   14788:     foreach my $rec (@$records) {
                   14789: 	my %temp = &record_sep($rec);
                   14790: 	if (! grep(/\S/, values(%temp))) { next; }
                   14791: 	if (%temp) {
                   14792: 	    $samples[$got]=\%temp;
                   14793: 	    $got++;
                   14794: 	    if ($got == $toget) { last; }
                   14795: 	}
                   14796:     }
                   14797:     return \@samples;
                   14798: }
                   14799: 
1.144     matthew  14800: ######################################################
                   14801: ######################################################
                   14802: 
1.56      matthew  14803: =pod
                   14804: 
1.648     raeburn  14805: =item * &csv_print_samples($r,$records)
1.41      ng       14806: 
                   14807: Prints a table of sample values from each column uploaded $r is an
                   14808: Apache Request ref, $records is an arrayref from
                   14809: &Apache::loncommon::upfile_record_sep
                   14810: 
                   14811: =cut
                   14812: 
1.144     matthew  14813: ######################################################
                   14814: ######################################################
1.31      albertel 14815: sub csv_print_samples {
                   14816:     my ($r,$records) = @_;
1.662     bisitz   14817:     my $samples = &get_samples($records,5);
1.301     albertel 14818: 
1.594     raeburn  14819:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14820:               &start_data_table_header_row());
1.356     albertel 14821:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14822:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14823:     $r->print(&end_data_table_header_row());
1.301     albertel 14824:     foreach my $hash (@$samples) {
1.594     raeburn  14825: 	$r->print(&start_data_table_row());
1.356     albertel 14826: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14827: 	    $r->print('<td>');
1.356     albertel 14828: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14829: 	    $r->print('</td>');
                   14830: 	}
1.594     raeburn  14831: 	$r->print(&end_data_table_row());
1.31      albertel 14832:     }
1.594     raeburn  14833:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14834: }
                   14835: 
1.144     matthew  14836: ######################################################
                   14837: ######################################################
                   14838: 
1.56      matthew  14839: =pod
                   14840: 
1.648     raeburn  14841: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14842: 
                   14843: Prints a table to create associations between values and table columns.
1.144     matthew  14844: 
1.41      ng       14845: $r is an Apache Request ref,
                   14846: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14847: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14848: 
                   14849: =cut
                   14850: 
1.144     matthew  14851: ######################################################
                   14852: ######################################################
1.31      albertel 14853: sub csv_print_select_table {
                   14854:     my ($r,$records,$d) = @_;
1.301     albertel 14855:     my $i=0;
                   14856:     my $samples = &get_samples($records,1);
1.144     matthew  14857:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14858: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14859:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14860:               '<th>'.&mt('Column').'</th>'.
                   14861:               &end_data_table_header_row()."\n");
1.356     albertel 14862:     foreach my $array_ref (@$d) {
                   14863: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14864: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14865: 
1.875     bisitz   14866: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14867: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14868: 	$r->print('<option value="none"></option>');
1.356     albertel 14869: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14870: 	    $r->print('<option value="'.$sample.'"'.
                   14871:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14872:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14873: 	}
1.594     raeburn  14874: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14875: 	$i++;
                   14876:     }
1.594     raeburn  14877:     $r->print(&end_data_table());
1.31      albertel 14878:     $i--;
                   14879:     return $i;
                   14880: }
1.56      matthew  14881: 
1.144     matthew  14882: ######################################################
                   14883: ######################################################
                   14884: 
1.56      matthew  14885: =pod
1.31      albertel 14886: 
1.648     raeburn  14887: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14888: 
                   14889: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14890: 
                   14891: $r is an Apache Request ref,
                   14892: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14893: $d is an array of 2 element arrays (internal name, displayed name)
                   14894: 
                   14895: =cut
                   14896: 
1.144     matthew  14897: ######################################################
                   14898: ######################################################
1.31      albertel 14899: sub csv_samples_select_table {
                   14900:     my ($r,$records,$d) = @_;
                   14901:     my $i=0;
1.144     matthew  14902:     #
1.662     bisitz   14903:     my $max_samples = 5;
                   14904:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14905:     $r->print(&start_data_table().
                   14906:               &start_data_table_header_row().'<th>'.
                   14907:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14908:               &end_data_table_header_row());
1.301     albertel 14909: 
                   14910:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14911: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14912: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14913: 	foreach my $option (@$d) {
                   14914: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14915: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14916:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14917:                       $display.'</option>');
1.31      albertel 14918: 	}
                   14919: 	$r->print('</select></td><td>');
1.662     bisitz   14920: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14921: 	    if (defined($samples->[$line]{$key})) { 
                   14922: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14923: 	    }
                   14924: 	}
1.594     raeburn  14925: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14926: 	$i++;
                   14927:     }
1.594     raeburn  14928:     $r->print(&end_data_table());
1.31      albertel 14929:     $i--;
                   14930:     return($i);
1.115     matthew  14931: }
                   14932: 
1.144     matthew  14933: ######################################################
                   14934: ######################################################
                   14935: 
1.115     matthew  14936: =pod
                   14937: 
1.648     raeburn  14938: =item * &clean_excel_name($name)
1.115     matthew  14939: 
                   14940: Returns a replacement for $name which does not contain any illegal characters.
                   14941: 
                   14942: =cut
                   14943: 
1.144     matthew  14944: ######################################################
                   14945: ######################################################
1.115     matthew  14946: sub clean_excel_name {
                   14947:     my ($name) = @_;
                   14948:     $name =~ s/[:\*\?\/\\]//g;
                   14949:     if (length($name) > 31) {
                   14950:         $name = substr($name,0,31);
                   14951:     }
                   14952:     return $name;
1.25      albertel 14953: }
1.84      albertel 14954: 
1.85      albertel 14955: =pod
                   14956: 
1.648     raeburn  14957: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14958: 
                   14959: Returns either 1 or undef
                   14960: 
                   14961: 1 if the part is to be hidden, undef if it is to be shown
                   14962: 
                   14963: Arguments are:
                   14964: 
                   14965: $id the id of the part to be checked
                   14966: $symb, optional the symb of the resource to check
                   14967: $udom, optional the domain of the user to check for
                   14968: $uname, optional the username of the user to check for
                   14969: 
                   14970: =cut
1.84      albertel 14971: 
                   14972: sub check_if_partid_hidden {
                   14973:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14974:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14975: 					 $symb,$udom,$uname);
1.141     albertel 14976:     my $truth=1;
                   14977:     #if the string starts with !, then the list is the list to show not hide
                   14978:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14979:     my @hiddenlist=split(/,/,$hiddenparts);
                   14980:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14981: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14982:     }
1.141     albertel 14983:     return !$truth;
1.84      albertel 14984: }
1.127     matthew  14985: 
1.138     matthew  14986: 
                   14987: ############################################################
                   14988: ############################################################
                   14989: 
                   14990: =pod
                   14991: 
1.157     matthew  14992: =back 
                   14993: 
1.138     matthew  14994: =head1 cgi-bin script and graphing routines
                   14995: 
1.157     matthew  14996: =over 4
                   14997: 
1.648     raeburn  14998: =item * &get_cgi_id()
1.138     matthew  14999: 
                   15000: Inputs: none
                   15001: 
                   15002: Returns an id which can be used to pass environment variables
                   15003: to various cgi-bin scripts.  These environment variables will
                   15004: be removed from the users environment after a given time by
                   15005: the routine &Apache::lonnet::transfer_profile_to_env.
                   15006: 
                   15007: =cut
                   15008: 
                   15009: ############################################################
                   15010: ############################################################
1.152     albertel 15011: my $uniq=0;
1.136     matthew  15012: sub get_cgi_id {
1.154     albertel 15013:     $uniq=($uniq+1)%100000;
1.280     albertel 15014:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15015: }
                   15016: 
1.127     matthew  15017: ############################################################
                   15018: ############################################################
                   15019: 
                   15020: =pod
                   15021: 
1.648     raeburn  15022: =item * &DrawBarGraph()
1.127     matthew  15023: 
1.138     matthew  15024: Facilitates the plotting of data in a (stacked) bar graph.
                   15025: Puts plot definition data into the users environment in order for 
                   15026: graph.png to plot it.  Returns an <img> tag for the plot.
                   15027: The bars on the plot are labeled '1','2',...,'n'.
                   15028: 
                   15029: Inputs:
                   15030: 
                   15031: =over 4
                   15032: 
                   15033: =item $Title: string, the title of the plot
                   15034: 
                   15035: =item $xlabel: string, text describing the X-axis of the plot
                   15036: 
                   15037: =item $ylabel: string, text describing the Y-axis of the plot
                   15038: 
                   15039: =item $Max: scalar, the maximum Y value to use in the plot
                   15040: If $Max is < any data point, the graph will not be rendered.
                   15041: 
1.140     matthew  15042: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15043: they are plotted.  If undefined, default values will be used.
                   15044: 
1.178     matthew  15045: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15046: 
1.138     matthew  15047: =item @Values: An array of array references.  Each array reference holds data
                   15048: to be plotted in a stacked bar chart.
                   15049: 
1.239     matthew  15050: =item If the final element of @Values is a hash reference the key/value
                   15051: pairs will be added to the graph definition.
                   15052: 
1.138     matthew  15053: =back
                   15054: 
                   15055: Returns:
                   15056: 
                   15057: An <img> tag which references graph.png and the appropriate identifying
                   15058: information for the plot.
                   15059: 
1.127     matthew  15060: =cut
                   15061: 
                   15062: ############################################################
                   15063: ############################################################
1.134     matthew  15064: sub DrawBarGraph {
1.178     matthew  15065:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15066:     #
                   15067:     if (! defined($colors)) {
                   15068:         $colors = ['#33ff00', 
                   15069:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15070:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15071:                   ]; 
                   15072:     }
1.228     matthew  15073:     my $extra_settings = {};
                   15074:     if (ref($Values[-1]) eq 'HASH') {
                   15075:         $extra_settings = pop(@Values);
                   15076:     }
1.127     matthew  15077:     #
1.136     matthew  15078:     my $identifier = &get_cgi_id();
                   15079:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15080:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15081:         return '';
                   15082:     }
1.225     matthew  15083:     #
                   15084:     my @Labels;
                   15085:     if (defined($labels)) {
                   15086:         @Labels = @$labels;
                   15087:     } else {
                   15088:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15089:             push(@Labels,$i+1);
1.225     matthew  15090:         }
                   15091:     }
                   15092:     #
1.129     matthew  15093:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15094:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15095:     my %ValuesHash;
                   15096:     my $NumSets=1;
                   15097:     foreach my $array (@Values) {
                   15098:         next if (! ref($array));
1.136     matthew  15099:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15100:             join(',',@$array);
1.129     matthew  15101:     }
1.127     matthew  15102:     #
1.136     matthew  15103:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15104:     if ($NumBars < 3) {
                   15105:         $width = 120+$NumBars*32;
1.220     matthew  15106:         $xskip = 1;
1.225     matthew  15107:         $bar_width = 30;
                   15108:     } elsif ($NumBars < 5) {
                   15109:         $width = 120+$NumBars*20;
                   15110:         $xskip = 1;
                   15111:         $bar_width = 20;
1.220     matthew  15112:     } elsif ($NumBars < 10) {
1.136     matthew  15113:         $width = 120+$NumBars*15;
                   15114:         $xskip = 1;
                   15115:         $bar_width = 15;
                   15116:     } elsif ($NumBars <= 25) {
                   15117:         $width = 120+$NumBars*11;
                   15118:         $xskip = 5;
                   15119:         $bar_width = 8;
                   15120:     } elsif ($NumBars <= 50) {
                   15121:         $width = 120+$NumBars*8;
                   15122:         $xskip = 5;
                   15123:         $bar_width = 4;
                   15124:     } else {
                   15125:         $width = 120+$NumBars*8;
                   15126:         $xskip = 5;
                   15127:         $bar_width = 4;
                   15128:     }
                   15129:     #
1.137     matthew  15130:     $Max = 1 if ($Max < 1);
                   15131:     if ( int($Max) < $Max ) {
                   15132:         $Max++;
                   15133:         $Max = int($Max);
                   15134:     }
1.127     matthew  15135:     $Title  = '' if (! defined($Title));
                   15136:     $xlabel = '' if (! defined($xlabel));
                   15137:     $ylabel = '' if (! defined($ylabel));
1.369     www      15138:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15139:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15140:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15141:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15142:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15143:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15144:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15145:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15146:     $ValuesHash{$id.'.height'}   = $height;
                   15147:     $ValuesHash{$id.'.width'}    = $width;
                   15148:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15149:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15150:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15151:     #
1.228     matthew  15152:     # Deal with other parameters
                   15153:     while (my ($key,$value) = each(%$extra_settings)) {
                   15154:         $ValuesHash{$id.'.'.$key} = $value;
                   15155:     }
                   15156:     #
1.646     raeburn  15157:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15158:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15159: }
                   15160: 
                   15161: ############################################################
                   15162: ############################################################
                   15163: 
                   15164: =pod
                   15165: 
1.648     raeburn  15166: =item * &DrawXYGraph()
1.137     matthew  15167: 
1.138     matthew  15168: Facilitates the plotting of data in an XY graph.
                   15169: Puts plot definition data into the users environment in order for 
                   15170: graph.png to plot it.  Returns an <img> tag for the plot.
                   15171: 
                   15172: Inputs:
                   15173: 
                   15174: =over 4
                   15175: 
                   15176: =item $Title: string, the title of the plot
                   15177: 
                   15178: =item $xlabel: string, text describing the X-axis of the plot
                   15179: 
                   15180: =item $ylabel: string, text describing the Y-axis of the plot
                   15181: 
                   15182: =item $Max: scalar, the maximum Y value to use in the plot
                   15183: If $Max is < any data point, the graph will not be rendered.
                   15184: 
                   15185: =item $colors: Array ref containing the hex color codes for the data to be 
                   15186: plotted in.  If undefined, default values will be used.
                   15187: 
                   15188: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15189: 
                   15190: =item $Ydata: Array ref containing Array refs.  
1.185     www      15191: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15192: 
                   15193: =item %Values: hash indicating or overriding any default values which are 
                   15194: passed to graph.png.  
                   15195: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15196: 
                   15197: =back
                   15198: 
                   15199: Returns:
                   15200: 
                   15201: An <img> tag which references graph.png and the appropriate identifying
                   15202: information for the plot.
                   15203: 
1.137     matthew  15204: =cut
                   15205: 
                   15206: ############################################################
                   15207: ############################################################
                   15208: sub DrawXYGraph {
                   15209:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15210:     #
                   15211:     # Create the identifier for the graph
                   15212:     my $identifier = &get_cgi_id();
                   15213:     my $id = 'cgi.'.$identifier;
                   15214:     #
                   15215:     $Title  = '' if (! defined($Title));
                   15216:     $xlabel = '' if (! defined($xlabel));
                   15217:     $ylabel = '' if (! defined($ylabel));
                   15218:     my %ValuesHash = 
                   15219:         (
1.369     www      15220:          $id.'.title'  => &escape($Title),
                   15221:          $id.'.xlabel' => &escape($xlabel),
                   15222:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15223:          $id.'.y_max_value'=> $Max,
                   15224:          $id.'.labels'     => join(',',@$Xlabels),
                   15225:          $id.'.PlotType'   => 'XY',
                   15226:          );
                   15227:     #
                   15228:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15229:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15230:     }
                   15231:     #
                   15232:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15233:         return '';
                   15234:     }
                   15235:     my $NumSets=1;
1.138     matthew  15236:     foreach my $array (@{$Ydata}){
1.137     matthew  15237:         next if (! ref($array));
                   15238:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15239:     }
1.138     matthew  15240:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15241:     #
                   15242:     # Deal with other parameters
                   15243:     while (my ($key,$value) = each(%Values)) {
                   15244:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15245:     }
                   15246:     #
1.646     raeburn  15247:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15248:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15249: }
                   15250: 
                   15251: ############################################################
                   15252: ############################################################
                   15253: 
                   15254: =pod
                   15255: 
1.648     raeburn  15256: =item * &DrawXYYGraph()
1.138     matthew  15257: 
                   15258: Facilitates the plotting of data in an XY graph with two Y axes.
                   15259: Puts plot definition data into the users environment in order for 
                   15260: graph.png to plot it.  Returns an <img> tag for the plot.
                   15261: 
                   15262: Inputs:
                   15263: 
                   15264: =over 4
                   15265: 
                   15266: =item $Title: string, the title of the plot
                   15267: 
                   15268: =item $xlabel: string, text describing the X-axis of the plot
                   15269: 
                   15270: =item $ylabel: string, text describing the Y-axis of the plot
                   15271: 
                   15272: =item $colors: Array ref containing the hex color codes for the data to be 
                   15273: plotted in.  If undefined, default values will be used.
                   15274: 
                   15275: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15276: 
                   15277: =item $Ydata1: The first data set
                   15278: 
                   15279: =item $Min1: The minimum value of the left Y-axis
                   15280: 
                   15281: =item $Max1: The maximum value of the left Y-axis
                   15282: 
                   15283: =item $Ydata2: The second data set
                   15284: 
                   15285: =item $Min2: The minimum value of the right Y-axis
                   15286: 
                   15287: =item $Max2: The maximum value of the left Y-axis
                   15288: 
                   15289: =item %Values: hash indicating or overriding any default values which are 
                   15290: passed to graph.png.  
                   15291: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15292: 
                   15293: =back
                   15294: 
                   15295: Returns:
                   15296: 
                   15297: An <img> tag which references graph.png and the appropriate identifying
                   15298: information for the plot.
1.136     matthew  15299: 
                   15300: =cut
                   15301: 
                   15302: ############################################################
                   15303: ############################################################
1.137     matthew  15304: sub DrawXYYGraph {
                   15305:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15306:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15307:     #
                   15308:     # Create the identifier for the graph
                   15309:     my $identifier = &get_cgi_id();
                   15310:     my $id = 'cgi.'.$identifier;
                   15311:     #
                   15312:     $Title  = '' if (! defined($Title));
                   15313:     $xlabel = '' if (! defined($xlabel));
                   15314:     $ylabel = '' if (! defined($ylabel));
                   15315:     my %ValuesHash = 
                   15316:         (
1.369     www      15317:          $id.'.title'  => &escape($Title),
                   15318:          $id.'.xlabel' => &escape($xlabel),
                   15319:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15320:          $id.'.labels' => join(',',@$Xlabels),
                   15321:          $id.'.PlotType' => 'XY',
                   15322:          $id.'.NumSets' => 2,
1.137     matthew  15323:          $id.'.two_axes' => 1,
                   15324:          $id.'.y1_max_value' => $Max1,
                   15325:          $id.'.y1_min_value' => $Min1,
                   15326:          $id.'.y2_max_value' => $Max2,
                   15327:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15328:          );
                   15329:     #
1.137     matthew  15330:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15331:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15332:     }
                   15333:     #
                   15334:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15335:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15336:         return '';
                   15337:     }
                   15338:     my $NumSets=1;
1.137     matthew  15339:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15340:         next if (! ref($array));
                   15341:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15342:     }
                   15343:     #
                   15344:     # Deal with other parameters
                   15345:     while (my ($key,$value) = each(%Values)) {
                   15346:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15347:     }
                   15348:     #
1.646     raeburn  15349:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15350:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15351: }
                   15352: 
                   15353: ############################################################
                   15354: ############################################################
                   15355: 
                   15356: =pod
                   15357: 
1.157     matthew  15358: =back 
                   15359: 
1.139     matthew  15360: =head1 Statistics helper routines?  
                   15361: 
                   15362: Bad place for them but what the hell.
                   15363: 
1.157     matthew  15364: =over 4
                   15365: 
1.648     raeburn  15366: =item * &chartlink()
1.139     matthew  15367: 
                   15368: Returns a link to the chart for a specific student.  
                   15369: 
                   15370: Inputs:
                   15371: 
                   15372: =over 4
                   15373: 
                   15374: =item $linktext: The text of the link
                   15375: 
                   15376: =item $sname: The students username
                   15377: 
                   15378: =item $sdomain: The students domain
                   15379: 
                   15380: =back
                   15381: 
1.157     matthew  15382: =back
                   15383: 
1.139     matthew  15384: =cut
                   15385: 
                   15386: ############################################################
                   15387: ############################################################
                   15388: sub chartlink {
                   15389:     my ($linktext, $sname, $sdomain) = @_;
                   15390:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15391:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15392:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15393:        '">'.$linktext.'</a>';
1.153     matthew  15394: }
                   15395: 
                   15396: #######################################################
                   15397: #######################################################
                   15398: 
                   15399: =pod
                   15400: 
                   15401: =head1 Course Environment Routines
1.157     matthew  15402: 
                   15403: =over 4
1.153     matthew  15404: 
1.648     raeburn  15405: =item * &restore_course_settings()
1.153     matthew  15406: 
1.648     raeburn  15407: =item * &store_course_settings()
1.153     matthew  15408: 
                   15409: Restores/Store indicated form parameters from the course environment.
                   15410: Will not overwrite existing values of the form parameters.
                   15411: 
                   15412: Inputs: 
                   15413: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15414: 
                   15415: a hash ref describing the data to be stored.  For example:
                   15416:    
                   15417: %Save_Parameters = ('Status' => 'scalar',
                   15418:     'chartoutputmode' => 'scalar',
                   15419:     'chartoutputdata' => 'scalar',
                   15420:     'Section' => 'array',
1.373     raeburn  15421:     'Group' => 'array',
1.153     matthew  15422:     'StudentData' => 'array',
                   15423:     'Maps' => 'array');
                   15424: 
                   15425: Returns: both routines return nothing
                   15426: 
1.631     raeburn  15427: =back
                   15428: 
1.153     matthew  15429: =cut
                   15430: 
                   15431: #######################################################
                   15432: #######################################################
                   15433: sub store_course_settings {
1.496     albertel 15434:     return &store_settings($env{'request.course.id'},@_);
                   15435: }
                   15436: 
                   15437: sub store_settings {
1.153     matthew  15438:     # save to the environment
                   15439:     # appenv the same items, just to be safe
1.300     albertel 15440:     my $udom  = $env{'user.domain'};
                   15441:     my $uname = $env{'user.name'};
1.496     albertel 15442:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15443:     my %SaveHash;
                   15444:     my %AppHash;
                   15445:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15446:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15447:         my $envname = 'environment.'.$basename;
1.258     albertel 15448:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15449:             # Save this value away
                   15450:             if ($type eq 'scalar' &&
1.258     albertel 15451:                 (! exists($env{$envname}) || 
                   15452:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15453:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15454:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15455:             } elsif ($type eq 'array') {
                   15456:                 my $stored_form;
1.258     albertel 15457:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15458:                     $stored_form = join(',',
                   15459:                                         map {
1.369     www      15460:                                             &escape($_);
1.258     albertel 15461:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15462:                 } else {
                   15463:                     $stored_form = 
1.369     www      15464:                         &escape($env{'form.'.$setting});
1.153     matthew  15465:                 }
                   15466:                 # Determine if the array contents are the same.
1.258     albertel 15467:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15468:                     $SaveHash{$basename} = $stored_form;
                   15469:                     $AppHash{$envname}   = $stored_form;
                   15470:                 }
                   15471:             }
                   15472:         }
                   15473:     }
                   15474:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15475:                                           $udom,$uname);
1.153     matthew  15476:     if ($put_result !~ /^(ok|delayed)/) {
                   15477:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15478:                                  'got error:'.$put_result);
                   15479:     }
                   15480:     # Make sure these settings stick around in this session, too
1.646     raeburn  15481:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15482:     return;
                   15483: }
                   15484: 
                   15485: sub restore_course_settings {
1.499     albertel 15486:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15487: }
                   15488: 
                   15489: sub restore_settings {
                   15490:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15491:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15492:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15493:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15494:             '.'.$setting;
1.258     albertel 15495:         if (exists($env{$envname})) {
1.153     matthew  15496:             if ($type eq 'scalar') {
1.258     albertel 15497:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15498:             } elsif ($type eq 'array') {
1.258     albertel 15499:                 $env{'form.'.$setting} = [ 
1.153     matthew  15500:                                            map { 
1.369     www      15501:                                                &unescape($_); 
1.258     albertel 15502:                                            } split(',',$env{$envname})
1.153     matthew  15503:                                            ];
                   15504:             }
                   15505:         }
                   15506:     }
1.127     matthew  15507: }
                   15508: 
1.618     raeburn  15509: #######################################################
                   15510: #######################################################
                   15511: 
                   15512: =pod
                   15513: 
                   15514: =head1 Domain E-mail Routines  
                   15515: 
                   15516: =over 4
                   15517: 
1.648     raeburn  15518: =item * &build_recipient_list()
1.618     raeburn  15519: 
1.1144    raeburn  15520: Build recipient lists for following types of e-mail:
1.766     raeburn  15521: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15522: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15523: module change checking, student/employee ID conflict checks, as
                   15524: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15525: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15526: 
                   15527: Inputs:
1.619     raeburn  15528: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15529: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15530: requestsmail, updatesmail, or idconflictsmail).
                   15531: 
1.619     raeburn  15532: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15533: 
1.619     raeburn  15534: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15535: i.e., predates configuration by DC via domainprefs.pm
                   15536: 
                   15537: $requname username of requester (if mailing type is helpdeskmail)
                   15538: 
                   15539: $requdom domain of requester (if mailing type is helpdeskmail)
                   15540: 
                   15541: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15542: 
1.618     raeburn  15543: 
1.655     raeburn  15544: Returns: comma separated list of addresses to which to send e-mail.
                   15545: 
                   15546: =back
1.618     raeburn  15547: 
                   15548: =cut
                   15549: 
                   15550: ############################################################
                   15551: ############################################################
                   15552: sub build_recipient_list {
1.1297    raeburn  15553:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15554:     my @recipients;
1.1270    raeburn  15555:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15556:     my %domconfig =
1.1270    raeburn  15557:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15558:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15559:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15560:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15561:                 my @contacts = ('adminemail','supportemail');
                   15562:                 foreach my $item (@contacts) {
                   15563:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15564:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15565:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15566:                             push(@recipients,$addr);
                   15567:                         }
1.619     raeburn  15568:                     }
1.1270    raeburn  15569:                 }
                   15570:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15571:                 if ($mailing eq 'helpdeskmail') {
                   15572:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15573:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15574:                         my @ok_bccs;
                   15575:                         foreach my $bcc (@bccs) {
                   15576:                             $bcc =~ s/^\s+//g;
                   15577:                             $bcc =~ s/\s+$//g;
                   15578:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15579:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15580:                                     push(@ok_bccs,$bcc);
                   15581:                                 }
                   15582:                             }
                   15583:                         }
                   15584:                         if (@ok_bccs > 0) {
                   15585:                             $allbcc = join(', ',@ok_bccs);
                   15586:                         }
                   15587:                     }
                   15588:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15589:                 }
                   15590:             }
1.766     raeburn  15591:         } elsif ($origmail ne '') {
1.1270    raeburn  15592:             $lastresort = $origmail;
1.618     raeburn  15593:         }
1.1297    raeburn  15594:         if ($mailing eq 'helpdeskmail') {
                   15595:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15596:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15597:                 my ($inststatus,$inststatus_checked);
                   15598:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15599:                     ($env{'user.domain'} ne 'public')) {
                   15600:                     $inststatus_checked = 1;
                   15601:                     $inststatus = $env{'environment.inststatus'};
                   15602:                 }
                   15603:                 unless ($inststatus_checked) {
                   15604:                     if (($requname ne '') && ($requdom ne '')) {
                   15605:                         if (($requname =~ /^$match_username$/) &&
                   15606:                             ($requdom =~ /^$match_domain$/) &&
                   15607:                             (&Apache::lonnet::domain($requdom))) {
                   15608:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15609:                                                                       $requdom);
                   15610:                             unless ($requhome eq 'no_host') {
                   15611:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15612:                                 $inststatus = $userenv{'inststatus'};
                   15613:                                 $inststatus_checked = 1;
                   15614:                             }
                   15615:                         }
                   15616:                     }
                   15617:                 }
                   15618:                 unless ($inststatus_checked) {
                   15619:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15620:                         my %srch = (srchby     => 'email',
                   15621:                                     srchdomain => $defdom,
                   15622:                                     srchterm   => $reqemail,
                   15623:                                     srchtype   => 'exact');
                   15624:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15625:                         foreach my $uname (keys(%srch_results)) {
                   15626:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15627:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15628:                                 $inststatus_checked = 1;
                   15629:                                 last;
                   15630:                             }
                   15631:                         }
                   15632:                         unless ($inststatus_checked) {
                   15633:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15634:                             if ($dirsrchres eq 'ok') {
                   15635:                                 foreach my $uname (keys(%srch_results)) {
                   15636:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15637:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15638:                                         $inststatus_checked = 1;
                   15639:                                         last;
                   15640:                                     }
                   15641:                                 }
                   15642:                             }
                   15643:                         }
                   15644:                     }
                   15645:                 }
                   15646:                 if ($inststatus ne '') {
                   15647:                     foreach my $status (split(/\:/,$inststatus)) {
                   15648:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15649:                             my @contacts = ('adminemail','supportemail');
                   15650:                             foreach my $item (@contacts) {
                   15651:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15652:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15653:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15654:                                         push(@recipients,$addr);
                   15655:                                     }
                   15656:                                 }
                   15657:                             }
                   15658:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15659:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15660:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15661:                                 my @ok_bccs;
                   15662:                                 foreach my $bcc (@bccs) {
                   15663:                                     $bcc =~ s/^\s+//g;
                   15664:                                     $bcc =~ s/\s+$//g;
                   15665:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15666:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15667:                                             push(@ok_bccs,$bcc);
                   15668:                                         }
                   15669:                                     }
                   15670:                                 }
                   15671:                                 if (@ok_bccs > 0) {
                   15672:                                     $allbcc = join(', ',@ok_bccs);
                   15673:                                 }
                   15674:                             }
                   15675:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15676:                             last;
                   15677:                         }
                   15678:                     }
                   15679:                 }
                   15680:             }
                   15681:         }
1.619     raeburn  15682:     } elsif ($origmail ne '') {
1.1270    raeburn  15683:         $lastresort = $origmail;
                   15684:     }
1.1297    raeburn  15685:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15686:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15687:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15688:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15689:             my %what = (
                   15690:                           perlvar => 1,
                   15691:                        );
                   15692:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15693:             if ($primary) {
                   15694:                 my $gotaddr;
                   15695:                 my ($result,$returnhash) =
                   15696:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15697:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15698:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15699:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15700:                         $gotaddr = 1;
                   15701:                     }
                   15702:                 }
                   15703:                 unless ($gotaddr) {
                   15704:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15705:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15706:                     unless ($uintdom eq $intdom) {
                   15707:                         my %domconfig =
                   15708:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15709:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15710:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15711:                                 my @contacts = ('adminemail','supportemail');
                   15712:                                 foreach my $item (@contacts) {
                   15713:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15714:                                         my $addr = $domconfig{'contacts'}{$item};
                   15715:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15716:                                             push(@recipients,$addr);
                   15717:                                         }
                   15718:                                     }
                   15719:                                 }
                   15720:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15721:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15722:                                 }
                   15723:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15724:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15725:                                     my @ok_bccs;
                   15726:                                     foreach my $bcc (@bccs) {
                   15727:                                         $bcc =~ s/^\s+//g;
                   15728:                                         $bcc =~ s/\s+$//g;
                   15729:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15730:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15731:                                                 push(@ok_bccs,$bcc);
                   15732:                                             }
                   15733:                                         }
                   15734:                                     }
                   15735:                                     if (@ok_bccs > 0) {
                   15736:                                         $allbcc = join(', ',@ok_bccs);
                   15737:                                     }
                   15738:                                 }
                   15739:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15740:                             }
                   15741:                         }
                   15742:                     }
                   15743:                 }
                   15744:             }
                   15745:         }
1.618     raeburn  15746:     }
1.688     raeburn  15747:     if (defined($defmail)) {
                   15748:         if ($defmail ne '') {
                   15749:             push(@recipients,$defmail);
                   15750:         }
1.618     raeburn  15751:     }
                   15752:     if ($otheremails) {
1.619     raeburn  15753:         my @others;
                   15754:         if ($otheremails =~ /,/) {
                   15755:             @others = split(/,/,$otheremails);
1.618     raeburn  15756:         } else {
1.619     raeburn  15757:             push(@others,$otheremails);
                   15758:         }
                   15759:         foreach my $addr (@others) {
                   15760:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15761:                 push(@recipients,$addr);
                   15762:             }
1.618     raeburn  15763:         }
                   15764:     }
1.1298    raeburn  15765:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15766:         if ((!@recipients) && ($lastresort ne '')) {
                   15767:             push(@recipients,$lastresort);
                   15768:         }
                   15769:     } elsif ($lastresort ne '') {
                   15770:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15771:             push(@recipients,$lastresort);
                   15772:         }
                   15773:     }
1.1271    raeburn  15774:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15775:     if (wantarray) {
                   15776:         return ($recipientlist,$allbcc,$addtext);
                   15777:     } else {
                   15778:         return $recipientlist;
                   15779:     }
1.618     raeburn  15780: }
                   15781: 
1.127     matthew  15782: ############################################################
                   15783: ############################################################
1.154     albertel 15784: 
1.655     raeburn  15785: =pod
                   15786: 
1.1224    musolffc 15787: =over 4
                   15788: 
1.1223    musolffc 15789: =item * &mime_email()
                   15790: 
                   15791: Sends an email with a possible attachment
                   15792: 
                   15793: Inputs:
                   15794: 
                   15795: =over 4
                   15796: 
                   15797: from -              Sender's email address
                   15798: 
1.1343    raeburn  15799: replyto -           Reply-To email address
                   15800: 
1.1223    musolffc 15801: to -                Email address of recipient
                   15802: 
                   15803: subject -           Subject of email
                   15804: 
                   15805: body -              Body of email
                   15806: 
                   15807: cc_string -         Carbon copy email address
                   15808: 
                   15809: bcc -               Blind carbon copy email address
                   15810: 
                   15811: attachment_path -   Path of file to be attached
                   15812: 
                   15813: file_name -         Name of file to be attached
                   15814: 
                   15815: attachment_text -   The body of an attachment of type "TEXT"
                   15816: 
                   15817: =back
                   15818: 
                   15819: =back
                   15820: 
                   15821: =cut
                   15822: 
                   15823: ############################################################
                   15824: ############################################################
                   15825: 
                   15826: sub mime_email {
1.1343    raeburn  15827:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15828:         $file_name,$attachment_text) = @_;
                   15829:  
1.1223    musolffc 15830:     my $msg = MIME::Lite->new(
                   15831:              From    => $from,
                   15832:              To      => $to,
                   15833:              Subject => $subject,
                   15834:              Type    =>'TEXT',
                   15835:              Data    => $body,
                   15836:              );
1.1343    raeburn  15837:     if ($replyto ne '') {
                   15838:         $msg->add("Reply-To" => $replyto);
                   15839:     }
1.1223    musolffc 15840:     if ($cc_string ne '') {
                   15841:         $msg->add("Cc" => $cc_string);
                   15842:     }
                   15843:     if ($bcc ne '') {
                   15844:         $msg->add("Bcc" => $bcc);
                   15845:     }
                   15846:     $msg->attr("content-type"         => "text/plain");
                   15847:     $msg->attr("content-type.charset" => "UTF-8");
                   15848:     # Attach file if given
                   15849:     if ($attachment_path) {
                   15850:         unless ($file_name) {
                   15851:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15852:         }
                   15853:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15854:         $msg->attach(Type     => $type,
                   15855:                      Path     => $attachment_path,
                   15856:                      Filename => $file_name
                   15857:                      );
                   15858:     # Otherwise attach text if given
                   15859:     } elsif ($attachment_text) {
                   15860:         $msg->attach(Type => 'TEXT',
                   15861:                      Data => $attachment_text);
                   15862:     }
                   15863:     # Send it
                   15864:     $msg->send('sendmail');
                   15865: }
                   15866: 
                   15867: ############################################################
                   15868: ############################################################
                   15869: 
                   15870: =pod
                   15871: 
1.655     raeburn  15872: =head1 Course Catalog Routines
                   15873: 
                   15874: =over 4
                   15875: 
                   15876: =item * &gather_categories()
                   15877: 
                   15878: Converts category definitions - keys of categories hash stored in  
                   15879: coursecategories in configuration.db on the primary library server in a 
                   15880: domain - to an array.  Also generates javascript and idx hash used to 
                   15881: generate Domain Coordinator interface for editing Course Categories.
                   15882: 
                   15883: Inputs:
1.663     raeburn  15884: 
1.655     raeburn  15885: categories (reference to hash of category definitions).
1.663     raeburn  15886: 
1.655     raeburn  15887: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15888:       categories and subcategories).
1.663     raeburn  15889: 
1.655     raeburn  15890: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15891:       editing Course Categories).
1.663     raeburn  15892: 
1.655     raeburn  15893: jsarray (reference to array of categories used to create Javascript arrays for
                   15894:          Domain Coordinator interface for editing Course Categories).
                   15895: 
                   15896: Returns: nothing
                   15897: 
                   15898: Side effects: populates cats, idx and jsarray. 
                   15899: 
                   15900: =cut
                   15901: 
                   15902: sub gather_categories {
                   15903:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15904:     my %counters;
                   15905:     my $num = 0;
                   15906:     foreach my $item (keys(%{$categories})) {
                   15907:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15908:         if ($container eq '' && $depth == 0) {
                   15909:             $cats->[$depth][$categories->{$item}] = $cat;
                   15910:         } else {
                   15911:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15912:         }
                   15913:         my ($escitem,$tail) = split(/:/,$item,2);
                   15914:         if ($counters{$tail} eq '') {
                   15915:             $counters{$tail} = $num;
                   15916:             $num ++;
                   15917:         }
                   15918:         if (ref($idx) eq 'HASH') {
                   15919:             $idx->{$item} = $counters{$tail};
                   15920:         }
                   15921:         if (ref($jsarray) eq 'ARRAY') {
                   15922:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15923:         }
                   15924:     }
                   15925:     return;
                   15926: }
                   15927: 
                   15928: =pod
                   15929: 
                   15930: =item * &extract_categories()
                   15931: 
                   15932: Used to generate breadcrumb trails for course categories.
                   15933: 
                   15934: Inputs:
1.663     raeburn  15935: 
1.655     raeburn  15936: categories (reference to hash of category definitions).
1.663     raeburn  15937: 
1.655     raeburn  15938: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15939:       categories and subcategories).
1.663     raeburn  15940: 
1.655     raeburn  15941: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15942: 
1.655     raeburn  15943: allitems (reference to hash - key is category key 
                   15944:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15945: 
1.655     raeburn  15946: idx (reference to hash of counters used in Domain Coordinator interface for
                   15947:       editing Course Categories).
1.663     raeburn  15948: 
1.655     raeburn  15949: jsarray (reference to array of categories used to create Javascript arrays for
                   15950:          Domain Coordinator interface for editing Course Categories).
                   15951: 
1.665     raeburn  15952: subcats (reference to hash of arrays containing all subcategories within each 
                   15953:          category, -recursive)
                   15954: 
1.1321    raeburn  15955: maxd (reference to hash used to hold max depth for all top-level categories).
                   15956: 
1.655     raeburn  15957: Returns: nothing
                   15958: 
                   15959: Side effects: populates trails and allitems hash references.
                   15960: 
                   15961: =cut
                   15962: 
                   15963: sub extract_categories {
1.1321    raeburn  15964:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15965:     if (ref($categories) eq 'HASH') {
                   15966:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15967:         if (ref($cats->[0]) eq 'ARRAY') {
                   15968:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15969:                 my $name = $cats->[0][$i];
                   15970:                 my $item = &escape($name).'::0';
                   15971:                 my $trailstr;
                   15972:                 if ($name eq 'instcode') {
                   15973:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15974:                 } elsif ($name eq 'communities') {
                   15975:                     $trailstr = &mt('Communities');
1.1239    raeburn  15976:                 } elsif ($name eq 'placement') {
                   15977:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15978:                 } else {
                   15979:                     $trailstr = $name;
                   15980:                 }
                   15981:                 if ($allitems->{$item} eq '') {
                   15982:                     push(@{$trails},$trailstr);
                   15983:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15984:                 }
                   15985:                 my @parents = ($name);
                   15986:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15987:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15988:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15989:                         if (ref($subcats) eq 'HASH') {
                   15990:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15991:                         }
1.1321    raeburn  15992:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15993:                     }
                   15994:                 } else {
                   15995:                     if (ref($subcats) eq 'HASH') {
                   15996:                         $subcats->{$item} = [];
1.655     raeburn  15997:                     }
1.1321    raeburn  15998:                     if (ref($maxd) eq 'HASH') {
                   15999:                         $maxd->{$name} = 1;
                   16000:                     }
1.655     raeburn  16001:                 }
                   16002:             }
                   16003:         }
                   16004:     }
                   16005:     return;
                   16006: }
                   16007: 
                   16008: =pod
                   16009: 
1.1162    raeburn  16010: =item * &recurse_categories()
1.655     raeburn  16011: 
                   16012: Recursively used to generate breadcrumb trails for course categories.
                   16013: 
                   16014: Inputs:
1.663     raeburn  16015: 
1.655     raeburn  16016: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16017:       categories and subcategories).
1.663     raeburn  16018: 
1.655     raeburn  16019: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16020: 
                   16021: category (current course category, for which breadcrumb trail is being generated).
                   16022: 
                   16023: trails (reference to array of breadcrumb trails for each category).
                   16024: 
1.655     raeburn  16025: allitems (reference to hash - key is category key
                   16026:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16027: 
1.655     raeburn  16028: parents (array containing containers directories for current category, 
                   16029:          back to top level). 
                   16030: 
                   16031: Returns: nothing
                   16032: 
                   16033: Side effects: populates trails and allitems hash references
                   16034: 
                   16035: =cut
                   16036: 
                   16037: sub recurse_categories {
1.1321    raeburn  16038:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16039:     my $shallower = $depth - 1;
                   16040:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16041:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16042:             my $name = $cats->[$depth]{$category}[$k];
                   16043:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16044:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16045:             if ($allitems->{$item} eq '') {
                   16046:                 push(@{$trails},$trailstr);
                   16047:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16048:             }
                   16049:             my $deeper = $depth+1;
                   16050:             push(@{$parents},$category);
1.665     raeburn  16051:             if (ref($subcats) eq 'HASH') {
                   16052:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16053:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16054:                     my $higher;
                   16055:                     if ($j > 0) {
                   16056:                         $higher = &escape($parents->[$j]).':'.
                   16057:                                   &escape($parents->[$j-1]).':'.$j;
                   16058:                     } else {
                   16059:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16060:                     }
                   16061:                     push(@{$subcats->{$higher}},$subcat);
                   16062:                 }
                   16063:             }
                   16064:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16065:                                 $subcats,$maxd);
1.655     raeburn  16066:             pop(@{$parents});
                   16067:         }
                   16068:     } else {
                   16069:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16070:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16071:         if ($allitems->{$item} eq '') {
                   16072:             push(@{$trails},$trailstr);
                   16073:             $allitems->{$item} = scalar(@{$trails})-1;
                   16074:         }
1.1321    raeburn  16075:         if (ref($maxd) eq 'HASH') {
                   16076:             if ($depth > $maxd->{$parents->[0]}) {
                   16077:                 $maxd->{$parents->[0]} = $depth;
                   16078:             }
                   16079:         }
1.655     raeburn  16080:     }
                   16081:     return;
                   16082: }
                   16083: 
1.663     raeburn  16084: =pod
                   16085: 
1.1162    raeburn  16086: =item * &assign_categories_table()
1.663     raeburn  16087: 
                   16088: Create a datatable for display of hierarchical categories in a domain,
                   16089: with checkboxes to allow a course to be categorized. 
                   16090: 
                   16091: Inputs:
                   16092: 
                   16093: cathash - reference to hash of categories defined for the domain (from
                   16094:           configuration.db)
                   16095: 
                   16096: currcat - scalar with an & separated list of categories assigned to a course. 
                   16097: 
1.919     raeburn  16098: type    - scalar contains course type (Course or Community).
                   16099: 
1.1260    raeburn  16100: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16101:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16102: 
1.663     raeburn  16103: Returns: $output (markup to be displayed) 
                   16104: 
                   16105: =cut
                   16106: 
                   16107: sub assign_categories_table {
1.1259    raeburn  16108:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16109:     my $output;
                   16110:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16111:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16112:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16113:         $maxdepth = scalar(@cats);
                   16114:         if (@cats > 0) {
                   16115:             my $itemcount = 0;
                   16116:             if (ref($cats[0]) eq 'ARRAY') {
                   16117:                 my @currcategories;
                   16118:                 if ($currcat ne '') {
                   16119:                     @currcategories = split('&',$currcat);
                   16120:                 }
1.919     raeburn  16121:                 my $table;
1.663     raeburn  16122:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16123:                     my $parent = $cats[0][$i];
1.919     raeburn  16124:                     next if ($parent eq 'instcode');
                   16125:                     if ($type eq 'Community') {
                   16126:                         next unless ($parent eq 'communities');
1.1239    raeburn  16127:                     } elsif ($type eq 'Placement') {
                   16128:                         next unless ($parent eq 'placement');
1.919     raeburn  16129:                     } else {
1.1239    raeburn  16130:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16131:                     }
1.663     raeburn  16132:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16133:                     my $item = &escape($parent).'::0';
                   16134:                     my $checked = '';
                   16135:                     if (@currcategories > 0) {
                   16136:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16137:                             $checked = ' checked="checked"';
1.663     raeburn  16138:                         }
                   16139:                     }
1.919     raeburn  16140:                     my $parent_title = $parent;
                   16141:                     if ($parent eq 'communities') {
                   16142:                         $parent_title = &mt('Communities');
1.1239    raeburn  16143:                     } elsif ($parent eq 'placement') {
                   16144:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16145:                     }
                   16146:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16147:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16148:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16149:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16150:                     my $depth = 1;
                   16151:                     push(@path,$parent);
1.1259    raeburn  16152:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16153:                     pop(@path);
1.919     raeburn  16154:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16155:                     $itemcount ++;
                   16156:                 }
1.919     raeburn  16157:                 if ($itemcount) {
                   16158:                     $output = &Apache::loncommon::start_data_table().
                   16159:                               $table.
                   16160:                               &Apache::loncommon::end_data_table();
                   16161:                 }
1.663     raeburn  16162:             }
                   16163:         }
                   16164:     }
                   16165:     return $output;
                   16166: }
                   16167: 
                   16168: =pod
                   16169: 
1.1162    raeburn  16170: =item * &assign_category_rows()
1.663     raeburn  16171: 
                   16172: Create a datatable row for display of nested categories in a domain,
                   16173: with checkboxes to allow a course to be categorized,called recursively.
                   16174: 
                   16175: Inputs:
                   16176: 
                   16177: itemcount - track row number for alternating colors
                   16178: 
                   16179: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16180:       categories and subcategories.
                   16181: 
                   16182: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16183: 
                   16184: parent - parent of current category item
                   16185: 
                   16186: path - Array containing all categories back up through the hierarchy from the
                   16187:        current category to the top level.
                   16188: 
                   16189: currcategories - reference to array of current categories assigned to the course
                   16190: 
1.1260    raeburn  16191: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16192:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16193: 
1.663     raeburn  16194: Returns: $output (markup to be displayed).
                   16195: 
                   16196: =cut
                   16197: 
                   16198: sub assign_category_rows {
1.1259    raeburn  16199:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16200:     my ($text,$name,$item,$chgstr);
                   16201:     if (ref($cats) eq 'ARRAY') {
                   16202:         my $maxdepth = scalar(@{$cats});
                   16203:         if (ref($cats->[$depth]) eq 'HASH') {
                   16204:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16205:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16206:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16207:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16208:                 for (my $j=0; $j<$numchildren; $j++) {
                   16209:                     $name = $cats->[$depth]{$parent}[$j];
                   16210:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16211:                     my $deeper = $depth+1;
                   16212:                     my $checked = '';
                   16213:                     if (ref($currcategories) eq 'ARRAY') {
                   16214:                         if (@{$currcategories} > 0) {
                   16215:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16216:                                 $checked = ' checked="checked"';
1.663     raeburn  16217:                             }
                   16218:                         }
                   16219:                     }
1.664     raeburn  16220:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16221:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16222:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16223:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16224:                              '</td><td>';
1.663     raeburn  16225:                     if (ref($path) eq 'ARRAY') {
                   16226:                         push(@{$path},$name);
1.1259    raeburn  16227:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16228:                         pop(@{$path});
                   16229:                     }
                   16230:                     $text .= '</td></tr>';
                   16231:                 }
                   16232:                 $text .= '</table></td>';
                   16233:             }
                   16234:         }
                   16235:     }
                   16236:     return $text;
                   16237: }
                   16238: 
1.1181    raeburn  16239: =pod
                   16240: 
                   16241: =back
                   16242: 
                   16243: =cut
                   16244: 
1.655     raeburn  16245: ############################################################
                   16246: ############################################################
                   16247: 
                   16248: 
1.443     albertel 16249: sub commit_customrole {
1.664     raeburn  16250:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16251:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16252:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16253:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16254:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16255:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16256:                  '</b><br />';
                   16257:     return $output;
                   16258: }
                   16259: 
                   16260: sub commit_standardrole {
1.1116    raeburn  16261:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16262:     my ($output,$logmsg,$linefeed);
                   16263:     if ($context eq 'auto') {
                   16264:         $linefeed = "\n";
                   16265:     } else {
                   16266:         $linefeed = "<br />\n";
                   16267:     }  
1.443     albertel 16268:     if ($three eq 'st') {
1.541     raeburn  16269:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16270:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16271:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16272:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16273:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16274:         } else {
1.541     raeburn  16275:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16276:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16277:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16278:             if ($context eq 'auto') {
                   16279:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16280:             } else {
                   16281:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16282:                &mt('Add to classlist').': <b>ok</b>';
                   16283:             }
                   16284:             $output .= $linefeed;
1.443     albertel 16285:         }
                   16286:     } else {
                   16287:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16288:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16289:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16290:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16291:         if ($context eq 'auto') {
                   16292:             $output .= $result.$linefeed;
                   16293:         } else {
                   16294:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16295:         }
1.443     albertel 16296:     }
                   16297:     return $output;
                   16298: }
                   16299: 
                   16300: sub commit_studentrole {
1.1116    raeburn  16301:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16302:         $credits) = @_;
1.626     raeburn  16303:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16304:     if ($context eq 'auto') {
                   16305:         $linefeed = "\n";
                   16306:     } else {
                   16307:         $linefeed = '<br />'."\n";
                   16308:     }
1.443     albertel 16309:     if (defined($one) && defined($two)) {
                   16310:         my $cid=$one.'_'.$two;
                   16311:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16312:         my $secchange = 0;
                   16313:         my $expire_role_result;
                   16314:         my $modify_section_result;
1.628     raeburn  16315:         if ($oldsec ne '-1') { 
                   16316:             if ($oldsec ne $sec) {
1.443     albertel 16317:                 $secchange = 1;
1.628     raeburn  16318:                 my $now = time;
1.443     albertel 16319:                 my $uurl='/'.$cid;
                   16320:                 $uurl=~s/\_/\//g;
                   16321:                 if ($oldsec) {
                   16322:                     $uurl.='/'.$oldsec;
                   16323:                 }
1.626     raeburn  16324:                 $oldsecurl = $uurl;
1.628     raeburn  16325:                 $expire_role_result = 
1.652     raeburn  16326:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16327:                 if ($env{'request.course.sec'} ne '') { 
                   16328:                     if ($expire_role_result eq 'refused') {
                   16329:                         my @roles = ('st');
                   16330:                         my @statuses = ('previous');
                   16331:                         my @roledoms = ($one);
                   16332:                         my $withsec = 1;
                   16333:                         my %roleshash = 
                   16334:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16335:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16336:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16337:                             my ($oldstart,$oldend) = 
                   16338:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16339:                             if ($oldend > 0 && $oldend <= $now) {
                   16340:                                 $expire_role_result = 'ok';
                   16341:                             }
                   16342:                         }
                   16343:                     }
                   16344:                 }
1.443     albertel 16345:                 $result = $expire_role_result;
                   16346:             }
                   16347:         }
                   16348:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16349:             $modify_section_result = 
                   16350:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16351:                                                            undef,undef,undef,$sec,
                   16352:                                                            $end,$start,'','',$cid,
                   16353:                                                            '',$context,$credits);
1.443     albertel 16354:             if ($modify_section_result =~ /^ok/) {
                   16355:                 if ($secchange == 1) {
1.628     raeburn  16356:                     if ($sec eq '') {
                   16357:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16358:                     } else {
                   16359:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16360:                     }
1.443     albertel 16361:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16362:                     if ($sec eq '') {
                   16363:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16364:                     } else {
                   16365:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16366:                     }
1.443     albertel 16367:                 } else {
1.628     raeburn  16368:                     if ($sec eq '') {
                   16369:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16370:                     } else {
                   16371:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16372:                     }
1.443     albertel 16373:                 }
                   16374:             } else {
1.1115    raeburn  16375:                 if ($secchange) { 
1.628     raeburn  16376:                     $$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;
                   16377:                 } else {
                   16378:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16379:                 }
1.443     albertel 16380:             }
                   16381:             $result = $modify_section_result;
                   16382:         } elsif ($secchange == 1) {
1.628     raeburn  16383:             if ($oldsec eq '') {
1.1103    raeburn  16384:                 $$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  16385:             } else {
                   16386:                 $$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;
                   16387:             }
1.626     raeburn  16388:             if ($expire_role_result eq 'refused') {
                   16389:                 my $newsecurl = '/'.$cid;
                   16390:                 $newsecurl =~ s/\_/\//g;
                   16391:                 if ($sec ne '') {
                   16392:                     $newsecurl.='/'.$sec;
                   16393:                 }
                   16394:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16395:                     if ($sec eq '') {
                   16396:                         $$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;
                   16397:                     } else {
                   16398:                         $$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;
                   16399:                     }
                   16400:                 }
                   16401:             }
1.443     albertel 16402:         }
                   16403:     } else {
1.626     raeburn  16404:         $$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 16405:         $result = "error: incomplete course id\n";
                   16406:     }
                   16407:     return $result;
                   16408: }
                   16409: 
1.1108    raeburn  16410: sub show_role_extent {
                   16411:     my ($scope,$context,$role) = @_;
                   16412:     $scope =~ s{^/}{};
                   16413:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16414:     push(@courseroles,'co');
                   16415:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16416:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16417:         $scope =~ s{/}{_};
                   16418:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16419:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16420:         my ($audom,$auname) = split(/\//,$scope);
                   16421:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16422:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16423:     } else {
                   16424:         $scope =~ s{/$}{};
                   16425:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16426:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16427:     }
                   16428: }
                   16429: 
1.443     albertel 16430: ############################################################
                   16431: ############################################################
                   16432: 
1.566     albertel 16433: sub check_clone {
1.578     raeburn  16434:     my ($args,$linefeed) = @_;
1.566     albertel 16435:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16436:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16437:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16438:     my $clonetitle;
                   16439:     my @clonemsg;
1.566     albertel 16440:     my $can_clone = 0;
1.944     raeburn  16441:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16442:     if ($lctype ne 'community') {
                   16443:         $lctype = 'course';
                   16444:     }
1.566     albertel 16445:     if ($clonehome eq 'no_host') {
1.944     raeburn  16446:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16447:             push(@clonemsg,({
                   16448:                               mt => 'No new community created.',
                   16449:                               args => [],
                   16450:                             },
                   16451:                             {
                   16452:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16453:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16454:                             }));
1.908     raeburn  16455:         } else {
1.1344    raeburn  16456:             push(@clonemsg,({
                   16457:                               mt => 'No new course created.',
                   16458:                               args => [],
                   16459:                             },
                   16460:                             {
                   16461:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16462:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16463:                             }));
                   16464:         }
1.566     albertel 16465:     } else {
                   16466: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16467:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16468:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16469:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16470:                 push(@clonemsg,({
                   16471:                                   mt => 'No new community created.',
                   16472:                                   args => [],
                   16473:                                 },
                   16474:                                 {
                   16475:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16476:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16477:                                 }));
                   16478:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16479:             }
                   16480:         }
1.1262    raeburn  16481: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16482:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16483: 	    $can_clone = 1;
                   16484: 	} else {
1.1221    raeburn  16485: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16486: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16487:             if ($clonehash{'cloners'} eq '') {
                   16488:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16489:                 if ($domdefs{'canclone'}) {
                   16490:                     unless ($domdefs{'canclone'} eq 'none') {
                   16491:                         if ($domdefs{'canclone'} eq 'domain') {
                   16492:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16493:                                 $can_clone = 1;
                   16494:                             }
                   16495:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16496:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16497:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16498:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16499:                                 $can_clone = 1;
                   16500:                             }
                   16501:                         }
                   16502:                     }
                   16503:                 }
1.578     raeburn  16504:             } else {
1.1221    raeburn  16505: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16506:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16507:                     $can_clone = 1;
1.1221    raeburn  16508:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16509:                     $can_clone = 1;
1.1225    raeburn  16510:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16511:                     $can_clone = 1;
1.1221    raeburn  16512:                 }
                   16513:                 unless ($can_clone) {
1.1225    raeburn  16514:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16515:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16516:                         my (%gotdomdefaults,%gotcodedefaults);
                   16517:                         foreach my $cloner (@cloners) {
                   16518:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16519:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16520:                                 my (%codedefaults,@code_order);
                   16521:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16522:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16523:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16524:                                     }
                   16525:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16526:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16527:                                     }
                   16528:                                 } else {
                   16529:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16530:                                                                             \%codedefaults,
                   16531:                                                                             \@code_order);
                   16532:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16533:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16534:                                 }
                   16535:                                 if (@code_order > 0) {
                   16536:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16537:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16538:                                                                                 $args->{'crscode'})) {
                   16539:                                         $can_clone = 1;
                   16540:                                         last;
                   16541:                                     }
                   16542:                                 }
                   16543:                             }
                   16544:                         }
                   16545:                     }
1.1225    raeburn  16546:                 }
                   16547:             }
                   16548:             unless ($can_clone) {
                   16549:                 my $ccrole = 'cc';
                   16550:                 if ($args->{'crstype'} eq 'Community') {
                   16551:                     $ccrole = 'co';
                   16552:                 }
                   16553: 	        my %roleshash =
                   16554: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16555: 					          $args->{'ccdomain'},
                   16556:                                                   'userroles',['active'],[$ccrole],
                   16557: 					          [$args->{'clonedomain'}]);
                   16558: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16559:                     $can_clone = 1;
                   16560:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16561:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16562:                     $can_clone = 1;
1.1221    raeburn  16563:                 }
                   16564:             }
                   16565:             unless ($can_clone) {
                   16566:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16567:                     push(@clonemsg,({
                   16568:                                       mt => 'No new community created.',
                   16569:                                       args => [],
                   16570:                                     },
                   16571:                                     {
                   16572:                                       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]).',
                   16573:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16574:                                     }));
1.942     raeburn  16575:                 } else {
1.1344    raeburn  16576:                     push(@clonemsg,({
                   16577:                                       mt => 'No new course created.',
                   16578:                                       args => [],
                   16579:                                     },
                   16580:                                     {
                   16581:                                       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]).',
                   16582:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16583:                                     }));
1.1221    raeburn  16584:                 }
1.566     albertel 16585: 	    }
1.578     raeburn  16586:         }
1.566     albertel 16587:     }
1.1344    raeburn  16588:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16589: }
                   16590: 
1.444     albertel 16591: sub construct_course {
1.1262    raeburn  16592:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16593:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16594:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16595:     my $linefeed =  '<br />'."\n";
                   16596:     if ($context eq 'auto') {
                   16597:         $linefeed = "\n";
                   16598:     }
1.566     albertel 16599: 
                   16600: #
                   16601: # Are we cloning?
                   16602: #
1.1344    raeburn  16603:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16604:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16605: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16606:         if (!$can_clone) {
1.1344    raeburn  16607: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16608: 	}
                   16609:     }
                   16610: 
1.444     albertel 16611: #
                   16612: # Open course
                   16613: #
1.1239    raeburn  16614:     my $showncrstype;
                   16615:     if ($args->{'crstype'} eq 'Placement') {
                   16616:         $showncrstype = 'placement test'; 
                   16617:     } else {  
                   16618:         $showncrstype = lc($args->{'crstype'});
                   16619:     }
1.444     albertel 16620:     my %cenv=();
                   16621:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16622:                                              $args->{'cdescr'},
                   16623:                                              $args->{'curl'},
                   16624:                                              $args->{'course_home'},
                   16625:                                              $args->{'nonstandard'},
                   16626:                                              $args->{'crscode'},
                   16627:                                              $args->{'ccuname'}.':'.
                   16628:                                              $args->{'ccdomain'},
1.882     raeburn  16629:                                              $args->{'crstype'},
1.1344    raeburn  16630:                                              $cnum,$context,$category,
                   16631:                                              $callercontext);
1.444     albertel 16632: 
                   16633:     # Note: The testing routines depend on this being output; see 
                   16634:     # Utils::Course. This needs to at least be output as a comment
                   16635:     # if anyone ever decides to not show this, and Utils::Course::new
                   16636:     # will need to be suitably modified.
1.1344    raeburn  16637:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16638:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16639:     } else {
                   16640:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16641:     }
1.943     raeburn  16642:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16643:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16644:     }
                   16645: 
1.444     albertel 16646: #
                   16647: # Check if created correctly
                   16648: #
1.479     albertel 16649:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16650:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16651:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16652:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16653:             $outcome .= &mt_user($user_lh,
                   16654:                             'Course creation failed, unrecognized course home server.');
                   16655:         } else {
                   16656:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16657:         }
                   16658:         $outcome .= $linefeed;
                   16659:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16660:     }
1.541     raeburn  16661:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16662: 
1.444     albertel 16663: #
1.566     albertel 16664: # Do the cloning
                   16665: #   
1.1344    raeburn  16666:     my @clonemsg;
1.566     albertel 16667:     if ($can_clone && $cloneid) {
1.1344    raeburn  16668:         push(@clonemsg,
                   16669:                       {
                   16670:                           mt => 'Created [_1] by cloning from [_2]',
                   16671:                           args => [$showncrstype,$clonetitle],
                   16672:                       });
1.566     albertel 16673: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16674: # Copy all files
1.1344    raeburn  16675:         my @info =
                   16676: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16677: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16678:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16679:                                                      $args->{'tinyurls'});
                   16680:         if (@info) {
                   16681:             push(@clonemsg,@info);
                   16682:         }
1.444     albertel 16683: # Restore URL
1.566     albertel 16684: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16685: # Restore title
1.566     albertel 16686: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16687: # Restore creation date, creator and creation context.
                   16688:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16689:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16690:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16691: # Mark as cloned
1.566     albertel 16692: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16693: # Need to clone grading mode
                   16694:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16695:         $cenv{'grading'}=$newenv{'grading'};
                   16696: # Do not clone these environment entries
                   16697:         &Apache::lonnet::del('environment',
                   16698:                   ['default_enrollment_start_date',
                   16699:                    'default_enrollment_end_date',
                   16700:                    'question.email',
                   16701:                    'policy.email',
                   16702:                    'comment.email',
                   16703:                    'pch.users.denied',
1.725     raeburn  16704:                    'plc.users.denied',
                   16705:                    'hidefromcat',
1.1121    raeburn  16706:                    'checkforpriv',
1.1355    raeburn  16707:                    'categories'],
1.638     www      16708:                    $$crsudom,$$crsunum);
1.1170    raeburn  16709:         if ($args->{'textbook'}) {
                   16710:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16711:         }
1.444     albertel 16712:     }
1.566     albertel 16713: 
1.444     albertel 16714: #
                   16715: # Set environment (will override cloned, if existing)
                   16716: #
                   16717:     my @sections = ();
                   16718:     my @xlists = ();
                   16719:     if ($args->{'crstype'}) {
                   16720:         $cenv{'type'}=$args->{'crstype'};
                   16721:     }
1.1371    raeburn  16722:     if ($args->{'lti'}) {
                   16723:         $cenv{'internal.lti'}=$args->{'lti'};
                   16724:     }
1.444     albertel 16725:     if ($args->{'crsid'}) {
                   16726:         $cenv{'courseid'}=$args->{'crsid'};
                   16727:     }
                   16728:     if ($args->{'crscode'}) {
                   16729:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16730:     }
                   16731:     if ($args->{'crsquota'} ne '') {
                   16732:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16733:     } else {
                   16734:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16735:     }
                   16736:     if ($args->{'ccuname'}) {
                   16737:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16738:                                         ':'.$args->{'ccdomain'};
                   16739:     } else {
                   16740:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16741:     }
1.1116    raeburn  16742:     if ($args->{'defaultcredits'}) {
                   16743:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16744:     }
1.444     albertel 16745:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16746:     if ($args->{'crssections'}) {
                   16747:         $cenv{'internal.sectionnums'} = '';
                   16748:         if ($args->{'crssections'} =~ m/,/) {
                   16749:             @sections = split/,/,$args->{'crssections'};
                   16750:         } else {
                   16751:             $sections[0] = $args->{'crssections'};
                   16752:         }
                   16753:         if (@sections > 0) {
                   16754:             foreach my $item (@sections) {
                   16755:                 my ($sec,$gp) = split/:/,$item;
                   16756:                 my $class = $args->{'crscode'}.$sec;
                   16757:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16758:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16759:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16760:                     push(@badclasses,$class);
1.444     albertel 16761:                 }
                   16762:             }
                   16763:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16764:         }
                   16765:     }
                   16766: # do not hide course coordinator from staff listing, 
                   16767: # even if privileged
                   16768:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16769: # add course coordinator's domain to domains to check for privileged users
                   16770: # if different to course domain
                   16771:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16772:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16773:     }
1.444     albertel 16774: # add crosslistings
                   16775:     if ($args->{'crsxlist'}) {
                   16776:         $cenv{'internal.crosslistings'}='';
                   16777:         if ($args->{'crsxlist'} =~ m/,/) {
                   16778:             @xlists = split/,/,$args->{'crsxlist'};
                   16779:         } else {
                   16780:             $xlists[0] = $args->{'crsxlist'};
                   16781:         }
                   16782:         if (@xlists > 0) {
                   16783:             foreach my $item (@xlists) {
                   16784:                 my ($xl,$gp) = split/:/,$item;
                   16785:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16786:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16787:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16788:                     push(@badclasses,$xl);
1.444     albertel 16789:                 }
                   16790:             }
                   16791:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16792:         }
                   16793:     }
                   16794:     if ($args->{'autoadds'}) {
                   16795:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16796:     }
                   16797:     if ($args->{'autodrops'}) {
                   16798:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16799:     }
                   16800: # check for notification of enrollment changes
                   16801:     my @notified = ();
                   16802:     if ($args->{'notify_owner'}) {
                   16803:         if ($args->{'ccuname'} ne '') {
                   16804:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16805:         }
                   16806:     }
                   16807:     if ($args->{'notify_dc'}) {
                   16808:         if ($uname ne '') { 
1.630     raeburn  16809:             push(@notified,$uname.':'.$udom);
1.444     albertel 16810:         }
                   16811:     }
                   16812:     if (@notified > 0) {
                   16813:         my $notifylist;
                   16814:         if (@notified > 1) {
                   16815:             $notifylist = join(',',@notified);
                   16816:         } else {
                   16817:             $notifylist = $notified[0];
                   16818:         }
                   16819:         $cenv{'internal.notifylist'} = $notifylist;
                   16820:     }
                   16821:     if (@badclasses > 0) {
                   16822:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16823:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16824:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16825:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16826:         );
1.1264    raeburn  16827:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16828:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  16829:         if ($context eq 'auto') {
                   16830:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16831:         } else {
1.566     albertel 16832:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16833:         }
                   16834:         foreach my $item (@badclasses) {
1.541     raeburn  16835:             if ($context eq 'auto') {
1.1261    raeburn  16836:                 $outcome .= " - $item\n";
1.541     raeburn  16837:             } else {
1.1261    raeburn  16838:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16839:             }
1.1261    raeburn  16840:         }
                   16841:         if ($context eq 'auto') {
                   16842:             $outcome .= $linefeed;
                   16843:         } else {
                   16844:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16845:         } 
1.444     albertel 16846:     }
                   16847:     if ($args->{'no_end_date'}) {
                   16848:         $args->{'endaccess'} = 0;
                   16849:     }
                   16850:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16851:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16852:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16853:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16854:     if ($args->{'showphotos'}) {
                   16855:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16856:     }
                   16857:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16858:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16859:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16860:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16861:             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'); 
                   16862:             if ($context eq 'auto') {
                   16863:                 $outcome .= $krb_msg;
                   16864:             } else {
1.566     albertel 16865:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16866:             }
                   16867:             $outcome .= $linefeed;
1.444     albertel 16868:         }
                   16869:     }
                   16870:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16871:        if ($args->{'setpolicy'}) {
                   16872:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16873:        }
                   16874:        if ($args->{'setcontent'}) {
                   16875:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16876:        }
1.1251    raeburn  16877:        if ($args->{'setcomment'}) {
                   16878:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16879:        }
1.444     albertel 16880:     }
                   16881:     if ($args->{'reshome'}) {
                   16882: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16883: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16884:     }
                   16885: #
                   16886: # course has keyed access
                   16887: #
                   16888:     if ($args->{'setkeys'}) {
                   16889:        $cenv{'keyaccess'}='yes';
                   16890:     }
                   16891: # if specified, key authority is not course, but user
                   16892: # only active if keyaccess is yes
                   16893:     if ($args->{'keyauth'}) {
1.487     albertel 16894: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16895: 	$user = &LONCAPA::clean_username($user);
                   16896: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16897: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16898: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16899: 	}
                   16900:     }
                   16901: 
1.1166    raeburn  16902: #
1.1167    raeburn  16903: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16904: #
                   16905:     if ($args->{'uniquecode'}) {
                   16906:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16907:         if ($code) {
                   16908:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16909:             my %crsinfo =
                   16910:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16911:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16912:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16913:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16914:             } 
1.1166    raeburn  16915:             if (ref($coderef)) {
                   16916:                 $$coderef = $code;
                   16917:             }
                   16918:         }
                   16919:     }
                   16920: 
1.444     albertel 16921:     if ($args->{'disresdis'}) {
                   16922:         $cenv{'pch.roles.denied'}='st';
                   16923:     }
                   16924:     if ($args->{'disablechat'}) {
                   16925:         $cenv{'plc.roles.denied'}='st';
                   16926:     }
                   16927: 
                   16928:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16929:     # course
                   16930:     $cenv{'course.helper.not.run'} = 1;
                   16931:     #
                   16932:     # Use new Randomseed
                   16933:     #
                   16934:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16935:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16936:     #
                   16937:     # The encryption code and receipt prefix for this course
                   16938:     #
                   16939:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16940:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16941:     #
                   16942:     # By default, use standard grading
                   16943:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16944: 
1.541     raeburn  16945:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16946:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16947: #
                   16948: # Open all assignments
                   16949: #
                   16950:     if ($args->{'openall'}) {
1.1341    raeburn  16951:        my $opendate = time;
                   16952:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16953:            $opendate = $args->{'openallfrom'};
                   16954:        }
1.444     albertel 16955:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16956:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16957:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16958:        $outcome .= &mt('All assignments open starting [_1]',
                   16959:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16960:                    &Apache::lonnet::cput
                   16961:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16962:    }
                   16963: #
                   16964: # Set first page
                   16965: #
                   16966:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16967: 	    || ($cloneid)) {
1.445     albertel 16968: 	use LONCAPA::map;
1.444     albertel 16969: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16970: 
                   16971: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16972:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16973: 
1.444     albertel 16974:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16975:         my $title; my $url;
                   16976:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16977: 	    $title=&mt('Syllabus');
1.444     albertel 16978:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16979:         } else {
1.963     raeburn  16980:             $title=&mt('Table of Contents');
1.444     albertel 16981:             $url='/adm/navmaps';
                   16982:         }
1.445     albertel 16983: 
                   16984:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16985: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16986: 
                   16987: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16988:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16989:     }
1.566     albertel 16990: 
1.1237    raeburn  16991: # 
                   16992: # Set params for Placement Tests
                   16993: #
1.1239    raeburn  16994:     if ($args->{'crstype'} eq 'Placement') {
                   16995:        my %storecontent; 
                   16996:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   16997:        my %defaults = (
                   16998:                         buttonshide   => { value => 'yes',
                   16999:                                            type => 'string_yesno',},
                   17000:                         type          => { value => 'randomizetry',
                   17001:                                            type  => 'string_questiontype',},
                   17002:                         maxtries      => { value => 1,
                   17003:                                            type => 'int_pos',},
                   17004:                         problemstatus => { value => 'no',
                   17005:                                            type  => 'string_problemstatus',},
                   17006:                       );
                   17007:        foreach my $key (keys(%defaults)) {
                   17008:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17009:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17010:        }
1.1237    raeburn  17011:        &Apache::lonnet::cput
                   17012:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17013:     }
                   17014: 
1.1344    raeburn  17015:     return (1,$outcome,\@clonemsg);
1.444     albertel 17016: }
                   17017: 
1.1166    raeburn  17018: sub make_unique_code {
                   17019:     my ($cdom,$cnum) = @_;
                   17020:     # get lock on uniquecodes db
                   17021:     my $lockhash = {
                   17022:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17023:                                                   ':'.$env{'user.domain'},
                   17024:                    };
                   17025:     my $tries = 0;
                   17026:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17027:     my ($code,$error);
                   17028:   
                   17029:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17030:         $tries ++;
                   17031:         sleep 1;
                   17032:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17033:     }
                   17034:     if ($gotlock eq 'ok') {
                   17035:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17036:         my $gotcode;
                   17037:         my $attempts = 0;
                   17038:         while ((!$gotcode) && ($attempts < 100)) {
                   17039:             $code = &generate_code();
                   17040:             if (!exists($currcodes{$code})) {
                   17041:                 $gotcode = 1;
                   17042:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17043:                     $error = 'nostore';
                   17044:                 }
                   17045:             }
                   17046:             $attempts ++;
                   17047:         }
                   17048:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17049:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17050:     } else {
                   17051:         $error = 'nolock';
                   17052:     }
                   17053:     return ($code,$error);
                   17054: }
                   17055: 
                   17056: sub generate_code {
                   17057:     my $code;
                   17058:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17059:     for (my $i=0; $i<6; $i++) {
                   17060:         my $lettnum = int (rand 2);
                   17061:         my $item = '';
                   17062:         if ($lettnum) {
                   17063:             $item = $letts[int( rand(18) )];
                   17064:         } else {
                   17065:             $item = 1+int( rand(8) );
                   17066:         }
                   17067:         $code .= $item;
                   17068:     }
                   17069:     return $code;
                   17070: }
                   17071: 
1.444     albertel 17072: ############################################################
                   17073: ############################################################
                   17074: 
1.1237    raeburn  17075: # Community, Course and Placement Test
1.378     raeburn  17076: sub course_type {
                   17077:     my ($cid) = @_;
                   17078:     if (!defined($cid)) {
                   17079:         $cid = $env{'request.course.id'};
                   17080:     }
1.404     albertel 17081:     if (defined($env{'course.'.$cid.'.type'})) {
                   17082:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17083:     } else {
                   17084:         return 'Course';
1.377     raeburn  17085:     }
                   17086: }
1.156     albertel 17087: 
1.406     raeburn  17088: sub group_term {
                   17089:     my $crstype = &course_type();
                   17090:     my %names = (
                   17091:                   'Course' => 'group',
1.865     raeburn  17092:                   'Community' => 'group',
1.1237    raeburn  17093:                   'Placement' => 'group',
1.406     raeburn  17094:                 );
                   17095:     return $names{$crstype};
                   17096: }
                   17097: 
1.902     raeburn  17098: sub course_types {
1.1310    raeburn  17099:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17100:     my %typename = (
                   17101:                          official   => 'Official course',
                   17102:                          unofficial => 'Unofficial course',
                   17103:                          community  => 'Community',
1.1165    raeburn  17104:                          textbook   => 'Textbook course',
1.1237    raeburn  17105:                          placement  => 'Placement test',
1.1310    raeburn  17106:                          lti        => 'LTI provider',
1.902     raeburn  17107:                    );
                   17108:     return (\@types,\%typename);
                   17109: }
                   17110: 
1.156     albertel 17111: sub icon {
                   17112:     my ($file)=@_;
1.505     albertel 17113:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17114:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17115:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17116:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17117: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17118: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17119: 	            $curfext.".gif") {
                   17120: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17121: 		$curfext.".gif";
                   17122: 	}
                   17123:     }
1.249     albertel 17124:     return &lonhttpdurl($iconname);
1.154     albertel 17125: } 
1.84      albertel 17126: 
1.575     albertel 17127: sub lonhttpdurl {
1.692     www      17128: #
                   17129: # Had been used for "small fry" static images on separate port 8080.
                   17130: # Modify here if lightweight http functionality desired again.
                   17131: # Currently eliminated due to increasing firewall issues.
                   17132: #
1.575     albertel 17133:     my ($url)=@_;
1.692     www      17134:     return $url;
1.215     albertel 17135: }
                   17136: 
1.213     albertel 17137: sub connection_aborted {
                   17138:     my ($r)=@_;
                   17139:     $r->print(" ");$r->rflush();
                   17140:     my $c = $r->connection;
                   17141:     return $c->aborted();
                   17142: }
                   17143: 
1.221     foxr     17144: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17145: #    strings as 'strings'.
                   17146: sub escape_single {
1.221     foxr     17147:     my ($input) = @_;
1.223     albertel 17148:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17149:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17150:     return $input;
                   17151: }
1.223     albertel 17152: 
1.222     foxr     17153: #  Same as escape_single, but escape's "'s  This 
                   17154: #  can be used for  "strings"
                   17155: sub escape_double {
                   17156:     my ($input) = @_;
                   17157:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17158:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17159:     return $input;
                   17160: }
1.223     albertel 17161:  
1.222     foxr     17162: #   Escapes the last element of a full URL.
                   17163: sub escape_url {
                   17164:     my ($url)   = @_;
1.238     raeburn  17165:     my @urlslices = split(/\//, $url,-1);
1.369     www      17166:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17167:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17168: }
1.462     albertel 17169: 
1.820     raeburn  17170: sub compare_arrays {
                   17171:     my ($arrayref1,$arrayref2) = @_;
                   17172:     my (@difference,%count);
                   17173:     @difference = ();
                   17174:     %count = ();
                   17175:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17176:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17177:         foreach my $element (keys(%count)) {
                   17178:             if ($count{$element} == 1) {
                   17179:                 push(@difference,$element);
                   17180:             }
                   17181:         }
                   17182:     }
                   17183:     return @difference;
                   17184: }
                   17185: 
1.1322    raeburn  17186: sub lon_status_items {
                   17187:     my %defaults = (
                   17188:                      E         => 100,
                   17189:                      W         => 4,
                   17190:                      N         => 1,
1.1324    raeburn  17191:                      U         => 5,
1.1322    raeburn  17192:                      threshold => 200,
                   17193:                      sysmail   => 2500,
                   17194:                    );
                   17195:     my %names = (
                   17196:                    E => 'Errors',
                   17197:                    W => 'Warnings',
                   17198:                    N => 'Notices',
1.1324    raeburn  17199:                    U => 'Unsent',
1.1322    raeburn  17200:                 );
                   17201:     return (\%defaults,\%names);
                   17202: }
                   17203: 
1.817     bisitz   17204: # -------------------------------------------------------- Initialize user login
1.462     albertel 17205: sub init_user_environment {
1.463     albertel 17206:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17207:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17208: 
                   17209:     my $public=($username eq 'public' && $domain eq 'public');
                   17210: 
1.1062    raeburn  17211:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17212:     my $now=time;
                   17213: 
                   17214:     if ($public) {
                   17215: 	my $max_public=100;
                   17216: 	my $oldest;
                   17217: 	my $oldest_time=0;
                   17218: 	for(my $next=1;$next<=$max_public;$next++) {
                   17219: 	    if (-e $lonids."/publicuser_$next.id") {
                   17220: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17221: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17222: 		    $oldest_time=$mtime;
                   17223: 		    $oldest=$next;
                   17224: 		}
                   17225: 	    } else {
                   17226: 		$cookie="publicuser_$next";
                   17227: 		last;
                   17228: 	    }
                   17229: 	}
                   17230: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17231:     } else {
1.1275    raeburn  17232: 	# See if old ID present, if so, remove if this isn't a robot,
                   17233: 	# killing any existing non-robot sessions
1.463     albertel 17234: 	if (!$args->{'robot'}) {
                   17235: 	    opendir(DIR,$lonids);
                   17236: 	    while ($filename=readdir(DIR)) {
                   17237: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17238:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17239:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17240:                         my $linkedfile;
1.1320    raeburn  17241:                         if (exists($oldenv{'user.linkedenv'})) {
                   17242:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17243:                         }
1.1320    raeburn  17244:                         untie(%oldenv);
                   17245:                         if (unlink("$lonids/$filename")) {
                   17246:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17247:                                 if (-l "$lonids/$linkedfile.id") {
                   17248:                                     unlink("$lonids/$linkedfile.id");
                   17249:                                 }
1.1295    raeburn  17250:                             }
                   17251:                         }
                   17252:                     } else {
                   17253:                         unlink($lonids.'/'.$filename);
                   17254:                     }
1.463     albertel 17255: 		}
1.462     albertel 17256: 	    }
1.463     albertel 17257: 	    closedir(DIR);
1.1204    raeburn  17258: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17259:             my $namespace = 'nohist_courseeditor';
                   17260:             my $lockingkey = 'paste'."\0".'locked_num';
                   17261:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17262:                                                 $domain,$username);
                   17263:             if (exists($lockhash{$lockingkey})) {
                   17264:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17265:                 unless ($delresult eq 'ok') {
                   17266:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17267:                 }
                   17268:             }
1.462     albertel 17269: 	}
                   17270: # Give them a new cookie
1.463     albertel 17271: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17272: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17273: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17274:     
                   17275: # Initialize roles
                   17276: 
1.1062    raeburn  17277: 	($userroles,$firstaccenv,$timerintenv) = 
                   17278:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17279:     }
                   17280: # ------------------------------------ Check browser type and MathML capability
                   17281: 
1.1194    raeburn  17282:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17283:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17284: 
                   17285: # ------------------------------------------------------------- Get environment
                   17286: 
                   17287:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17288:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17289:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17290: 	undef(%userenv);
                   17291:     }
                   17292:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17293: 	$form->{'interface'}=$userenv{'interface'};
                   17294:     }
                   17295:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17296: 
                   17297: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17298:     foreach my $option ('interface','localpath','localres') {
                   17299:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17300:     }
                   17301: # --------------------------------------------------------- Write first profile
                   17302: 
                   17303:     {
1.1350    raeburn  17304:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17305: 	my %initial_env = 
                   17306: 	    ("user.name"          => $username,
                   17307: 	     "user.domain"        => $domain,
                   17308: 	     "user.home"          => $authhost,
                   17309: 	     "browser.type"       => $clientbrowser,
                   17310: 	     "browser.version"    => $clientversion,
                   17311: 	     "browser.mathml"     => $clientmathml,
                   17312: 	     "browser.unicode"    => $clientunicode,
                   17313: 	     "browser.os"         => $clientos,
1.1137    raeburn  17314:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17315:              "browser.info"       => $clientinfo,
1.1194    raeburn  17316:              "browser.osversion"  => $clientosversion,
1.462     albertel 17317: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17318: 	     "request.course.fn"  => '',
                   17319: 	     "request.course.uri" => '',
                   17320: 	     "request.course.sec" => '',
                   17321: 	     "request.role"       => 'cm',
                   17322: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17323: 	     "request.host"       => $ip,);
1.462     albertel 17324: 
                   17325:         if ($form->{'localpath'}) {
                   17326: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17327: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17328:         }
                   17329: 	
                   17330: 	if ($form->{'interface'}) {
                   17331: 	    $form->{'interface'}=~s/\W//gs;
                   17332: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17333: 	    $env{'browser.interface'}=$form->{'interface'};
                   17334: 	}
                   17335: 
1.1157    raeburn  17336:         if ($form->{'iptoken'}) {
                   17337:             my $lonhost = $r->dir_config('lonHostID');
                   17338:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17339:             $env{'user.noloadbalance'} = $lonhost;
                   17340:         }
                   17341: 
1.1268    raeburn  17342:         if ($form->{'noloadbalance'}) {
                   17343:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17344:             my $hosthere = $form->{'noloadbalance'};
                   17345:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17346:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17347:                 $env{'user.noloadbalance'} = $hosthere;
                   17348:             }
                   17349:         }
                   17350: 
1.1016    raeburn  17351:         unless ($domain eq 'public') {
1.1273    raeburn  17352:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17353:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17354: 
                   17355:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17356:                 $userenv{'availabletools.'.$tool} = 
                   17357:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17358:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17359:             }
1.980     raeburn  17360: 
1.1311    raeburn  17361:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17362:                 $userenv{'canrequest.'.$crstype} =
                   17363:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17364:                                                       'reload','requestcourses',
                   17365:                                                       \%userenv,\%domdef,\%is_adv);
                   17366:             }
1.724     raeburn  17367: 
1.1273    raeburn  17368:             $userenv{'canrequest.author'} =
                   17369:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17370:                                                   'reload','requestauthor',
1.980     raeburn  17371:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17372:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17373:                                                  $domain,$username);
                   17374:             my $reqstatus = $reqauthor{'author_status'};
                   17375:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17376:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17377:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17378:                                                       $reqauthor{'author'}{'timestamp'};
                   17379:                 }
1.1092    raeburn  17380:             }
1.1287    raeburn  17381:             my ($types,$typename) = &course_types();
                   17382:             if (ref($types) eq 'ARRAY') {
                   17383:                 my @options = ('approval','validate','autolimit');
                   17384:                 my $optregex = join('|',@options);
                   17385:                 my (%willtrust,%trustchecked);
                   17386:                 foreach my $type (@{$types}) {
                   17387:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17388:                     if ($dom_str ne '') {
                   17389:                         my $updatedstr = '';
                   17390:                         my @possdomains = split(',',$dom_str);
                   17391:                         foreach my $entry (@possdomains) {
                   17392:                             my ($extdom,$extopt) = split(':',$entry);
                   17393:                             unless ($trustchecked{$extdom}) {
                   17394:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17395:                                 $trustchecked{$extdom} = 1;
                   17396:                             }
                   17397:                             if ($willtrust{$extdom}) {
                   17398:                                 $updatedstr .= $entry.',';
                   17399:                             }
                   17400:                         }
                   17401:                         $updatedstr =~ s/,$//;
                   17402:                         if ($updatedstr) {
                   17403:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17404:                         } else {
                   17405:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17406:                         }
                   17407:                     }
                   17408:                 }
                   17409:             }
1.1092    raeburn  17410:         }
1.462     albertel 17411: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17412: 
1.462     albertel 17413: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17414: 		 &GDBM_WRCREAT(),0640)) {
                   17415: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17416: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17417: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17418:             if (ref($firstaccenv) eq 'HASH') {
                   17419:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17420:             }
                   17421:             if (ref($timerintenv) eq 'HASH') {
                   17422:                 &_add_to_env(\%disk_env,$timerintenv);
                   17423:             }
1.463     albertel 17424: 	    if (ref($args->{'extra_env'})) {
                   17425: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17426: 	    }
1.462     albertel 17427: 	    untie(%disk_env);
                   17428: 	} else {
1.705     tempelho 17429: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17430: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17431: 	    return 'error: '.$!;
                   17432: 	}
                   17433:     }
                   17434:     $env{'request.role'}='cm';
                   17435:     $env{'request.role.adv'}=$env{'user.adv'};
                   17436:     $env{'browser.type'}=$clientbrowser;
                   17437: 
                   17438:     return $cookie;
                   17439: 
                   17440: }
                   17441: 
                   17442: sub _add_to_env {
                   17443:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17444:     if (ref($env_data) eq 'HASH') {
                   17445:         while (my ($key,$value) = each(%$env_data)) {
                   17446: 	    $idf->{$prefix.$key} = $value;
                   17447: 	    $env{$prefix.$key}   = $value;
                   17448:         }
1.462     albertel 17449:     }
                   17450: }
                   17451: 
1.685     tempelho 17452: # --- Get the symbolic name of a problem and the url
                   17453: sub get_symb {
                   17454:     my ($request,$silent) = @_;
1.726     raeburn  17455:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17456:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17457:     if ($symb eq '') {
                   17458:         if (!$silent) {
1.1071    raeburn  17459:             if (ref($request)) { 
                   17460:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17461:             }
1.685     tempelho 17462:             return ();
                   17463:         }
                   17464:     }
                   17465:     &Apache::lonenc::check_decrypt(\$symb);
                   17466:     return ($symb);
                   17467: }
                   17468: 
                   17469: # --------------------------------------------------------------Get annotation
                   17470: 
                   17471: sub get_annotation {
                   17472:     my ($symb,$enc) = @_;
                   17473: 
                   17474:     my $key = $symb;
                   17475:     if (!$enc) {
                   17476:         $key =
                   17477:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17478:     }
                   17479:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17480:     return $annotation{$key};
                   17481: }
                   17482: 
                   17483: sub clean_symb {
1.731     raeburn  17484:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17485: 
                   17486:     &Apache::lonenc::check_decrypt(\$symb);
                   17487:     my $enc = $env{'request.enc'};
1.731     raeburn  17488:     if ($delete_enc) {
1.730     raeburn  17489:         delete($env{'request.enc'});
                   17490:     }
1.685     tempelho 17491: 
                   17492:     return ($symb,$enc);
                   17493: }
1.462     albertel 17494: 
1.1181    raeburn  17495: ############################################################
                   17496: ############################################################
                   17497: 
                   17498: =pod
                   17499: 
                   17500: =head1 Routines for building display used to search for courses
                   17501: 
                   17502: 
                   17503: =over 4
                   17504: 
                   17505: =item * &build_filters()
                   17506: 
                   17507: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17508: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17509: and quotacheck.pl
                   17510: 
1.1181    raeburn  17511: 
                   17512: Inputs:
                   17513: 
                   17514: filterlist - anonymous array of fields to include as potential filters 
                   17515: 
                   17516: crstype - course type
                   17517: 
                   17518: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17519:               to pop-open a course selector (will contain "extra element"). 
                   17520: 
                   17521: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17522: 
                   17523: filter - anonymous hash of criteria and their values
                   17524: 
                   17525: action - form action
                   17526: 
                   17527: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17528: 
1.1182    raeburn  17529: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17530: 
                   17531: cloneruname - username of owner of new course who wants to clone
                   17532: 
                   17533: clonerudom - domain of owner of new course who wants to clone
                   17534: 
                   17535: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17536: 
                   17537: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17538: 
                   17539: codedom - domain
                   17540: 
                   17541: formname - value of form element named "form". 
                   17542: 
                   17543: fixeddom - domain, if fixed.
                   17544: 
                   17545: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17546: 
                   17547: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17548: 
                   17549: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17550: 
                   17551: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17552: 
                   17553: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17554: 
                   17555: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17556: 
                   17557: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17558: 
1.1182    raeburn  17559: 
1.1181    raeburn  17560: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17561: 
1.1182    raeburn  17562: 
1.1181    raeburn  17563: Side Effects: None
                   17564: 
                   17565: =cut
                   17566: 
                   17567: # ---------------------------------------------- search for courses based on last activity etc.
                   17568: 
                   17569: sub build_filters {
                   17570:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17571:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17572:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17573:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17574:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17575:     my ($list,$jscript);
1.1181    raeburn  17576:     my $onchange = 'javascript:updateFilters(this)';
                   17577:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17578:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17579:         $typeselectform,$instcodetitle);
                   17580:     if ($formname eq '') {
                   17581:         $formname = $caller;
                   17582:     }
                   17583:     foreach my $item (@{$filterlist}) {
                   17584:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17585:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17586:             if ($item eq 'domainfilter') {
                   17587:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17588:             } elsif ($item eq 'coursefilter') {
                   17589:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17590:             } elsif ($item eq 'ownerfilter') {
                   17591:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17592:             } elsif ($item eq 'ownerdomfilter') {
                   17593:                 $filter->{'ownerdomfilter'} =
                   17594:                     &LONCAPA::clean_domain($filter->{$item});
                   17595:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17596:                                                        'ownerdomfilter',1);
                   17597:             } elsif ($item eq 'personfilter') {
                   17598:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17599:             } elsif ($item eq 'persondomfilter') {
                   17600:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17601:                                                         'persondomfilter',1);
                   17602:             } else {
                   17603:                 $filter->{$item} =~ s/\W//g;
                   17604:             }
                   17605:             if (!$filter->{$item}) {
                   17606:                 $filter->{$item} = '';
                   17607:             }
                   17608:         }
                   17609:         if ($item eq 'domainfilter') {
                   17610:             my $allow_blank = 1;
                   17611:             if ($formname eq 'portform') {
                   17612:                 $allow_blank=0;
                   17613:             } elsif ($formname eq 'studentform') {
                   17614:                 $allow_blank=0;
                   17615:             }
                   17616:             if ($fixeddom) {
                   17617:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17618:                                     ' value="'.$codedom.'" />'.
                   17619:                                     &Apache::lonnet::domain($codedom,'description');
                   17620:             } else {
                   17621:                 $domainselectform = &select_dom_form($filter->{$item},
                   17622:                                                      'domainfilter',
                   17623:                                                       $allow_blank,'',$onchange);
                   17624:             }
                   17625:         } else {
                   17626:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17627:         }
                   17628:     }
                   17629: 
                   17630:     # last course activity filter and selection
                   17631:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17632: 
                   17633:     # course created filter and selection
                   17634:     if (exists($filter->{'createdfilter'})) {
                   17635:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17636:     }
                   17637: 
1.1239    raeburn  17638:     my $prefix = $crstype;
                   17639:     if ($crstype eq 'Placement') {
                   17640:         $prefix = 'Placement Test'
                   17641:     }
1.1181    raeburn  17642:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17643:                 'cac' => "$prefix Activity",
                   17644:                 'ccr' => "$prefix Created",
                   17645:                 'cde' => "$prefix Title",
                   17646:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17647:                 'ins' => 'Institutional Code',
                   17648:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17649:                 'cow' => "$prefix Owner/Co-owner",
                   17650:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17651:                 'cog' => 'Type',
                   17652:              );
                   17653: 
                   17654:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17655:         my $typeval = 'Course';
                   17656:         if ($crstype eq 'Community') {
                   17657:             $typeval = 'Community';
1.1239    raeburn  17658:         } elsif ($crstype eq 'Placement') {
                   17659:             $typeval = 'Placement';
1.1181    raeburn  17660:         }
                   17661:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17662:     } else {
                   17663:         $typeselectform =  '<select name="type" size="1"';
                   17664:         if ($onchange) {
                   17665:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17666:         }
                   17667:         $typeselectform .= '>'."\n";
1.1237    raeburn  17668:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17669:             my $shown;
                   17670:             if ($posstype eq 'Placement') {
                   17671:                 $shown = &mt('Placement Test');
                   17672:             } else {
                   17673:                 $shown = &mt($posstype);
                   17674:             }
1.1181    raeburn  17675:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17676:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17677:         }
                   17678:         $typeselectform.="</select>";
                   17679:     }
                   17680: 
                   17681:     my ($cloneableonlyform,$cloneabletitle);
                   17682:     if (exists($filter->{'cloneableonly'})) {
                   17683:         my $cloneableon = '';
                   17684:         my $cloneableoff = ' checked="checked"';
                   17685:         if ($filter->{'cloneableonly'}) {
                   17686:             $cloneableon = $cloneableoff;
                   17687:             $cloneableoff = '';
                   17688:         }
                   17689:         $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>';
                   17690:         if ($formname eq 'ccrs') {
1.1187    bisitz   17691:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17692:         } else {
                   17693:             $cloneabletitle = &mt('Cloneable by you');
                   17694:         }
                   17695:     }
                   17696:     my $officialjs;
                   17697:     if ($crstype eq 'Course') {
                   17698:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17699: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17700: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17701:             if ($codedom) { 
1.1181    raeburn  17702:                 $officialjs = 1;
                   17703:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17704:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17705:                                                                   $officialjs,$codetitlesref);
                   17706:                 if ($jscript) {
1.1182    raeburn  17707:                     $jscript = '<script type="text/javascript">'."\n".
                   17708:                                '// <![CDATA['."\n".
                   17709:                                $jscript."\n".
                   17710:                                '// ]]>'."\n".
                   17711:                                '</script>'."\n";
1.1181    raeburn  17712:                 }
                   17713:             }
                   17714:             if ($instcodeform eq '') {
                   17715:                 $instcodeform =
                   17716:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17717:                     $list->{'instcodefilter'}.'" />';
                   17718:                 $instcodetitle = $lt{'ins'};
                   17719:             } else {
                   17720:                 $instcodetitle = $lt{'inc'};
                   17721:             }
                   17722:             if ($fixeddom) {
                   17723:                 $instcodetitle .= '<br />('.$codedom.')';
                   17724:             }
                   17725:         }
                   17726:     }
                   17727:     my $output = qq|
                   17728: <form method="post" name="filterpicker" action="$action">
                   17729: <input type="hidden" name="form" value="$formname" />
                   17730: |;
                   17731:     if ($formname eq 'modifycourse') {
                   17732:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17733:                    '<input type="hidden" name="prevphase" value="'.
                   17734:                    $prevphase.'" />'."\n";
1.1198    musolffc 17735:     } elsif ($formname eq 'quotacheck') {
                   17736:         $output .= qq|
                   17737: <input type="hidden" name="sortby" value="" />
                   17738: <input type="hidden" name="sortorder" value="" />
                   17739: |;
                   17740:     } else {
1.1181    raeburn  17741:         my $name_input;
                   17742:         if ($cnameelement ne '') {
                   17743:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17744:                           $cnameelement.'" />';
                   17745:         }
                   17746:         $output .= qq|
1.1182    raeburn  17747: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17748: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17749: $name_input
                   17750: $roleelement
                   17751: $multelement
                   17752: $typeelement
                   17753: |;
                   17754:         if ($formname eq 'portform') {
                   17755:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17756:         }
                   17757:     }
                   17758:     if ($fixeddom) {
                   17759:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17760:     }
                   17761:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17762:     if ($sincefilterform) {
                   17763:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17764:                   .$sincefilterform
                   17765:                   .&Apache::lonhtmlcommon::row_closure();
                   17766:     }
                   17767:     if ($createdfilterform) {
                   17768:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17769:                   .$createdfilterform
                   17770:                   .&Apache::lonhtmlcommon::row_closure();
                   17771:     }
                   17772:     if ($domainselectform) {
                   17773:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17774:                   .$domainselectform
                   17775:                   .&Apache::lonhtmlcommon::row_closure();
                   17776:     }
                   17777:     if ($typeselectform) {
                   17778:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17779:             $output .= $typeselectform;
                   17780:         } else {
                   17781:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17782:                       .$typeselectform
                   17783:                       .&Apache::lonhtmlcommon::row_closure();
                   17784:         }
                   17785:     }
                   17786:     if ($instcodeform) {
                   17787:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17788:                   .$instcodeform
                   17789:                   .&Apache::lonhtmlcommon::row_closure();
                   17790:     }
                   17791:     if (exists($filter->{'ownerfilter'})) {
                   17792:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17793:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17794:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17795:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17796:                    $ownerdomselectform.'</td></tr></table>'.
                   17797:                    &Apache::lonhtmlcommon::row_closure();
                   17798:     }
                   17799:     if (exists($filter->{'personfilter'})) {
                   17800:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17801:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17802:                    '<input type="text" name="personfilter" size="20" value="'.
                   17803:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17804:                    $persondomselectform.'</td></tr></table>'.
                   17805:                    &Apache::lonhtmlcommon::row_closure();
                   17806:     }
                   17807:     if (exists($filter->{'coursefilter'})) {
                   17808:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17809:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17810:                   .$list->{'coursefilter'}.'" />'
                   17811:                   .&Apache::lonhtmlcommon::row_closure();
                   17812:     }
                   17813:     if ($cloneableonlyform) {
                   17814:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17815:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17816:     }
                   17817:     if (exists($filter->{'descriptfilter'})) {
                   17818:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17819:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17820:                   .$list->{'descriptfilter'}.'" />'
                   17821:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17822:     }
                   17823:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17824:                '<input type="hidden" name="updater" value="" />'."\n".
                   17825:                '<input type="submit" name="gosearch" value="'.
                   17826:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17827:     return $jscript.$clonewarning.$output;
                   17828: }
                   17829: 
                   17830: =pod 
                   17831: 
                   17832: =item * &timebased_select_form()
                   17833: 
1.1182    raeburn  17834: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17835: filter e.g., Course Activity, Course Created, when searching for courses
                   17836: or communities
                   17837: 
                   17838: Inputs:
                   17839: 
                   17840: item - name of form element (sincefilter or createdfilter)
                   17841: 
                   17842: filter - anonymous hash of criteria and their values
                   17843: 
                   17844: Returns: HTML for a select box contained a blank, then six time selections,
                   17845:          with value set in incoming form variables currently selected. 
                   17846: 
                   17847: Side Effects: None
                   17848: 
                   17849: =cut
                   17850: 
                   17851: sub timebased_select_form {
                   17852:     my ($item,$filter) = @_;
                   17853:     if (ref($filter) eq 'HASH') {
                   17854:         $filter->{$item} =~ s/[^\d-]//g;
                   17855:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17856:         return &select_form(
                   17857:                             $filter->{$item},
                   17858:                             $item,
                   17859:                             {      '-1' => '',
                   17860:                                 '86400' => &mt('today'),
                   17861:                                '604800' => &mt('last week'),
                   17862:                               '2592000' => &mt('last month'),
                   17863:                               '7776000' => &mt('last three months'),
                   17864:                              '15552000' => &mt('last six months'),
                   17865:                              '31104000' => &mt('last year'),
                   17866:                     'select_form_order' =>
                   17867:                            ['-1','86400','604800','2592000','7776000',
                   17868:                             '15552000','31104000']});
                   17869:     }
                   17870: }
                   17871: 
                   17872: =pod
                   17873: 
                   17874: =item * &js_changer()
                   17875: 
                   17876: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17877: when course type or domain is changed, and also to hide 'Searching ...' on
                   17878: page load completion for page showing search result.
1.1181    raeburn  17879: 
                   17880: Inputs: None
                   17881: 
1.1183    raeburn  17882: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17883: 
                   17884: Side Effects: None
                   17885: 
                   17886: =cut
                   17887: 
                   17888: sub js_changer {
                   17889:     return <<ENDJS;
                   17890: <script type="text/javascript">
                   17891: // <![CDATA[
                   17892: function updateFilters(caller) {
                   17893:     if (typeof(caller) != "undefined") {
                   17894:         document.filterpicker.updater.value = caller.name;
                   17895:     }
                   17896:     document.filterpicker.submit();
                   17897: }
1.1183    raeburn  17898: 
                   17899: function hideSearching() {
                   17900:     if (document.getElementById('searching')) {
                   17901:         document.getElementById('searching').style.display = 'none';
                   17902:     }
                   17903:     return;
                   17904: }
                   17905: 
1.1181    raeburn  17906: // ]]>
                   17907: </script>
                   17908: 
                   17909: ENDJS
                   17910: }
                   17911: 
                   17912: =pod
                   17913: 
1.1182    raeburn  17914: =item * &search_courses()
                   17915: 
                   17916: Process selected filters form course search form and pass to lonnet::courseiddump
                   17917: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17918: 
                   17919: Inputs:
                   17920: 
                   17921: dom - domain being searched 
                   17922: 
                   17923: type - course type ('Course' or 'Community' or '.' if any).
                   17924: 
                   17925: filter - anonymous hash of criteria and their values
                   17926: 
                   17927: numtitles - for institutional codes - number of categories
                   17928: 
                   17929: cloneruname - optional username of new course owner
                   17930: 
                   17931: clonerudom - optional domain of new course owner
                   17932: 
1.1221    raeburn  17933: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17934:             (used when DC is using course creation form)
                   17935: 
                   17936: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17937: 
1.1221    raeburn  17938: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17939:            (and so can clone automatically)
                   17940: 
                   17941: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17942: 
                   17943: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17944:               courses to clone 
1.1182    raeburn  17945: 
                   17946: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17947: 
                   17948: 
                   17949: Side Effects: None
                   17950: 
                   17951: =cut
                   17952: 
                   17953: 
                   17954: sub search_courses {
1.1221    raeburn  17955:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17956:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17957:     my (%courses,%showcourses,$cloner);
                   17958:     if (($filter->{'ownerfilter'} ne '') ||
                   17959:         ($filter->{'ownerdomfilter'} ne '')) {
                   17960:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17961:                                        $filter->{'ownerdomfilter'};
                   17962:     }
                   17963:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17964:         if (!$filter->{$item}) {
                   17965:             $filter->{$item}='.';
                   17966:         }
                   17967:     }
                   17968:     my $now = time;
                   17969:     my $timefilter =
                   17970:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17971:     my ($createdbefore,$createdafter);
                   17972:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17973:         $createdbefore = $now;
                   17974:         $createdafter = $now-$filter->{'createdfilter'};
                   17975:     }
                   17976:     my ($instcodefilter,$regexpok);
                   17977:     if ($numtitles) {
                   17978:         if ($env{'form.official'} eq 'on') {
                   17979:             $instcodefilter =
                   17980:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17981:             $regexpok = 1;
                   17982:         } elsif ($env{'form.official'} eq 'off') {
                   17983:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17984:             unless ($instcodefilter eq '') {
                   17985:                 $regexpok = -1;
                   17986:             }
                   17987:         }
                   17988:     } else {
                   17989:         $instcodefilter = $filter->{'instcodefilter'};
                   17990:     }
                   17991:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17992:     if ($type eq '') { $type = '.'; }
                   17993: 
                   17994:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17995:         $cloner = $cloneruname.':'.$clonerudom;
                   17996:     }
                   17997:     %courses = &Apache::lonnet::courseiddump($dom,
                   17998:                                              $filter->{'descriptfilter'},
                   17999:                                              $timefilter,
                   18000:                                              $instcodefilter,
                   18001:                                              $filter->{'combownerfilter'},
                   18002:                                              $filter->{'coursefilter'},
                   18003:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18004:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18005:                                              $filter->{'cloneableonly'},
                   18006:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18007:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18008:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18009:         my $ccrole;
                   18010:         if ($type eq 'Community') {
                   18011:             $ccrole = 'co';
                   18012:         } else {
                   18013:             $ccrole = 'cc';
                   18014:         }
                   18015:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18016:                                                      $filter->{'persondomfilter'},
                   18017:                                                      'userroles',undef,
                   18018:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18019:                                                      $dom);
                   18020:         foreach my $role (keys(%rolehash)) {
                   18021:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18022:             my $cid = $cdom.'_'.$cnum;
                   18023:             if (exists($courses{$cid})) {
                   18024:                 if (ref($courses{$cid}) eq 'HASH') {
                   18025:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18026:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18027:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18028:                         }
                   18029:                     } else {
                   18030:                         $courses{$cid}{roles} = [$courserole];
                   18031:                     }
                   18032:                     $showcourses{$cid} = $courses{$cid};
                   18033:                 }
                   18034:             }
                   18035:         }
                   18036:         %courses = %showcourses;
                   18037:     }
                   18038:     return %courses;
                   18039: }
                   18040: 
                   18041: =pod
                   18042: 
1.1181    raeburn  18043: =back
                   18044: 
1.1207    raeburn  18045: =head1 Routines for version requirements for current course.
                   18046: 
                   18047: =over 4
                   18048: 
                   18049: =item * &check_release_required()
                   18050: 
                   18051: Compares required LON-CAPA version with version on server, and
                   18052: if required version is newer looks for a server with the required version.
                   18053: 
                   18054: Looks first at servers in user's owen domain; if none suitable, looks at
                   18055: servers in course's domain are permitted to host sessions for user's domain.
                   18056: 
                   18057: Inputs:
                   18058: 
                   18059: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18060: 
                   18061: $courseid - Course ID of current course
                   18062: 
                   18063: $rolecode - User's current role in course (for switchserver query string).
                   18064: 
                   18065: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18066: 
                   18067: 
                   18068: Returns:
                   18069: 
                   18070: $switchserver - query string tp append to /adm/switchserver call (if 
                   18071:                 current server's LON-CAPA version is too old. 
                   18072: 
                   18073: $warning - Message is displayed if no suitable server could be found.
                   18074: 
                   18075: =cut
                   18076: 
                   18077: sub check_release_required {
                   18078:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18079:     my ($switchserver,$warning);
                   18080:     if ($required ne '') {
                   18081:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18082:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18083:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18084:             my $otherserver;
                   18085:             if (($major eq '' && $minor eq '') ||
                   18086:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18087:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18088:                 my $switchlcrev =
                   18089:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18090:                                                            $userdomserver);
                   18091:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18092:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18093:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18094:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18095:                     if ($cdom ne $env{'user.domain'}) {
                   18096:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18097:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18098:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18099:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18100:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18101:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18102:                         my $canhost =
                   18103:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18104:                                                               $coursedomserver,
                   18105:                                                               $remoterev,
                   18106:                                                               $udomdefaults{'remotesessions'},
                   18107:                                                               $defdomdefaults{'hostedsessions'});
                   18108: 
                   18109:                         if ($canhost) {
                   18110:                             $otherserver = $coursedomserver;
                   18111:                         } else {
                   18112:                             $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.");
                   18113:                         }
                   18114:                     } else {
                   18115:                         $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).");
                   18116:                     }
                   18117:                 } else {
                   18118:                     $otherserver = $userdomserver;
                   18119:                 }
                   18120:             }
                   18121:             if ($otherserver ne '') {
                   18122:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18123:             }
                   18124:         }
                   18125:     }
                   18126:     return ($switchserver,$warning);
                   18127: }
                   18128: 
                   18129: =pod
                   18130: 
                   18131: =item * &check_release_result()
                   18132: 
                   18133: Inputs:
                   18134: 
                   18135: $switchwarning - Warning message if no suitable server found to host session.
                   18136: 
                   18137: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18138:                 and current role.
                   18139: 
                   18140: Returns: HTML to display with information about requirement to switch server.
                   18141:          Either displaying warning with link to Roles/Courses screen or
                   18142:          display link to switchserver.
                   18143: 
1.1181    raeburn  18144: =cut
                   18145: 
1.1207    raeburn  18146: sub check_release_result {
                   18147:     my ($switchwarning,$switchserver) = @_;
                   18148:     my $output = &start_page('Selected course unavailable on this server').
                   18149:                  '<p class="LC_warning">';
                   18150:     if ($switchwarning) {
                   18151:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18152:         if (&show_course()) {
                   18153:             $output .= &mt('Display courses');
                   18154:         } else {
                   18155:             $output .= &mt('Display roles');
                   18156:         }
                   18157:         $output .= '</a>';
                   18158:     } elsif ($switchserver) {
                   18159:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18160:                    '<br />'.
                   18161:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18162:                    &mt('Switch Server').
                   18163:                    '</a>';
                   18164:     }
                   18165:     $output .= '</p>'.&end_page();
                   18166:     return $output;
                   18167: }
                   18168: 
                   18169: =pod
                   18170: 
                   18171: =item * &needs_coursereinit()
                   18172: 
                   18173: Determine if course contents stored for user's session needs to be
                   18174: refreshed, because content has changed since "Big Hash" last tied.
                   18175: 
                   18176: Check for change is made if time last checked is more than 10 minutes ago
                   18177: (by default).
                   18178: 
                   18179: Inputs:
                   18180: 
                   18181: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18182: 
                   18183: $interval (optional) - Time which may elapse (in s) between last check for content
                   18184:                        change in current course. (default: 600 s).  
                   18185: 
                   18186: Returns: an array; first element is:
                   18187: 
                   18188: =over 4
                   18189: 
                   18190: 'switch' - if content updates mean user's session
                   18191:            needs to be switched to a server running a newer LON-CAPA version
                   18192:  
                   18193: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18194:            on current server hosting user's session                
                   18195: 
                   18196: ''       - if no action required.
                   18197: 
                   18198: =back
                   18199: 
                   18200: If first item element is 'switch':
                   18201: 
                   18202: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18203: 
                   18204: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18205:                               and current role. 
                   18206: 
                   18207: otherwise: no other elements returned.
                   18208: 
                   18209: =back
                   18210: 
                   18211: =cut
                   18212: 
                   18213: sub needs_coursereinit {
                   18214:     my ($loncaparev,$interval) = @_;
                   18215:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18216:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18217:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18218:     my $now = time;
                   18219:     if ($interval eq '') {
                   18220:         $interval = 600;
                   18221:     }
                   18222:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18223:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18224:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18225:         if ($blocked) {
                   18226:             return ();
                   18227:         }
1.1207    raeburn  18228:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18229:         if ($lastchange > $env{'request.course.tied'}) {
                   18230:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18231:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18232:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18233:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18234:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18235:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   18236:                     my ($switchserver,$switchwarning) =
                   18237:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18238:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   18239:                     if ($switchwarning ne '' || $switchserver ne '') {
                   18240:                         return ('switch',$switchwarning,$switchserver);
                   18241:                     }
                   18242:                 }
                   18243:             }
                   18244:             return ('update');
                   18245:         }
                   18246:     }
                   18247:     return ();
                   18248: }
1.1181    raeburn  18249: 
1.1083    raeburn  18250: sub update_content_constraints {
1.1326    raeburn  18251:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  18252:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18253:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18254:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18255:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18256:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18257:         if ($item eq 'resourcetag') {
                   18258:             if ($name eq 'responsetype') {
                   18259:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18260:             }
1.1307    raeburn  18261:         } elsif ($item eq 'course') {
                   18262:             if ($name eq 'courserestype') {
                   18263:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18264:             }
1.1083    raeburn  18265:         }
                   18266:     }
                   18267:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18268:     if (defined($navmap)) {
1.1307    raeburn  18269:         my (%allresponses,%allcrsrestypes);
                   18270:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18271:             if ($res->is_tool()) {
                   18272:                 if ($allcrsrestypes{'exttool'}) {
                   18273:                     $allcrsrestypes{'exttool'} ++;
                   18274:                 } else {
                   18275:                     $allcrsrestypes{'exttool'} = 1;
                   18276:                 }
                   18277:                 next;
                   18278:             }
1.1083    raeburn  18279:             my %responses = $res->responseTypes();
                   18280:             foreach my $key (keys(%responses)) {
                   18281:                 next unless(exists($checkresponsetypes{$key}));
                   18282:                 $allresponses{$key} += $responses{$key};
                   18283:             }
                   18284:         }
                   18285:         foreach my $key (keys(%allresponses)) {
                   18286:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18287:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18288:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18289:             }
                   18290:         }
1.1307    raeburn  18291:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18292:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18293:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18294:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18295:             }
                   18296:         }
1.1083    raeburn  18297:         undef($navmap);
                   18298:     }
1.1326    raeburn  18299:     my (@resources,@order,@resparms,@zombies);
                   18300:     if ($keeporder) {
                   18301:         use LONCAPA::map;
                   18302:         @resources = @LONCAPA::map::resources;
                   18303:         @order = @LONCAPA::map::order;
                   18304:         @resparms = @LONCAPA::map::resparms;
                   18305:         @zombies = @LONCAPA::map::zombies;
                   18306:     }
1.1308    raeburn  18307:     my $suppmap = 'supplemental.sequence';
                   18308:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18309:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18310:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18311:     if ($keeporder) {
                   18312:         @LONCAPA::map::resources = @resources;
                   18313:         @LONCAPA::map::order = @order;
                   18314:         @LONCAPA::map::resparms = @resparms;
                   18315:         @LONCAPA::map::zombies = @zombies;
                   18316:     }
1.1308    raeburn  18317:     if ($supptools) {
                   18318:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18319:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18320:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18321:         }
                   18322:     }
1.1083    raeburn  18323:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18324:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18325:     }
                   18326:     return;
                   18327: }
                   18328: 
1.1110    raeburn  18329: sub allmaps_incourse {
                   18330:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18331:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18332:         $cid = $env{'request.course.id'};
                   18333:         $cdom = $env{'course.'.$cid.'.domain'};
                   18334:         $cnum = $env{'course.'.$cid.'.num'};
                   18335:         $chome = $env{'course.'.$cid.'.home'};
                   18336:     }
                   18337:     my %allmaps = ();
                   18338:     my $lastchange =
                   18339:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18340:     if ($lastchange > $env{'request.course.tied'}) {
                   18341:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18342:         unless ($ferr) {
1.1326    raeburn  18343:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18344:         }
                   18345:     }
                   18346:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18347:     if (defined($navmap)) {
                   18348:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18349:             $allmaps{$res->src()} = 1;
                   18350:         }
                   18351:     }
                   18352:     return \%allmaps;
                   18353: }
                   18354: 
1.1083    raeburn  18355: sub parse_supplemental_title {
                   18356:     my ($title) = @_;
                   18357: 
                   18358:     my ($foldertitle,$renametitle);
                   18359:     if ($title =~ /&amp;&amp;&amp;/) {
                   18360:         $title = &HTML::Entites::decode($title);
                   18361:     }
                   18362:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18363:         $renametitle=$4;
                   18364:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18365:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18366:         my $name =  &plainname($uname,$udom);
                   18367:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18368:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18369:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18370:             $name.': <br />'.$foldertitle;
                   18371:     }
                   18372:     if (wantarray) {
                   18373:         return ($title,$foldertitle,$renametitle);
                   18374:     }
                   18375:     return $title;
                   18376: }
                   18377: 
1.1143    raeburn  18378: sub recurse_supplemental {
1.1308    raeburn  18379:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18380:     if ($suppmap) {
                   18381:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18382:         if ($fatal) {
                   18383:             $errors ++;
                   18384:         } else {
                   18385:             if ($#LONCAPA::map::resources > 0) {
                   18386:                 foreach my $res (@LONCAPA::map::resources) {
                   18387:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18388:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18389:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18390:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18391:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18392:                         } else {
1.1308    raeburn  18393:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18394:                                 $numexttools ++;
                   18395:                             }
1.1143    raeburn  18396:                             $numfiles ++;
                   18397:                         }
                   18398:                     }
                   18399:                 }
                   18400:             }
                   18401:         }
                   18402:     }
1.1308    raeburn  18403:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18404: }
                   18405: 
1.1101    raeburn  18406: sub symb_to_docspath {
1.1267    raeburn  18407:     my ($symb,$navmapref) = @_;
                   18408:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18409:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18410:     if ($resurl=~/\.(sequence|page)$/) {
                   18411:         $mapurl=$resurl;
                   18412:     } elsif ($resurl eq 'adm/navmaps') {
                   18413:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18414:     }
                   18415:     my $mapresobj;
1.1267    raeburn  18416:     unless (ref($$navmapref)) {
                   18417:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18418:     }
                   18419:     if (ref($$navmapref)) {
                   18420:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18421:     }
                   18422:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18423:     my $type=$2;
                   18424:     my $path;
                   18425:     if (ref($mapresobj)) {
                   18426:         my $pcslist = $mapresobj->map_hierarchy();
                   18427:         if ($pcslist ne '') {
                   18428:             foreach my $pc (split(/,/,$pcslist)) {
                   18429:                 next if ($pc <= 1);
1.1267    raeburn  18430:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18431:                 if (ref($res)) {
                   18432:                     my $thisurl = $res->src();
                   18433:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18434:                     my $thistitle = $res->title();
                   18435:                     $path .= '&'.
                   18436:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18437:                              &escape($thistitle).
1.1101    raeburn  18438:                              ':'.$res->randompick().
                   18439:                              ':'.$res->randomout().
                   18440:                              ':'.$res->encrypted().
                   18441:                              ':'.$res->randomorder().
                   18442:                              ':'.$res->is_page();
                   18443:                 }
                   18444:             }
                   18445:         }
                   18446:         $path =~ s/^\&//;
                   18447:         my $maptitle = $mapresobj->title();
                   18448:         if ($mapurl eq 'default') {
1.1129    raeburn  18449:             $maptitle = 'Main Content';
1.1101    raeburn  18450:         }
                   18451:         $path .= (($path ne '')? '&' : '').
                   18452:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18453:                  &escape($maptitle).
1.1101    raeburn  18454:                  ':'.$mapresobj->randompick().
                   18455:                  ':'.$mapresobj->randomout().
                   18456:                  ':'.$mapresobj->encrypted().
                   18457:                  ':'.$mapresobj->randomorder().
                   18458:                  ':'.$mapresobj->is_page();
                   18459:     } else {
                   18460:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18461:         my $ispage = (($type eq 'page')? 1 : '');
                   18462:         if ($mapurl eq 'default') {
1.1129    raeburn  18463:             $maptitle = 'Main Content';
1.1101    raeburn  18464:         }
                   18465:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18466:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18467:     }
                   18468:     unless ($mapurl eq 'default') {
                   18469:         $path = 'default&'.
1.1146    raeburn  18470:                 &escape('Main Content').
1.1101    raeburn  18471:                 ':::::&'.$path;
                   18472:     }
                   18473:     return $path;
                   18474: }
                   18475: 
1.1094    raeburn  18476: sub captcha_display {
1.1327    raeburn  18477:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18478:     my ($output,$error);
1.1234    raeburn  18479:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18480:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18481:     if ($captcha eq 'original') {
1.1094    raeburn  18482:         $output = &create_captcha();
                   18483:         unless ($output) {
1.1172    raeburn  18484:             $error = 'captcha';
1.1094    raeburn  18485:         }
                   18486:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18487:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18488:         unless ($output) {
1.1172    raeburn  18489:             $error = 'recaptcha';
1.1094    raeburn  18490:         }
                   18491:     }
1.1234    raeburn  18492:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18493: }
                   18494: 
                   18495: sub captcha_response {
1.1327    raeburn  18496:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18497:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18498:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18499:     if ($captcha eq 'original') {
1.1094    raeburn  18500:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18501:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18502:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18503:     } else {
                   18504:         $captcha_chk = 1;
                   18505:     }
                   18506:     return ($captcha_chk,$captcha_error);
                   18507: }
                   18508: 
                   18509: sub get_captcha_config {
1.1327    raeburn  18510:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18511:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18512:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18513:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18514:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18515:     if ($context eq 'usercreation') {
                   18516:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18517:         if (ref($domconfig{$context}) eq 'HASH') {
                   18518:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18519:             if (ref($hashtocheck) eq 'HASH') {
                   18520:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18521:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18522:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18523:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18524:                     }
                   18525:                     if ($privkey && $pubkey) {
                   18526:                         $captcha = 'recaptcha';
1.1234    raeburn  18527:                         $version = $hashtocheck->{'recaptchaversion'};
                   18528:                         if ($version ne '2') {
                   18529:                             $version = 1;
                   18530:                         }
1.1095    raeburn  18531:                     } else {
                   18532:                         $captcha = 'original';
                   18533:                     }
                   18534:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18535:                     $captcha = 'original';
                   18536:                 }
1.1094    raeburn  18537:             }
1.1095    raeburn  18538:         } else {
                   18539:             $captcha = 'captcha';
                   18540:         }
                   18541:     } elsif ($context eq 'login') {
                   18542:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18543:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18544:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18545:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18546:             if ($privkey && $pubkey) {
                   18547:                 $captcha = 'recaptcha';
1.1234    raeburn  18548:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18549:                 if ($version ne '2') {
                   18550:                     $version = 1; 
                   18551:                 }
1.1095    raeburn  18552:             } else {
                   18553:                 $captcha = 'original';
1.1094    raeburn  18554:             }
1.1095    raeburn  18555:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18556:             $captcha = 'original';
1.1094    raeburn  18557:         }
1.1327    raeburn  18558:     } elsif ($context eq 'passwords') {
                   18559:         if ($dom_in_effect) {
                   18560:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18561:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18562:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18563:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18564:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18565:                 }
                   18566:                 if ($privkey && $pubkey) {
                   18567:                     $captcha = 'recaptcha';
                   18568:                     $version = $passwdconf{'recaptchaversion'};
                   18569:                     if ($version ne '2') {
                   18570:                         $version = 1;
                   18571:                     }
                   18572:                 } else {
                   18573:                     $captcha = 'original';
                   18574:                 }
                   18575:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18576:                 $captcha = 'original';
                   18577:             }
                   18578:         }
                   18579:     } 
1.1234    raeburn  18580:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18581: }
                   18582: 
                   18583: sub create_captcha {
                   18584:     my %captcha_params = &captcha_settings();
                   18585:     my ($output,$maxtries,$tries) = ('',10,0);
                   18586:     while ($tries < $maxtries) {
                   18587:         $tries ++;
                   18588:         my $captcha = Authen::Captcha->new (
                   18589:                                            output_folder => $captcha_params{'output_dir'},
                   18590:                                            data_folder   => $captcha_params{'db_dir'},
                   18591:                                           );
                   18592:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18593: 
                   18594:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18595:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18596:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18597:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18598:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18599:                       '</span><br />'.
1.1176    raeburn  18600:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18601:             last;
                   18602:         }
                   18603:     }
1.1323    raeburn  18604:     if ($output eq '') {
                   18605:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18606:     }
1.1094    raeburn  18607:     return $output;
                   18608: }
                   18609: 
                   18610: sub captcha_settings {
                   18611:     my %captcha_params = (
                   18612:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18613:                            www_output_dir => "/captchaspool",
                   18614:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18615:                            numchars       => '5',
                   18616:                          );
                   18617:     return %captcha_params;
                   18618: }
                   18619: 
                   18620: sub check_captcha {
                   18621:     my ($captcha_chk,$captcha_error);
                   18622:     my $code = $env{'form.code'};
                   18623:     my $md5sum = $env{'form.crypt'};
                   18624:     my %captcha_params = &captcha_settings();
                   18625:     my $captcha = Authen::Captcha->new(
                   18626:                       output_folder => $captcha_params{'output_dir'},
                   18627:                       data_folder   => $captcha_params{'db_dir'},
                   18628:                   );
1.1109    raeburn  18629:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18630:     my %captcha_hash = (
                   18631:                         0       => 'Code not checked (file error)',
                   18632:                        -1      => 'Failed: code expired',
                   18633:                        -2      => 'Failed: invalid code (not in database)',
                   18634:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18635:     );
                   18636:     if ($captcha_chk != 1) {
                   18637:         $captcha_error = $captcha_hash{$captcha_chk}
                   18638:     }
                   18639:     return ($captcha_chk,$captcha_error);
                   18640: }
                   18641: 
                   18642: sub create_recaptcha {
1.1234    raeburn  18643:     my ($pubkey,$version) = @_;
                   18644:     if ($version >= 2) {
1.1367    raeburn  18645:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18646:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18647:     } else {
                   18648:         my $use_ssl;
                   18649:         if ($ENV{'SERVER_PORT'} == 443) {
                   18650:             $use_ssl = 1;
                   18651:         }
                   18652:         my $captcha = Captcha::reCAPTCHA->new;
                   18653:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18654:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18655:                &mt('If the text is hard to read, [_1] will replace them.',
                   18656:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18657:                '<br /><br />';
                   18658:     }
1.1094    raeburn  18659: }
                   18660: 
                   18661: sub check_recaptcha {
1.1234    raeburn  18662:     my ($privkey,$version) = @_;
1.1094    raeburn  18663:     my $captcha_chk;
1.1350    raeburn  18664:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18665:     if ($version >= 2) {
                   18666:         my %info = (
                   18667:                      secret   => $privkey, 
                   18668:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18669:                      remoteip => $ip,
1.1234    raeburn  18670:                    );
1.1280    raeburn  18671:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18672:         $request->content(join('&',map {
                   18673:                          my $name = escape($_);
                   18674:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18675:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18676:                          : &escape($info{$_}) );
                   18677:         } keys(%info)));
                   18678:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18679:         if ($response->is_success)  {
                   18680:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18681:             if (ref($data) eq 'HASH') {
                   18682:                 if ($data->{'success'}) {
                   18683:                     $captcha_chk = 1;
                   18684:                 }
                   18685:             }
                   18686:         }
                   18687:     } else {
                   18688:         my $captcha = Captcha::reCAPTCHA->new;
                   18689:         my $captcha_result =
                   18690:             $captcha->check_answer(
                   18691:                                     $privkey,
1.1350    raeburn  18692:                                     $ip,
1.1234    raeburn  18693:                                     $env{'form.recaptcha_challenge_field'},
                   18694:                                     $env{'form.recaptcha_response_field'},
                   18695:                                   );
                   18696:         if ($captcha_result->{is_valid}) {
                   18697:             $captcha_chk = 1;
                   18698:         }
1.1094    raeburn  18699:     }
                   18700:     return $captcha_chk;
                   18701: }
                   18702: 
1.1174    raeburn  18703: sub emailusername_info {
1.1244    raeburn  18704:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18705:     my %titles = &Apache::lonlocal::texthash (
                   18706:                      lastname      => 'Last Name',
                   18707:                      firstname     => 'First Name',
                   18708:                      institution   => 'School/college/university',
                   18709:                      location      => "School's city, state/province, country",
                   18710:                      web           => "School's web address",
                   18711:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18712:                      id            => 'Student/Employee ID',
1.1174    raeburn  18713:                  );
                   18714:     return (\@fields,\%titles);
                   18715: }
                   18716: 
1.1161    raeburn  18717: sub cleanup_html {
                   18718:     my ($incoming) = @_;
                   18719:     my $outgoing;
                   18720:     if ($incoming ne '') {
                   18721:         $outgoing = $incoming;
                   18722:         $outgoing =~ s/;/&#059;/g;
                   18723:         $outgoing =~ s/\#/&#035;/g;
                   18724:         $outgoing =~ s/\&/&#038;/g;
                   18725:         $outgoing =~ s/</&#060;/g;
                   18726:         $outgoing =~ s/>/&#062;/g;
                   18727:         $outgoing =~ s/\(/&#040/g;
                   18728:         $outgoing =~ s/\)/&#041;/g;
                   18729:         $outgoing =~ s/"/&#034;/g;
                   18730:         $outgoing =~ s/'/&#039;/g;
                   18731:         $outgoing =~ s/\$/&#036;/g;
                   18732:         $outgoing =~ s{/}{&#047;}g;
                   18733:         $outgoing =~ s/=/&#061;/g;
                   18734:         $outgoing =~ s/\\/&#092;/g
                   18735:     }
                   18736:     return $outgoing;
                   18737: }
                   18738: 
1.1190    musolffc 18739: # Checks for critical messages and returns a redirect url if one exists.
                   18740: # $interval indicates how often to check for messages.
1.1282    raeburn  18741: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18742: sub critical_redirect {
1.1282    raeburn  18743:     my ($interval,$context) = @_;
1.1356    raeburn  18744:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18745:         return ();
                   18746:     }
1.1190    musolffc 18747:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18748:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18749:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18750:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  18751:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18752:             if ($blocked) {
                   18753:                 my $checkrole = "cm./$cdom/$cnum";
                   18754:                 if ($env{'request.course.sec'} ne '') {
                   18755:                     $checkrole .= "/$env{'request.course.sec'}";
                   18756:                 }
                   18757:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18758:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18759:                     return;
                   18760:                 }
                   18761:             }
                   18762:         }
1.1190    musolffc 18763:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18764:                                         $env{'user.name'});
                   18765:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18766:         my $redirecturl;
1.1190    musolffc 18767:         if ($what[0]) {
1.1356    raeburn  18768: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18769: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18770: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18771:                 return (1, $url);
1.1190    musolffc 18772:             }
1.1191    raeburn  18773:         }
                   18774:     } 
                   18775:     return ();
1.1190    musolffc 18776: }
                   18777: 
1.1174    raeburn  18778: # Use:
                   18779: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18780: #
                   18781: ##################################################
                   18782: #          password associated functions         #
                   18783: ##################################################
                   18784: sub des_keys {
                   18785:     # Make a new key for DES encryption.
                   18786:     # Each key has two parts which are returned separately.
                   18787:     # Please note:  Each key must be passed through the &hex function
                   18788:     # before it is output to the web browser.  The hex versions cannot
                   18789:     # be used to decrypt.
                   18790:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18791:                 '8','9','a','b','c','d','e','f');
                   18792:     my $lkey='';
                   18793:     for (0..7) {
                   18794:         $lkey.=$hexstr[rand(15)];
                   18795:     }
                   18796:     my $ukey='';
                   18797:     for (0..7) {
                   18798:         $ukey.=$hexstr[rand(15)];
                   18799:     }
                   18800:     return ($lkey,$ukey);
                   18801: }
                   18802: 
                   18803: sub des_decrypt {
                   18804:     my ($key,$cyphertext) = @_;
                   18805:     my $keybin=pack("H16",$key);
                   18806:     my $cypher;
                   18807:     if ($Crypt::DES::VERSION>=2.03) {
                   18808:         $cypher=new Crypt::DES $keybin;
                   18809:     } else {
                   18810:         $cypher=new DES $keybin;
                   18811:     }
1.1233    raeburn  18812:     my $plaintext='';
                   18813:     my $cypherlength = length($cyphertext);
                   18814:     my $numchunks = int($cypherlength/32);
                   18815:     for (my $j=0; $j<$numchunks; $j++) {
                   18816:         my $start = $j*32;
                   18817:         my $cypherblock = substr($cyphertext,$start,32);
                   18818:         my $chunk =
                   18819:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18820:         $chunk .=
                   18821:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18822:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18823:         $plaintext .= $chunk;
                   18824:     }
1.1174    raeburn  18825:     return $plaintext;
                   18826: }
                   18827: 
1.1344    raeburn  18828: sub get_requested_shorturls {
1.1309    raeburn  18829:     my ($cdom,$cnum,$navmap) = @_;
                   18830:     return unless (ref($navmap));
1.1344    raeburn  18831:     my ($numnew,$errors);
1.1309    raeburn  18832:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18833:     if (@toshorten) {
                   18834:         my (%maps,%resources,%titles);
                   18835:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18836:                                                                'shorturls',$cdom,$cnum);
                   18837:         if (keys(%resources)) {
1.1344    raeburn  18838:             my %tocreate;
1.1309    raeburn  18839:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18840:                 my $symb = $resources{$item};
                   18841:                 if ($symb) {
                   18842:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18843:                 }
                   18844:             }
1.1344    raeburn  18845:             if (keys(%tocreate)) {
                   18846:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18847:                                                       \%tocreate);
                   18848:             }
1.1309    raeburn  18849:         }
1.1344    raeburn  18850:     }
                   18851:     return ($numnew,$errors);
                   18852: }
                   18853: 
                   18854: sub make_short_symbs {
                   18855:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18856:     my ($numnew,@errors);
                   18857:     if (ref($tocreateref) eq 'HASH') {
                   18858:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18859:         if (keys(%tocreate)) {
                   18860:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18861:             my $su = Short::URL->new(no_vowels => 1);
                   18862:             my $init = '';
                   18863:             my (%newunique,%addcourse,%courseonly,%failed);
                   18864:             # get lock on tiny db
                   18865:             my $now = time;
1.1344    raeburn  18866:             if ($lockuser eq '') {
                   18867:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18868:             }
1.1309    raeburn  18869:             my $lockhash = {
1.1344    raeburn  18870:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18871:                             };
                   18872:             my $tries = 0;
                   18873:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18874:             my ($code,$error);
                   18875:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18876:                 $tries ++;
                   18877:                 sleep 1;
1.1319    raeburn  18878:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18879:             }
                   18880:             if ($gotlock eq 'ok') {
                   18881:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18882:                                        \%addcourse,\%courseonly,\%failed);
                   18883:                 if (keys(%failed)) {
                   18884:                     my $numfailed = scalar(keys(%failed));
                   18885:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18886:                 }
                   18887:                 if (keys(%newunique)) {
                   18888:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18889:                     if ($putres eq 'ok') {
                   18890:                         $numnew = scalar(keys(%newunique));
                   18891:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18892:                         unless ($newputres eq 'ok') {
                   18893:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18894:                         }
                   18895:                     } else {
                   18896:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18897:                     }
                   18898:                 }
                   18899:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18900:                 unless ($dellockres eq 'ok') {
                   18901:                     push(@errors,&mt('error: could not release lockfile'));
                   18902:                 }
                   18903:             } else {
                   18904:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18905:             }
                   18906:             if (keys(%courseonly)) {
                   18907:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18908:                 if ($result ne 'ok') {
                   18909:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18910:                 }
                   18911:             }
                   18912:         }
                   18913:     }
                   18914:     return ($numnew,\@errors);
                   18915: }
                   18916: 
                   18917: sub shorten_symbs {
                   18918:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18919:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18920:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18921:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18922:     my (%possibles,%collisions);
                   18923:     foreach my $key (keys(%{$tocreate})) {
                   18924:         my $num = String::CRC32::crc32($key);
                   18925:         my $tiny = $su->encode($num,$init);
                   18926:         if ($tiny) {
                   18927:             $possibles{$tiny} = $key;
                   18928:         }
                   18929:     }
                   18930:     if (!$init) {
                   18931:         $init = 1;
                   18932:     } else {
                   18933:         $init ++;
                   18934:     }
                   18935:     if (keys(%possibles)) {
                   18936:         my @posstiny = keys(%possibles);
                   18937:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18938:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18939:         if (keys(%currtiny)) {
                   18940:             foreach my $key (keys(%currtiny)) {
                   18941:                 next if ($currtiny{$key} eq '');
                   18942:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18943:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18944:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18945:                         $courseonly->{$tsymb} = $key;
                   18946:                     }
                   18947:                 } else {
                   18948:                     $collisions{$possibles{$key}} = 1;
                   18949:                 }
                   18950:                 delete($possibles{$key});
                   18951:             }
                   18952:         }
                   18953:         foreach my $key (keys(%possibles)) {
                   18954:             $newunique->{$key} = $possibles{$key};
                   18955:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18956:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18957:                 $addcourse->{$tsymb} = $key;
                   18958:             }
                   18959:         }
                   18960:     }
                   18961:     if (keys(%collisions)) {
                   18962:         if ($init <5) {
                   18963:             if (!$init) {
                   18964:                 $init = 1;
                   18965:             } else {
                   18966:                 $init ++;
                   18967:             }
                   18968:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18969:                                    $newunique,$addcourse,$courseonly,$failed);
                   18970:         } else {
                   18971:             foreach my $key (keys(%collisions)) {
                   18972:                 $failed->{$key} = 1;
                   18973:             }
                   18974:         }
                   18975:     }
                   18976:     return $init;
                   18977: }
                   18978: 
1.1328    raeburn  18979: sub is_nonframeable {
1.1329    raeburn  18980:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18981:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18982:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18983: 
                   18984:     $remprotocol = lc($remprotocol);
                   18985:     $remhost = lc($remhost);
                   18986:     my $remport = 80;
                   18987:     if ($remprotocol eq 'https') {
                   18988:         $remport = 443;
                   18989:     }
1.1330    raeburn  18990:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18991:     if ($cached) {
                   18992:         unless ($nocache) {
                   18993:             if ($result) {
                   18994:                 return 1;
                   18995:             } else {
                   18996:                 return 0;
                   18997:             }
                   18998:         }
                   18999:     }
1.1328    raeburn  19000:     my $uselink;
                   19001:     my $request = new HTTP::Request('HEAD',$url);
                   19002:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19003:     if ($response->is_success()) {
                   19004:         my $secpolicy = lc($response->header('content-security-policy'));
                   19005:         my $xframeop = lc($response->header('x-frame-options'));
                   19006:         $secpolicy =~ s/^\s+|\s+$//g;
                   19007:         $xframeop =~ s/^\s+|\s+$//g;
                   19008:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19009:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19010:             my ($origin,$protocol,$port);
                   19011:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19012:                 $port = $ENV{'SERVER_PORT'};
                   19013:             } else {
                   19014:                 $port = 80;
                   19015:             }
                   19016:             if ($absolute eq '') {
                   19017:                 $protocol = 'http:';
                   19018:                 if ($port == 443) {
                   19019:                     $protocol = 'https:';
                   19020:                 }
                   19021:                 $origin = $protocol.'//'.lc($hostname);
                   19022:             } else {
                   19023:                 $origin = lc($absolute);
                   19024:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19025:             }
                   19026:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19027:                 my $framepolicy = $1;
                   19028:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19029:                 my @policies = split(/\s+/,$framepolicy);
                   19030:                 if (@policies) {
                   19031:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19032:                         $uselink = 1;
                   19033:                     } else {
                   19034:                         $uselink = 1;
                   19035:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19036:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19037:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19038:                             undef($uselink);
                   19039:                         }
                   19040:                         if ($uselink) {
                   19041:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19042:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19043:                                     undef($uselink);
                   19044:                                 }
                   19045:                             }
                   19046:                         }
                   19047:                         if ($uselink) {
                   19048:                             my @possok;
                   19049:                             if ($ip ne '') {
                   19050:                                 push(@possok,$ip);
                   19051:                             }
                   19052:                             my $hoststr = '';
                   19053:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19054:                                 if ($hoststr eq '') {
                   19055:                                     $hoststr = $part;
                   19056:                                 } else {
                   19057:                                     $hoststr = "$part.$hoststr";
                   19058:                                 }
                   19059:                                 if ($hoststr eq $hostname) {
                   19060:                                     push(@possok,$hostname);
                   19061:                                 } else {
                   19062:                                     push(@possok,"*.$hoststr");
                   19063:                                 }
                   19064:                             }
                   19065:                             if (@possok) {
                   19066:                                 foreach my $poss (@possok) {
                   19067:                                     last if (!$uselink);
                   19068:                                     foreach my $policy (@policies) {
                   19069:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19070:                                             undef($uselink);
                   19071:                                             last;
                   19072:                                         }
                   19073:                                     }
                   19074:                                 }
                   19075:                             }
                   19076:                         }
                   19077:                     }
                   19078:                 }
                   19079:             } elsif ($xframeop ne '') {
                   19080:                 $uselink = 1;
                   19081:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19082:                 if (@policies) {
                   19083:                     unless (grep(/^deny$/,@policies)) {
                   19084:                         if ($origin ne '') {
                   19085:                             if (grep(/^sameorigin$/,@policies)) {
                   19086:                                 if ($remotehost eq $origin) {
                   19087:                                     undef($uselink);
                   19088:                                 }
                   19089:                             }
                   19090:                             if ($uselink) {
                   19091:                                 foreach my $policy (@policies) {
                   19092:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19093:                                         my $allowfrom = $1;
                   19094:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19095:                                             undef($uselink);
                   19096:                                             last;
                   19097:                                         }
                   19098:                                     }
                   19099:                                 }
                   19100:                             }
                   19101:                         }
                   19102:                     }
                   19103:                 }
                   19104:             }
                   19105:         }
                   19106:     }
1.1329    raeburn  19107:     if ($nocache) {
                   19108:         if ($cached) {
                   19109:             my $devalidate;
                   19110:             if ($uselink && !$result) {
                   19111:                 $devalidate = 1;
                   19112:             } elsif (!$uselink && $result) {
                   19113:                 $devalidate = 1;
                   19114:             }
                   19115:             if ($devalidate) {
                   19116:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19117:             }
                   19118:         }
                   19119:     } else {
                   19120:         if ($uselink) {
                   19121:             $result = 1;
                   19122:         } else {
                   19123:             $result = 0;
                   19124:         }
                   19125:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19126:     }
1.1328    raeburn  19127:     return $uselink;
                   19128: }
                   19129: 
1.1359    raeburn  19130: sub page_menu {
                   19131:     my ($menucolls,$menunum) = @_;
                   19132:     my %menu;
                   19133:     foreach my $item (split(/;/,$menucolls)) {
                   19134:         my ($num,$value) = split(/\%/,$item);
                   19135:         if ($num eq $menunum) {
                   19136:             my @entries = split(/\&/,$value);
                   19137:             foreach my $entry (@entries) {
                   19138:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19139:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19140:                     $menu{$name} = $fields;
                   19141:                 } else {
                   19142:                     my @shown;
                   19143:                     if ($fields =~ /,/) {
                   19144:                         @shown = split(/,/,$fields);
                   19145:                     } else {
                   19146:                         @shown = ($fields);
                   19147:                     }
                   19148:                     if (@shown) {
                   19149:                         foreach my $field (@shown) {
                   19150:                             next if ($field eq '');
                   19151:                             $menu{$field} = 1;
                   19152:                         }
                   19153:                     }
                   19154:                 }
                   19155:             }
                   19156:         }
                   19157:     }
                   19158:     return %menu;
                   19159: }
                   19160: 
1.112     bowersj2 19161: 1;
                   19162: __END__;
1.41      ng       19163: 

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