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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1387  ! raeburn     4: # $Id: loncommon.pm,v 1.1386 2022/08/24 20:58:50 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.1383    raeburn    64: use Apache::lonnavmaps();
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.1387  ! raeburn   960:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
        !           961:    my $output='<select name="'.$name.'" '.$id.$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: 
1.1382    raeburn  1524:     my $target = '_top';
                   1525:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1526:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1527:         $target = '_blank';
1.1378    raeburn  1528:     }
1.1382    raeburn  1529: 
1.172     www      1530:     # Add the text
                   1531:     if ($text ne "")
                   1532:     {
                   1533: 	$template .= 
                   1534:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1535:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1536:     }
                   1537: 
                   1538:     # Add the graphic
1.179     matthew  1539:     my $title = &mt('Report a Bug');
1.215     albertel 1540:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1541:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1542:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1543: ENDTEMPLATE
                   1544:     if ($text ne '') { $template.='</td></tr></table>' };
                   1545:     return $template;
                   1546: 
                   1547: }
                   1548: 
                   1549: sub help_open_faq {
                   1550:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1551:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1552:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1553:     $text = "" if (not defined $text);
                   1554: 	$stayOnPage=1;
                   1555:     $width = 350 if (not defined $width);
                   1556:     $height = 400 if (not defined $height);
                   1557: 
                   1558:     $topic=~s/\W+/\+/g;
                   1559:     my $link='';
                   1560:     my $template='';
                   1561:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1562:     if (!$stayOnPage)
                   1563:     {
                   1564: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1565:     }
                   1566:     else
                   1567:     {
                   1568: 	$link = $url;
                   1569:     }
                   1570: 
                   1571:     # Add the text
                   1572:     if ($text ne "")
                   1573:     {
                   1574: 	$template .= 
1.173     www      1575:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1576:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1577:     }
                   1578: 
                   1579:     # Add the graphic
1.179     matthew  1580:     my $title = &mt('View the FAQ');
1.215     albertel 1581:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1582:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1583:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1584: ENDTEMPLATE
                   1585:     if ($text ne '') { $template.='</td></tr></table>' };
                   1586:     return $template;
                   1587: 
1.44      bowersj2 1588: }
1.37      matthew  1589: 
1.180     matthew  1590: ###############################################################
                   1591: ###############################################################
                   1592: 
1.45      matthew  1593: =pod
                   1594: 
1.648     raeburn  1595: =item * &change_content_javascript():
1.256     matthew  1596: 
                   1597: This and the next function allow you to create small sections of an
                   1598: otherwise static HTML page that you can update on the fly with
                   1599: Javascript, even in Netscape 4.
                   1600: 
                   1601: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1602: must be written to the HTML page once. It will prove the Javascript
                   1603: function "change(name, content)". Calling the change function with the
                   1604: name of the section 
                   1605: you want to update, matching the name passed to C<changable_area>, and
                   1606: the new content you want to put in there, will put the content into
                   1607: that area.
                   1608: 
                   1609: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1610: to contain room for the original contents. You need to "make space"
                   1611: for whatever changes you wish to make, and be B<sure> to check your
                   1612: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1613: it's adequate for updating a one-line status display, but little more.
                   1614: This script will set the space to 100% width, so you only need to
                   1615: worry about height in Netscape 4.
                   1616: 
                   1617: Modern browsers are much less limiting, and if you can commit to the
                   1618: user not using Netscape 4, this feature may be used freely with
                   1619: pretty much any HTML.
                   1620: 
                   1621: =cut
                   1622: 
                   1623: sub change_content_javascript {
                   1624:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1625:     if ($env{'browser.type'} eq 'netscape' &&
                   1626: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1627: 	return (<<NETSCAPE4);
                   1628: 	function change(name, content) {
                   1629: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1630: 	    doc.open();
                   1631: 	    doc.write(content);
                   1632: 	    doc.close();
                   1633: 	}
                   1634: NETSCAPE4
                   1635:     } else {
                   1636: 	# Otherwise, we need to use semi-standards-compliant code
                   1637: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1638: 	# is really scary, and every useful browser supports it
                   1639: 	return (<<DOMBASED);
                   1640: 	function change(name, content) {
                   1641: 	    element = document.getElementById(name);
                   1642: 	    element.innerHTML = content;
                   1643: 	}
                   1644: DOMBASED
                   1645:     }
                   1646: }
                   1647: 
                   1648: =pod
                   1649: 
1.648     raeburn  1650: =item * &changable_area($name,$origContent):
1.256     matthew  1651: 
                   1652: This provides a "changable area" that can be modified on the fly via
                   1653: the Javascript code provided in C<change_content_javascript>. $name is
                   1654: the name you will use to reference the area later; do not repeat the
                   1655: same name on a given HTML page more then once. $origContent is what
                   1656: the area will originally contain, which can be left blank.
                   1657: 
                   1658: =cut
                   1659: 
                   1660: sub changable_area {
                   1661:     my ($name, $origContent) = @_;
                   1662: 
1.258     albertel 1663:     if ($env{'browser.type'} eq 'netscape' &&
                   1664: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1665: 	# If this is netscape 4, we need to use the Layer tag
                   1666: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1667:     } else {
                   1668: 	return "<span id='$name'>$origContent</span>";
                   1669:     }
                   1670: }
                   1671: 
                   1672: =pod
                   1673: 
1.648     raeburn  1674: =item * &viewport_geometry_js 
1.590     raeburn  1675: 
                   1676: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1677: 
                   1678: =cut
                   1679: 
                   1680: 
                   1681: sub viewport_geometry_js { 
                   1682:     return <<"GEOMETRY";
                   1683: var Geometry = {};
                   1684: function init_geometry() {
                   1685:     if (Geometry.init) { return };
                   1686:     Geometry.init=1;
                   1687:     if (window.innerHeight) {
                   1688:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1689:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1690:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1691:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1692:     }
                   1693:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1694:         Geometry.getViewportHeight =
                   1695:             function() { return document.documentElement.clientHeight; };
                   1696:         Geometry.getViewportWidth =
                   1697:             function() { return document.documentElement.clientWidth; };
                   1698: 
                   1699:         Geometry.getHorizontalScroll =
                   1700:             function() { return document.documentElement.scrollLeft; };
                   1701:         Geometry.getVerticalScroll =
                   1702:             function() { return document.documentElement.scrollTop; };
                   1703:     }
                   1704:     else if (document.body.clientHeight) {
                   1705:         Geometry.getViewportHeight =
                   1706:             function() { return document.body.clientHeight; };
                   1707:         Geometry.getViewportWidth =
                   1708:             function() { return document.body.clientWidth; };
                   1709:         Geometry.getHorizontalScroll =
                   1710:             function() { return document.body.scrollLeft; };
                   1711:         Geometry.getVerticalScroll =
                   1712:             function() { return document.body.scrollTop; };
                   1713:     }
                   1714: }
                   1715: 
                   1716: GEOMETRY
                   1717: }
                   1718: 
                   1719: =pod
                   1720: 
1.648     raeburn  1721: =item * &viewport_size_js()
1.590     raeburn  1722: 
                   1723: 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. 
                   1724: 
                   1725: =cut
                   1726: 
                   1727: sub viewport_size_js {
                   1728:     my $geometry = &viewport_geometry_js();
                   1729:     return <<"DIMS";
                   1730: 
                   1731: $geometry
                   1732: 
                   1733: function getViewportDims(width,height) {
                   1734:     init_geometry();
                   1735:     width.value = Geometry.getViewportWidth();
                   1736:     height.value = Geometry.getViewportHeight();
                   1737:     return;
                   1738: }
                   1739: 
                   1740: DIMS
                   1741: }
                   1742: 
                   1743: =pod
                   1744: 
1.648     raeburn  1745: =item * &resize_textarea_js()
1.565     albertel 1746: 
                   1747: emits the needed javascript to resize a textarea to be as big as possible
                   1748: 
                   1749: creates a function resize_textrea that takes two IDs first should be
                   1750: the id of the element to resize, second should be the id of a div that
                   1751: surrounds everything that comes after the textarea, this routine needs
                   1752: to be attached to the <body> for the onload and onresize events.
                   1753: 
1.648     raeburn  1754: =back
1.565     albertel 1755: 
                   1756: =cut
                   1757: 
                   1758: sub resize_textarea_js {
1.590     raeburn  1759:     my $geometry = &viewport_geometry_js();
1.565     albertel 1760:     return <<"RESIZE";
                   1761:     <script type="text/javascript">
1.824     bisitz   1762: // <![CDATA[
1.590     raeburn  1763: $geometry
1.565     albertel 1764: 
1.588     albertel 1765: function getX(element) {
                   1766:     var x = 0;
                   1767:     while (element) {
                   1768: 	x += element.offsetLeft;
                   1769: 	element = element.offsetParent;
                   1770:     }
                   1771:     return x;
                   1772: }
                   1773: function getY(element) {
                   1774:     var y = 0;
                   1775:     while (element) {
                   1776: 	y += element.offsetTop;
                   1777: 	element = element.offsetParent;
                   1778:     }
                   1779:     return y;
                   1780: }
                   1781: 
                   1782: 
1.565     albertel 1783: function resize_textarea(textarea_id,bottom_id) {
                   1784:     init_geometry();
                   1785:     var textarea        = document.getElementById(textarea_id);
                   1786:     //alert(textarea);
                   1787: 
1.588     albertel 1788:     var textarea_top    = getY(textarea);
1.565     albertel 1789:     var textarea_height = textarea.offsetHeight;
                   1790:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1791:     var bottom_top      = getY(bottom);
1.565     albertel 1792:     var bottom_height   = bottom.offsetHeight;
                   1793:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1794:     var fudge           = 23;
1.565     albertel 1795:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1796:     if (new_height < 300) {
                   1797: 	new_height = 300;
                   1798:     }
                   1799:     textarea.style.height=new_height+'px';
                   1800: }
1.824     bisitz   1801: // ]]>
1.565     albertel 1802: </script>
                   1803: RESIZE
                   1804: 
                   1805: }
                   1806: 
1.1205    golterma 1807: sub colorfuleditor_js {
1.1248    raeburn  1808:     my $browse_or_search;
                   1809:     my $respath;
                   1810:     my ($cnum,$cdom) = &crsauthor_url();
                   1811:     if ($cnum) {
                   1812:         $respath = "/res/$cdom/$cnum/";
                   1813:         my %js_lt = &Apache::lonlocal::texthash(
                   1814:             sunm => 'Sub-directory name',
                   1815:             save => 'Save page to make this permanent',
                   1816:         );
                   1817:         &js_escape(\%js_lt);
                   1818:         $browse_or_search = <<"END";
                   1819: 
                   1820:     function toggleChooser(form,element,titleid,only,search) {
                   1821:         var disp = 'none';
                   1822:         if (document.getElementById('chooser_'+element)) {
                   1823:             var curr = document.getElementById('chooser_'+element).style.display;
                   1824:             if (curr == 'none') {
                   1825:                 disp='inline';
                   1826:                 if (form.elements['chooser_'+element].length) {
                   1827:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1828:                         form.elements['chooser_'+element][i].checked = false;
                   1829:                     }
                   1830:                 }
                   1831:                 toggleResImport(form,element);
                   1832:             }
                   1833:             document.getElementById('chooser_'+element).style.display = disp;
                   1834:         }
                   1835:     }
                   1836: 
                   1837:     function toggleCrsFile(form,element,numdirs) {
                   1838:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1839:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1840:             if (curr == 'none') {
                   1841:                 if (numdirs) {
                   1842:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1843:                     if (numdirs > 1) {
                   1844:                         window['select1'+element+'_changed']();
                   1845:                     }
                   1846:                 }
                   1847:             } 
                   1848:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1849:             
                   1850:         }
                   1851:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1852:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1853:             if (document.getElementById('uploadcrsres_'+element)) {
                   1854:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1855:             }
                   1856:         }
                   1857:         return;
                   1858:     }
                   1859: 
                   1860:     function toggleCrsUpload(form,element,numcrsdirs) {
                   1861:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1862:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1863:         }
                   1864:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1865:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1866:             if (curr == 'none') {
                   1867:                 if (numcrsdirs) {
                   1868:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
                   1869:                    form.elements['newsubdir_'+element][0].checked = true;
                   1870:                    toggleNewsubdir(form,element);
                   1871:                 }
                   1872:             }
                   1873:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1874:         }
                   1875:         return;
                   1876:     }
                   1877: 
                   1878:     function toggleResImport(form,element) {
                   1879:         var choices = new Array('crsres','upload');
                   1880:         for (var i=0; i<choices.length; i++) {
                   1881:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1882:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1883:             }
                   1884:         }
                   1885:     }
                   1886: 
                   1887:     function toggleNewsubdir(form,element) {
                   1888:         var newsub = form.elements['newsubdir_'+element];
                   1889:         if (newsub) {
                   1890:             if (newsub.length) {
                   1891:                 for (var j=0; j<newsub.length; j++) {
                   1892:                     if (newsub[j].checked) {
                   1893:                         if (document.getElementById('newsubdirname_'+element)) {
                   1894:                             if (newsub[j].value == '1') {
                   1895:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1896:                                 if (document.getElementById('newsubdir_'+element)) {
                   1897:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1898:                                 }
                   1899:                             } else {
                   1900:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1901:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1902:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1903:                             }
                   1904:                         }
                   1905:                         break; 
                   1906:                     }
                   1907:                 }
                   1908:             }
                   1909:         }
                   1910:     }
                   1911: 
                   1912:     function updateCrsFile(form,element) {
                   1913:         var directory = form.elements['coursepath_'+element];
                   1914:         var filename = form.elements['coursefile_'+element];
                   1915:         var path = directory.options[directory.selectedIndex].value;
                   1916:         var file = filename.options[filename.selectedIndex].value;
                   1917:         form.elements[element].value = '$respath';
                   1918:         if (path == '/') {
                   1919:             form.elements[element].value += file;
                   1920:         } else {
                   1921:             form.elements[element].value += path+'/'+file;
                   1922:         }
                   1923:         unClean();
                   1924:         if (document.getElementById('previewimg_'+element)) {
                   1925:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1926:             var newsrc = document.getElementById('previewimg_'+element).src; 
                   1927:         }
                   1928:         if (document.getElementById('showimg_'+element)) {
                   1929:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1930:         }
                   1931:         toggleChooser(form,element);
                   1932:         return;
                   1933:     }
                   1934: 
                   1935:     function uploadDone(suffix,name) {
                   1936:         if (name) {
                   1937: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1938:             unClean();
                   1939:             toggleChooser(document.forms["lonhomework"],suffix);
                   1940:         }
                   1941:     }
                   1942: 
                   1943: \$(document).ready(function(){
                   1944: 
                   1945:     \$(document).delegate('form :submit', 'click', function( event ) {
                   1946:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   1947:             var buttonId = this.id;
                   1948:             var suffix = buttonId.toString();
                   1949:             suffix = suffix.replace(/^crsupload_/,'');
                   1950:             event.preventDefault();
                   1951:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   1952:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   1953:             \$(this.form).submit();
                   1954:             document.lonhomework.target = '';
                   1955:             if (document.getElementById('crsuploadto_'+suffix)) {
                   1956:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   1957:             }
                   1958:             return false;
                   1959:         }
                   1960:     });
                   1961: });
                   1962: END
                   1963:     }
1.1205    golterma 1964:     return <<"COLORFULEDIT"
                   1965: <script type="text/javascript">
                   1966: // <![CDATA[>
                   1967:     function fold_box(curDepth, lastresource){
                   1968: 
                   1969:     // we need a list because there can be several blocks you need to fold in one tag
                   1970:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1971:     // but there is only one folding button per tag
                   1972:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1973: 
                   1974:         if(block.item(0).style.display == 'none'){
                   1975: 
                   1976:             foldbutton.value = '@{[&mt("Hide")]}';
                   1977:             for (i = 0; i < block.length; i++){
                   1978:                 block.item(i).style.display = '';
                   1979:             }
                   1980:         }else{
                   1981: 
                   1982:             foldbutton.value = '@{[&mt("Show")]}';
                   1983:             for (i = 0; i < block.length; i++){
                   1984:                 // block.item(i).style.visibility = 'collapse';
                   1985:                 block.item(i).style.display = 'none';
                   1986:             }
                   1987:         };
                   1988:         saveState(lastresource);
                   1989:     }
                   1990: 
                   1991:     function saveState (lastresource) {
                   1992: 
                   1993:         var tag_list = getTagList();
                   1994:         if(tag_list != null){
                   1995:             var timestamp = new Date().getTime();
                   1996:             var key = lastresource;
                   1997: 
                   1998:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1999:             // starting with timestamp
                   2000:             var value = timestamp+';';
                   2001: 
                   2002:             // building the list of key-value pairs
                   2003:             for(var i = 0; i < tag_list.length; i++){
                   2004:                 value += tag_list[i]+',';
                   2005:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2006:             }
                   2007: 
                   2008:             // only iterate whole storage if nothing to override
                   2009:             if(localStorage.getItem(key) == null){        
                   2010: 
                   2011:                 // prevent storage from growing large
                   2012:                 if(localStorage.length > 50){
                   2013:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2014:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2015:                     var oldest_key;
                   2016:                     
                   2017:                     for(var i = 1; i < localStorage.length; i++){
                   2018:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2019:                             oldest_key = localStorage.key(i);
                   2020:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2021:                         }
                   2022:                     }
                   2023:                     localStorage.removeItem(oldest_key);
                   2024:                 }
                   2025:             }
                   2026:             localStorage.setItem(key,value);
                   2027:         }
                   2028:     }
                   2029: 
                   2030:     // restore folding status of blocks (on page load)
                   2031:     function restoreState (lastresource) {
                   2032:         if(localStorage.getItem(lastresource) != null){
                   2033:             var key = lastresource;
                   2034:             var value = localStorage.getItem(key);
                   2035:             var regex_delTimestamp = /^\d+;/;
                   2036: 
                   2037:             value.replace(regex_delTimestamp, '');
                   2038: 
                   2039:             var valueArr = value.split(';');
                   2040:             var pairs;
                   2041:             var elements;
                   2042:             for (var i = 0; i < valueArr.length; i++){
                   2043:                 pairs = valueArr[i].split(',');
                   2044:                 elements = document.getElementsByName(pairs[0]);
                   2045: 
                   2046:                 for (var j = 0; j < elements.length; j++){  
                   2047:                     elements[j].style.display = pairs[1];
                   2048:                     if (pairs[1] == "none"){
                   2049:                         var regex_id = /([_\\d]+)\$/;
                   2050:                         regex_id.exec(pairs[0]);
                   2051:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2052:                     }
                   2053:                 }
                   2054:             }
                   2055:         }
                   2056:     }
                   2057: 
                   2058:     function getTagList () {
                   2059:         
                   2060:         var stringToSearch = document.lonhomework.innerHTML;
                   2061: 
                   2062:         var ret = new Array();
                   2063:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2064:         var tag_list = stringToSearch.match(regex_findBlock);
                   2065: 
                   2066:         if(tag_list != null){
                   2067:             for(var i = 0; i < tag_list.length; i++){            
                   2068:                 ret.push(tag_list[i].replace(/"/, ''));
                   2069:             }
                   2070:         }
                   2071:         return ret;
                   2072:     }
                   2073: 
                   2074:     function saveScrollPosition (resource) {
                   2075:         var tag_list = getTagList();
                   2076: 
                   2077:         // we dont always want to jump to the first block
                   2078:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2079:         if(\$(window).scrollTop() > 170){
                   2080:             if(tag_list != null){
                   2081:                 var result;
                   2082:                 for(var i = 0; i < tag_list.length; i++){
                   2083:                     if(isElementInViewport(tag_list[i])){
                   2084:                         result += tag_list[i]+';';
                   2085:                     }
                   2086:                 }
                   2087:                 sessionStorage.setItem('anchor_'+resource, result);
                   2088:             }
                   2089:         } else {
                   2090:             // we dont need to save zero, just delete the item to leave everything tidy
                   2091:             sessionStorage.removeItem('anchor_'+resource);
                   2092:         }
                   2093:     }
                   2094: 
                   2095:     function restoreScrollPosition(resource){
                   2096: 
                   2097:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2098:         if(elem != null){
                   2099:             var tag_list = elem.split(';');
                   2100:             var elem_list;
                   2101: 
                   2102:             for(var i = 0; i < tag_list.length; i++){
                   2103:                 elem_list = document.getElementsByName(tag_list[i]);
                   2104:                 
                   2105:                 if(elem_list.length > 0){
                   2106:                     elem = elem_list[0];
                   2107:                     break;
                   2108:                 }
                   2109:             }
                   2110:             elem.scrollIntoView();
                   2111:         }
                   2112:     }
                   2113: 
                   2114:     function isElementInViewport(el) {
                   2115: 
                   2116:         // change to last element instead of first
                   2117:         var elem = document.getElementsByName(el);
                   2118:         var rect = elem[0].getBoundingClientRect();
                   2119: 
                   2120:         return (
                   2121:             rect.top >= 0 &&
                   2122:             rect.left >= 0 &&
                   2123:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2124:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2125:         );
                   2126:     }
                   2127:     
                   2128:     function autosize(depth){
                   2129:         var cmInst = window['cm'+depth];
                   2130:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2131: 
                   2132:         // is fixed size, switching to dynamic
                   2133:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2134:             cmInst.setSize("","auto");
                   2135:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2136:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2137: 
                   2138:         // is dynamic size, switching to fixed
                   2139:         } else {
                   2140:             cmInst.setSize("","300px");
                   2141:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2142:             sessionStorage.removeItem("autosized_"+depth);
                   2143:         }
                   2144:     }
                   2145: 
1.1248    raeburn  2146: $browse_or_search
1.1205    golterma 2147: 
                   2148: // ]]>
                   2149: </script>
                   2150: COLORFULEDIT
                   2151: }
                   2152: 
                   2153: sub xmleditor_js {
                   2154:     return <<XMLEDIT
                   2155: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2156: <script type="text/javascript">
                   2157: // <![CDATA[>
                   2158: 
                   2159:     function saveScrollPosition (resource) {
                   2160: 
                   2161:         var scrollPos = \$(window).scrollTop();
                   2162:         sessionStorage.setItem(resource,scrollPos);
                   2163:     }
                   2164: 
                   2165:     function restoreScrollPosition(resource){
                   2166: 
                   2167:         var scrollPos = sessionStorage.getItem(resource);
                   2168:         \$(window).scrollTop(scrollPos);
                   2169:     }
                   2170: 
                   2171:     // unless internet explorer
                   2172:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2173: 
                   2174:         \$(document).ready(function() {
                   2175:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2176:         });
                   2177:     }
                   2178: 
                   2179:     // inserts text at cursor position into codemirror (xml editor only)
                   2180:     function insertText(text){
                   2181:         cm.focus();
                   2182:         var curPos = cm.getCursor();
                   2183:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2184:     }
                   2185: // ]]>
                   2186: </script>
                   2187: XMLEDIT
                   2188: }
                   2189: 
                   2190: sub insert_folding_button {
                   2191:     my $curDepth = $Apache::lonxml::curdepth;
                   2192:     my $lastresource = $env{'request.ambiguous'};
                   2193: 
                   2194:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2195:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2196: }
                   2197: 
1.1248    raeburn  2198: sub crsauthor_url {
                   2199:     my ($url) = @_;
                   2200:     if ($url eq '') {
                   2201:         $url = $ENV{'REQUEST_URI'};
                   2202:     }
                   2203:     my ($cnum,$cdom);
                   2204:     if ($env{'request.course.id'}) {
                   2205:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2206:         if ($audom ne '' && $auname ne '') {
                   2207:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2208:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2209:                 $cnum = $auname;
                   2210:                 $cdom = $audom;
                   2211:             }
                   2212:         }
                   2213:     }
                   2214:     return ($cnum,$cdom);
                   2215: }
                   2216: 
                   2217: sub import_crsauthor_form {
1.1265    raeburn  2218:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2219:     return (0) unless ($env{'request.course.id'});
                   2220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2221:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2222:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2223:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2224:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
                   2225:     my @ids=&Apache::lonnet::current_machine_ids();
                   2226:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
                   2227:     
                   2228:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2229:         $is_home = 1;
                   2230:     }
                   2231:     $relpath = "/priv/$cdom/$cnum";
                   2232:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
                   2233:     my %lt = &Apache::lonlocal::texthash (
                   2234:         fnam => 'Filename',
                   2235:         dire => 'Directory',
                   2236:     );
                   2237:     my $numdirs = scalar(keys(%files));
                   2238:     my (%possexts,$singledir,@singledirfiles);
                   2239:     if ($only) {
                   2240:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
                   2241:     }
                   2242:     my (%nonemptydirs,$possdirs);
                   2243:     if ($numdirs > 1) {
                   2244:         my @order;
                   2245:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
                   2246:             if (ref($files{$key}) eq 'HASH') {
                   2247:                 my $shown = $key;
                   2248:                 if ($key eq '') {
                   2249:                     $shown = '/';
                   2250:                 }
                   2251:                 my @ordered = ();
                   2252:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
1.1315    raeburn  2253:                     next if ($file =~ /\.rights$/);
1.1248    raeburn  2254:                     if ($only) {
                   2255:                         my ($ext) = ($file =~ /\.([^.]+)$/);
                   2256:                         unless ($possexts{lc($ext)}) {
                   2257:                             next;
                   2258:                         }
                   2259:                     }
                   2260:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
                   2261:                     push(@ordered,$file);
                   2262:                 }
                   2263:                 if (@ordered) {
                   2264:                     push(@order,$key);
                   2265:                     $nonemptydirs{$key} = 1;
                   2266:                     $selimport_menus{$key}->{'text'} = $shown;
                   2267:                     $selimport_menus{$key}->{'default'} = '';
                   2268:                     $selimport_menus{$key}->{'select2'}->{''} = '';
                   2269:                     $selimport_menus{$key}->{'order'} = \@ordered;
                   2270:                 }
                   2271:             }
                   2272:         }
                   2273:         $possdirs = scalar(keys(%nonemptydirs));
                   2274:         if ($possdirs > 1) {
                   2275:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
                   2276:             $output = $lt{'dire'}.
                   2277:                       &linked_select_forms($form,'<br />'.
                   2278:                                            $lt{'fnam'},'',
                   2279:                                            $firstselectname,$secondselectname,
                   2280:                                            \%selimport_menus,\@order,
                   2281:                                            $onchangefirst,'',$suffix).'<br />';
                   2282:         } elsif ($possdirs == 1) {
                   2283:             $singledir = (keys(%nonemptydirs))[0];
                   2284:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
                   2285:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
                   2286:             }
                   2287:             delete($selimport_menus{$singledir});
                   2288:         }
                   2289:     } elsif ($numdirs == 1) {
                   2290:         $singledir = (keys(%files))[0];
                   2291:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
                   2292:             if ($only) {
                   2293:                 my ($ext) = ($file =~ /\.([^.]+)$/);
                   2294:                 unless ($possexts{lc($ext)}) {
                   2295:                     next;
                   2296:                 }
1.1315    raeburn  2297:             } else {
                   2298:                 next if ($file =~ /\.rights$/);
1.1248    raeburn  2299:             }
                   2300:             push(@singledirfiles,$file);
                   2301:         }
                   2302:         if (@singledirfiles) {
1.1315    raeburn  2303:             $possdirs = 1;
1.1248    raeburn  2304:         }
                   2305:     }
                   2306:     if (($possdirs == 1) && (@singledirfiles)) {
                   2307:         my $showdir = $singledir;
                   2308:         if ($singledir eq '') {
                   2309:             $showdir = '/';
                   2310:         }
                   2311:         $output = $lt{'dire'}.
                   2312:                   '<select name="'.$firstselectname.'">'.
                   2313:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
                   2314:                   '</select><br />'.
                   2315:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
                   2316:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
                   2317:         foreach my $file (@singledirfiles) {
                   2318:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
                   2319:         }
                   2320:         $output .= '</select><br />'."\n";
                   2321:     }
                   2322:     return ($possdirs,$output);
                   2323: }
                   2324: 
1.565     albertel 2325: =pod
                   2326: 
1.256     matthew  2327: =head1 Excel and CSV file utility routines
                   2328: 
                   2329: =cut
                   2330: 
                   2331: ###############################################################
                   2332: ###############################################################
                   2333: 
                   2334: =pod
                   2335: 
1.1162    raeburn  2336: =over 4
                   2337: 
1.648     raeburn  2338: =item * &csv_translate($text) 
1.37      matthew  2339: 
1.185     www      2340: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2341: format.
                   2342: 
                   2343: =cut
                   2344: 
1.180     matthew  2345: ###############################################################
                   2346: ###############################################################
1.37      matthew  2347: sub csv_translate {
                   2348:     my $text = shift;
                   2349:     $text =~ s/\"/\"\"/g;
1.209     albertel 2350:     $text =~ s/\n/ /g;
1.37      matthew  2351:     return $text;
                   2352: }
1.180     matthew  2353: 
                   2354: ###############################################################
                   2355: ###############################################################
                   2356: 
                   2357: =pod
                   2358: 
1.648     raeburn  2359: =item * &define_excel_formats()
1.180     matthew  2360: 
                   2361: Define some commonly used Excel cell formats.
                   2362: 
                   2363: Currently supported formats:
                   2364: 
                   2365: =over 4
                   2366: 
                   2367: =item header
                   2368: 
                   2369: =item bold
                   2370: 
                   2371: =item h1
                   2372: 
                   2373: =item h2
                   2374: 
                   2375: =item h3
                   2376: 
1.256     matthew  2377: =item h4
                   2378: 
                   2379: =item i
                   2380: 
1.180     matthew  2381: =item date
                   2382: 
                   2383: =back
                   2384: 
                   2385: Inputs: $workbook
                   2386: 
                   2387: Returns: $format, a hash reference.
                   2388: 
1.1057    foxr     2389: 
1.180     matthew  2390: =cut
                   2391: 
                   2392: ###############################################################
                   2393: ###############################################################
                   2394: sub define_excel_formats {
                   2395:     my ($workbook) = @_;
                   2396:     my $format;
                   2397:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2398:                                                 bottom    => 1,
                   2399:                                                 align     => 'center');
                   2400:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2401:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2402:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2403:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2404:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2405:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2406:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2407:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2408:     return $format;
                   2409: }
                   2410: 
                   2411: ###############################################################
                   2412: ###############################################################
1.113     bowersj2 2413: 
                   2414: =pod
                   2415: 
1.648     raeburn  2416: =item * &create_workbook()
1.255     matthew  2417: 
                   2418: Create an Excel worksheet.  If it fails, output message on the
                   2419: request object and return undefs.
                   2420: 
                   2421: Inputs: Apache request object
                   2422: 
                   2423: Returns (undef) on failure, 
                   2424:     Excel worksheet object, scalar with filename, and formats 
                   2425:     from &Apache::loncommon::define_excel_formats on success
                   2426: 
                   2427: =cut
                   2428: 
                   2429: ###############################################################
                   2430: ###############################################################
                   2431: sub create_workbook {
                   2432:     my ($r) = @_;
                   2433:         #
                   2434:     # Create the excel spreadsheet
                   2435:     my $filename = '/prtspool/'.
1.258     albertel 2436:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2437:         time.'_'.rand(1000000000).'.xls';
                   2438:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2439:     if (! defined($workbook)) {
                   2440:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2441:         $r->print(
                   2442:             '<p class="LC_error">'
                   2443:            .&mt('Problems occurred in creating the new Excel file.')
                   2444:            .' '.&mt('This error has been logged.')
                   2445:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2446:            .'</p>'
                   2447:         );
1.255     matthew  2448:         return (undef);
                   2449:     }
                   2450:     #
1.1014    foxr     2451:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2452:     #
                   2453:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2454:     return ($workbook,$filename,$format);
                   2455: }
                   2456: 
                   2457: ###############################################################
                   2458: ###############################################################
                   2459: 
                   2460: =pod
                   2461: 
1.648     raeburn  2462: =item * &create_text_file()
1.113     bowersj2 2463: 
1.542     raeburn  2464: Create a file to write to and eventually make available to the user.
1.256     matthew  2465: If file creation fails, outputs an error message on the request object and 
                   2466: return undefs.
1.113     bowersj2 2467: 
1.256     matthew  2468: Inputs: Apache request object, and file suffix
1.113     bowersj2 2469: 
1.256     matthew  2470: Returns (undef) on failure, 
                   2471:     Filehandle and filename on success.
1.113     bowersj2 2472: 
                   2473: =cut
                   2474: 
1.256     matthew  2475: ###############################################################
                   2476: ###############################################################
                   2477: sub create_text_file {
                   2478:     my ($r,$suffix) = @_;
                   2479:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2480:     my $fh;
                   2481:     my $filename = '/prtspool/'.
1.258     albertel 2482:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2483:         time.'_'.rand(1000000000).'.'.$suffix;
                   2484:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2485:     if (! defined($fh)) {
                   2486:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2487:         $r->print(
                   2488:             '<p class="LC_error">'
                   2489:            .&mt('Problems occurred in creating the output file.')
                   2490:            .' '.&mt('This error has been logged.')
                   2491:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2492:            .'</p>'
                   2493:         );
1.113     bowersj2 2494:     }
1.256     matthew  2495:     return ($fh,$filename)
1.113     bowersj2 2496: }
                   2497: 
                   2498: 
1.256     matthew  2499: =pod 
1.113     bowersj2 2500: 
                   2501: =back
                   2502: 
                   2503: =cut
1.37      matthew  2504: 
                   2505: ###############################################################
1.33      matthew  2506: ##        Home server <option> list generating code          ##
                   2507: ###############################################################
1.35      matthew  2508: 
1.169     www      2509: # ------------------------------------------
                   2510: 
                   2511: sub domain_select {
1.1289    raeburn  2512:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2513:     my @possdoms;
                   2514:     if (ref($incdoms) eq 'ARRAY') {
                   2515:         @possdoms = @{$incdoms};
                   2516:     } else {
                   2517:         @possdoms = &Apache::lonnet::all_domains();
                   2518:     }
                   2519: 
1.169     www      2520:     my %domains=map { 
1.514     albertel 2521: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2522:     } @possdoms;
                   2523: 
                   2524:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2525:         foreach my $dom (@{$excdoms}) {
                   2526:             delete($domains{$dom});
                   2527:         }
                   2528:     }
                   2529: 
1.169     www      2530:     if ($multiple) {
                   2531: 	$domains{''}=&mt('Any domain');
1.550     albertel 2532: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2533: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2534:     } else {
1.550     albertel 2535: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2536: 	return &select_form($name,$value,\%domains);
1.169     www      2537:     }
                   2538: }
                   2539: 
1.282     albertel 2540: #-------------------------------------------
                   2541: 
                   2542: =pod
                   2543: 
1.519     raeburn  2544: =head1 Routines for form select boxes
                   2545: 
                   2546: =over 4
                   2547: 
1.648     raeburn  2548: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2549: 
                   2550: Returns a string containing a <select> element int multiple mode
                   2551: 
                   2552: 
                   2553: Args:
                   2554:   $name - name of the <select> element
1.506     raeburn  2555:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2556:   $size - number of rows long the select element is
1.283     albertel 2557:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2558:           (shown text should already have been &mt())
1.506     raeburn  2559:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2560: 
1.282     albertel 2561: =cut
                   2562: 
                   2563: #-------------------------------------------
1.169     www      2564: sub multiple_select_form {
1.284     albertel 2565:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2566:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2567:     my $output='';
1.191     matthew  2568:     if (! defined($size)) {
                   2569:         $size = 4;
1.283     albertel 2570:         if (scalar(keys(%$hash))<4) {
                   2571:             $size = scalar(keys(%$hash));
1.191     matthew  2572:         }
                   2573:     }
1.734     bisitz   2574:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2575:     my @order;
1.506     raeburn  2576:     if (ref($order) eq 'ARRAY')  {
                   2577:         @order = @{$order};
                   2578:     } else {
                   2579:         @order = sort(keys(%$hash));
1.501     banghart 2580:     }
                   2581:     if (exists($$hash{'select_form_order'})) {
                   2582:         @order = @{$$hash{'select_form_order'}};
                   2583:     }
                   2584:         
1.284     albertel 2585:     foreach my $key (@order) {
1.356     albertel 2586:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2587:         $output.='selected="selected" ' if ($selected{$key});
                   2588:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2589:     }
                   2590:     $output.="</select>\n";
                   2591:     return $output;
                   2592: }
                   2593: 
1.88      www      2594: #-------------------------------------------
                   2595: 
                   2596: =pod
                   2597: 
1.1254    raeburn  2598: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2599: 
                   2600: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2601: allow a user to select options from a ref to a hash containing:
                   2602: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2603: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2604: An optional arg -- $readonly -- if true will cause the select form
                   2605: to be disabled, e.g., for the case where an instructor has a section-
                   2606: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2607: 
1.88      www      2608: See lonrights.pm for an example invocation and use.
                   2609: 
                   2610: =cut
                   2611: 
                   2612: #-------------------------------------------
                   2613: sub select_form {
1.1228    raeburn  2614:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2615:     return unless (ref($hashref) eq 'HASH');
                   2616:     if ($onchange) {
                   2617:         $onchange = ' onchange="'.$onchange.'"';
                   2618:     }
1.1228    raeburn  2619:     my $disabled;
                   2620:     if ($readonly) {
                   2621:         $disabled = ' disabled="disabled"';
                   2622:     }
                   2623:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2624:     my @keys;
1.970     raeburn  2625:     if (exists($hashref->{'select_form_order'})) {
                   2626: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2627:     } else {
1.970     raeburn  2628: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2629:     }
1.356     albertel 2630:     foreach my $key (@keys) {
                   2631:         $selectform.=
                   2632: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2633:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2634:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2635:     }
                   2636:     $selectform.="</select>";
                   2637:     return $selectform;
                   2638: }
                   2639: 
1.475     www      2640: # For display filters
                   2641: 
                   2642: sub display_filter {
1.1074    raeburn  2643:     my ($context) = @_;
1.475     www      2644:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2645:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2646:     my $phraseinput = 'hidden';
                   2647:     my $includeinput = 'hidden';
                   2648:     my ($checked,$includetypestext);
                   2649:     if ($env{'form.displayfilter'} eq 'containing') {
                   2650:         $phraseinput = 'text'; 
                   2651:         if ($context eq 'parmslog') {
                   2652:             $includeinput = 'checkbox';
                   2653:             if ($env{'form.includetypes'}) {
                   2654:                 $checked = ' checked="checked"';
                   2655:             }
                   2656:             $includetypestext = &mt('Include parameter types');
                   2657:         }
                   2658:     } else {
                   2659:         $includetypestext = '&nbsp;';
                   2660:     }
                   2661:     my ($additional,$secondid,$thirdid);
                   2662:     if ($context eq 'parmslog') {
                   2663:         $additional = 
                   2664:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2665:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2666:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2667:             '</label>';
                   2668:         $secondid = 'includetypes';
                   2669:         $thirdid = 'includetypestext';
                   2670:     }
                   2671:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2672:                                                     '$secondid','$thirdid')";
                   2673:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2674: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2675: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2676: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2677:            &mt('Filter: [_1]',
1.477     www      2678: 	   &select_form($env{'form.displayfilter'},
                   2679: 			'displayfilter',
1.970     raeburn  2680: 			{'currentfolder' => 'Current folder/page',
1.477     www      2681: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2682: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2683: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2684:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2685:                          '" />'.$additional;
                   2686: }
                   2687: 
                   2688: sub display_filter_js {
                   2689:     my $includetext = &mt('Include parameter types');
                   2690:     return <<"ENDJS";
                   2691:   
                   2692: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2693:     var firstType = 'hidden';
                   2694:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2695:         firstType = 'text';
                   2696:     }
                   2697:     firstObject = document.getElementById(firstid);
                   2698:     if (typeof(firstObject) == 'object') {
                   2699:         if (firstObject.type != firstType) {
                   2700:             changeInputType(firstObject,firstType);
                   2701:         }
                   2702:     }
                   2703:     if (context == 'parmslog') {
                   2704:         var secondType = 'hidden';
                   2705:         if (firstType == 'text') {
                   2706:             secondType = 'checkbox';
                   2707:         }
                   2708:         secondObject = document.getElementById(secondid);  
                   2709:         if (typeof(secondObject) == 'object') {
                   2710:             if (secondObject.type != secondType) {
                   2711:                 changeInputType(secondObject,secondType);
                   2712:             }
                   2713:         }
                   2714:         var textItem = document.getElementById(thirdid);
                   2715:         var currtext = textItem.innerHTML;
                   2716:         var newtext;
                   2717:         if (firstType == 'text') {
                   2718:             newtext = '$includetext';
                   2719:         } else {
                   2720:             newtext = '&nbsp;';
                   2721:         }
                   2722:         if (currtext != newtext) {
                   2723:             textItem.innerHTML = newtext;
                   2724:         }
                   2725:     }
                   2726:     return;
                   2727: }
                   2728: 
                   2729: function changeInputType(oldObject,newType) {
                   2730:     var newObject = document.createElement('input');
                   2731:     newObject.type = newType;
                   2732:     if (oldObject.size) {
                   2733:         newObject.size = oldObject.size;
                   2734:     }
                   2735:     if (oldObject.value) {
                   2736:         newObject.value = oldObject.value;
                   2737:     }
                   2738:     if (oldObject.name) {
                   2739:         newObject.name = oldObject.name;
                   2740:     }
                   2741:     if (oldObject.id) {
                   2742:         newObject.id = oldObject.id;
                   2743:     }
                   2744:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2745:     return;
                   2746: }
                   2747: 
                   2748: ENDJS
1.475     www      2749: }
                   2750: 
1.167     www      2751: sub gradeleveldescription {
                   2752:     my $gradelevel=shift;
                   2753:     my %gradelevels=(0 => 'Not specified',
                   2754: 		     1 => 'Grade 1',
                   2755: 		     2 => 'Grade 2',
                   2756: 		     3 => 'Grade 3',
                   2757: 		     4 => 'Grade 4',
                   2758: 		     5 => 'Grade 5',
                   2759: 		     6 => 'Grade 6',
                   2760: 		     7 => 'Grade 7',
                   2761: 		     8 => 'Grade 8',
                   2762: 		     9 => 'Grade 9',
                   2763: 		     10 => 'Grade 10',
                   2764: 		     11 => 'Grade 11',
                   2765: 		     12 => 'Grade 12',
                   2766: 		     13 => 'Grade 13',
                   2767: 		     14 => '100 Level',
                   2768: 		     15 => '200 Level',
                   2769: 		     16 => '300 Level',
                   2770: 		     17 => '400 Level',
                   2771: 		     18 => 'Graduate Level');
                   2772:     return &mt($gradelevels{$gradelevel});
                   2773: }
                   2774: 
1.163     www      2775: sub select_level_form {
                   2776:     my ($deflevel,$name)=@_;
                   2777:     unless ($deflevel) { $deflevel=0; }
1.167     www      2778:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2779:     for (my $i=0; $i<=18; $i++) {
                   2780:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2781:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2782:                 ">".&gradeleveldescription($i)."</option>\n";
                   2783:     }
                   2784:     $selectform.="</select>";
                   2785:     return $selectform;
1.163     www      2786: }
1.167     www      2787: 
1.35      matthew  2788: #-------------------------------------------
                   2789: 
1.45      matthew  2790: =pod
                   2791: 
1.1256    raeburn  2792: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2793: 
                   2794: Returns a string containing a <select name='$name' size='1'> form to 
                   2795: allow a user to select the domain to preform an operation in.  
                   2796: See loncreateuser.pm for an example invocation and use.
                   2797: 
1.90      www      2798: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2799: selected");
                   2800: 
1.743     raeburn  2801: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2802: 
1.910     raeburn  2803: 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.
                   2804: 
1.1121    raeburn  2805: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2806: 
                   2807: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2808: 
1.1256    raeburn  2809: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   2810: 
1.35      matthew  2811: =cut
                   2812: 
                   2813: #-------------------------------------------
1.34      matthew  2814: sub select_dom_form {
1.1256    raeburn  2815:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2816:     if ($onchange) {
1.874     raeburn  2817:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2818:     }
1.1256    raeburn  2819:     if ($disabled) {
                   2820:         $disabled = ' disabled="disabled"';
                   2821:     }
1.1121    raeburn  2822:     my (@domains,%exclude);
1.910     raeburn  2823:     if (ref($incdoms) eq 'ARRAY') {
                   2824:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2825:     } else {
                   2826:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2827:     }
1.90      www      2828:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2829:     if (ref($excdoms) eq 'ARRAY') {
                   2830:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2831:     }
1.1256    raeburn  2832:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2833:     foreach my $dom (@domains) {
1.1121    raeburn  2834:         next if ($exclude{$dom});
1.356     albertel 2835:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2836:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2837:         if ($showdomdesc) {
                   2838:             if ($dom ne '') {
                   2839:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2840:                 if ($domdesc ne '') {
                   2841:                     $selectdomain .= ' ('.$domdesc.')';
                   2842:                 }
                   2843:             } 
                   2844:         }
                   2845:         $selectdomain .= "</option>\n";
1.34      matthew  2846:     }
                   2847:     $selectdomain.="</select>";
                   2848:     return $selectdomain;
                   2849: }
                   2850: 
1.35      matthew  2851: #-------------------------------------------
                   2852: 
1.45      matthew  2853: =pod
                   2854: 
1.648     raeburn  2855: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2856: 
1.586     raeburn  2857: input: 4 arguments (two required, two optional) - 
                   2858:     $domain - domain of new user
                   2859:     $name - name of form element
                   2860:     $default - Value of 'default' causes a default item to be first 
                   2861:                             option, and selected by default. 
                   2862:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2863:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2864: output: returns 2 items: 
1.586     raeburn  2865: (a) form element which contains either:
                   2866:    (i) <select name="$name">
                   2867:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2868:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2869:        </select>
                   2870:        form item if there are multiple library servers in $domain, or
                   2871:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2872:        if there is only one library server in $domain.
                   2873: 
                   2874: (b) number of library servers found.
                   2875: 
                   2876: See loncreateuser.pm for example of use.
1.35      matthew  2877: 
                   2878: =cut
                   2879: 
                   2880: #-------------------------------------------
1.586     raeburn  2881: sub home_server_form_item {
                   2882:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2883:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2884:     my $result;
                   2885:     my $numlib = keys(%servers);
                   2886:     if ($numlib > 1) {
                   2887:         $result .= '<select name="'.$name.'" />'."\n";
                   2888:         if ($default) {
1.804     bisitz   2889:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2890:                        '</option>'."\n";
                   2891:         }
                   2892:         foreach my $hostid (sort(keys(%servers))) {
                   2893:             $result.= '<option value="'.$hostid.'">'.
                   2894: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2895:         }
                   2896:         $result .= '</select>'."\n";
                   2897:     } elsif ($numlib == 1) {
                   2898:         my $hostid;
                   2899:         foreach my $item (keys(%servers)) {
                   2900:             $hostid = $item;
                   2901:         }
                   2902:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2903:                    $hostid.'" />';
                   2904:                    if (!$hide) {
                   2905:                        $result .= $hostid.' '.$servers{$hostid};
                   2906:                    }
                   2907:                    $result .= "\n";
                   2908:     } elsif ($default) {
                   2909:         $result .= '<input type="hidden" name="'.$name.
                   2910:                    '" value="default" />';
                   2911:                    if (!$hide) {
                   2912:                        $result .= &mt('default');
                   2913:                    }
                   2914:                    $result .= "\n";
1.33      matthew  2915:     }
1.586     raeburn  2916:     return ($result,$numlib);
1.33      matthew  2917: }
1.112     bowersj2 2918: 
                   2919: =pod
                   2920: 
1.534     albertel 2921: =back 
                   2922: 
1.112     bowersj2 2923: =cut
1.87      matthew  2924: 
                   2925: ###############################################################
1.112     bowersj2 2926: ##                  Decoding User Agent                      ##
1.87      matthew  2927: ###############################################################
                   2928: 
                   2929: =pod
                   2930: 
1.112     bowersj2 2931: =head1 Decoding the User Agent
                   2932: 
                   2933: =over 4
                   2934: 
                   2935: =item * &decode_user_agent()
1.87      matthew  2936: 
                   2937: Inputs: $r
                   2938: 
                   2939: Outputs:
                   2940: 
                   2941: =over 4
                   2942: 
1.112     bowersj2 2943: =item * $httpbrowser
1.87      matthew  2944: 
1.112     bowersj2 2945: =item * $clientbrowser
1.87      matthew  2946: 
1.112     bowersj2 2947: =item * $clientversion
1.87      matthew  2948: 
1.112     bowersj2 2949: =item * $clientmathml
1.87      matthew  2950: 
1.112     bowersj2 2951: =item * $clientunicode
1.87      matthew  2952: 
1.112     bowersj2 2953: =item * $clientos
1.87      matthew  2954: 
1.1137    raeburn  2955: =item * $clientmobile
                   2956: 
1.1141    raeburn  2957: =item * $clientinfo
                   2958: 
1.1194    raeburn  2959: =item * $clientosversion
                   2960: 
1.87      matthew  2961: =back
                   2962: 
1.157     matthew  2963: =back 
                   2964: 
1.87      matthew  2965: =cut
                   2966: 
                   2967: ###############################################################
                   2968: ###############################################################
                   2969: sub decode_user_agent {
1.247     albertel 2970:     my ($r)=@_;
1.87      matthew  2971:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2972:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2973:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2974:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2975:     my $clientbrowser='unknown';
                   2976:     my $clientversion='0';
                   2977:     my $clientmathml='';
                   2978:     my $clientunicode='0';
1.1137    raeburn  2979:     my $clientmobile=0;
1.1194    raeburn  2980:     my $clientosversion='';
1.87      matthew  2981:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2982:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2983: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2984: 	    $clientbrowser=$bname;
                   2985:             $httpbrowser=~/$vreg/i;
                   2986: 	    $clientversion=$1;
                   2987:             $clientmathml=($clientversion>=$minv);
                   2988:             $clientunicode=($clientversion>=$univ);
                   2989: 	}
                   2990:     }
                   2991:     my $clientos='unknown';
1.1141    raeburn  2992:     my $clientinfo;
1.87      matthew  2993:     if (($httpbrowser=~/linux/i) ||
                   2994:         ($httpbrowser=~/unix/i) ||
                   2995:         ($httpbrowser=~/ux/i) ||
                   2996:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2997:     if (($httpbrowser=~/vax/i) ||
                   2998:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2999:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3000:     if (($httpbrowser=~/mac/i) ||
                   3001:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3002:     if ($httpbrowser=~/win/i) {
                   3003:         $clientos='win';
                   3004:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3005:             $clientosversion = $1;
                   3006:         }
                   3007:     }
1.87      matthew  3008:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3009:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3010:         $clientmobile=lc($1);
                   3011:     }
1.1141    raeburn  3012:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3013:         $clientinfo = 'firefox-'.$1;
                   3014:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3015:         $clientinfo = 'chromeframe-'.$1;
                   3016:     }
1.87      matthew  3017:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3018:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3019:             $clientosversion);
1.87      matthew  3020: }
                   3021: 
1.32      matthew  3022: ###############################################################
                   3023: ##    Authentication changing form generation subroutines    ##
                   3024: ###############################################################
                   3025: ##
                   3026: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3027: ## hash, and have reasonable default values.
                   3028: ##
                   3029: ##    formname = the name given in the <form> tag.
1.35      matthew  3030: #-------------------------------------------
                   3031: 
1.45      matthew  3032: =pod
                   3033: 
1.112     bowersj2 3034: =head1 Authentication Routines
                   3035: 
                   3036: =over 4
                   3037: 
1.648     raeburn  3038: =item * &authform_xxxxxx()
1.35      matthew  3039: 
                   3040: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3041: handle some of the conveniences required for authentication forms.  
                   3042: This is not an optimal method, but it works.  
                   3043: 
                   3044: =over 4
                   3045: 
1.112     bowersj2 3046: =item * authform_header
1.35      matthew  3047: 
1.112     bowersj2 3048: =item * authform_authorwarning
1.35      matthew  3049: 
1.112     bowersj2 3050: =item * authform_nochange
1.35      matthew  3051: 
1.112     bowersj2 3052: =item * authform_kerberos
1.35      matthew  3053: 
1.112     bowersj2 3054: =item * authform_internal
1.35      matthew  3055: 
1.112     bowersj2 3056: =item * authform_filesystem
1.35      matthew  3057: 
1.1310    raeburn  3058: =item * authform_lti
                   3059: 
1.35      matthew  3060: =back
                   3061: 
1.648     raeburn  3062: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3063: 
1.35      matthew  3064: =cut
                   3065: 
                   3066: #-------------------------------------------
1.32      matthew  3067: sub authform_header{  
                   3068:     my %in = (
                   3069:         formname => 'cu',
1.80      albertel 3070:         kerb_def_dom => '',
1.32      matthew  3071:         @_,
                   3072:     );
                   3073:     $in{'formname'} = 'document.' . $in{'formname'};
                   3074:     my $result='';
1.80      albertel 3075: 
                   3076: #---------------------------------------------- Code for upper case translation
                   3077:     my $Javascript_toUpperCase;
                   3078:     unless ($in{kerb_def_dom}) {
                   3079:         $Javascript_toUpperCase =<<"END";
                   3080:         switch (choice) {
                   3081:            case 'krb': currentform.elements[choicearg].value =
                   3082:                currentform.elements[choicearg].value.toUpperCase();
                   3083:                break;
                   3084:            default:
                   3085:         }
                   3086: END
                   3087:     } else {
                   3088:         $Javascript_toUpperCase = "";
                   3089:     }
                   3090: 
1.165     raeburn  3091:     my $radioval = "'nochange'";
1.591     raeburn  3092:     if (defined($in{'curr_authtype'})) {
                   3093:         if ($in{'curr_authtype'} ne '') {
                   3094:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3095:         }
1.174     matthew  3096:     }
1.165     raeburn  3097:     my $argfield = 'null';
1.591     raeburn  3098:     if (defined($in{'mode'})) {
1.165     raeburn  3099:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3100:             if (defined($in{'curr_autharg'})) {
                   3101:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3102:                     $argfield = "'$in{'curr_autharg'}'";
                   3103:                 }
                   3104:             }
                   3105:         }
                   3106:     }
                   3107: 
1.32      matthew  3108:     $result.=<<"END";
                   3109: var current = new Object();
1.165     raeburn  3110: current.radiovalue = $radioval;
                   3111: current.argfield = $argfield;
1.32      matthew  3112: 
                   3113: function changed_radio(choice,currentform) {
                   3114:     var choicearg = choice + 'arg';
                   3115:     // If a radio button in changed, we need to change the argfield
                   3116:     if (current.radiovalue != choice) {
                   3117:         current.radiovalue = choice;
                   3118:         if (current.argfield != null) {
                   3119:             currentform.elements[current.argfield].value = '';
                   3120:         }
                   3121:         if (choice == 'nochange') {
                   3122:             current.argfield = null;
                   3123:         } else {
                   3124:             current.argfield = choicearg;
                   3125:             switch(choice) {
                   3126:                 case 'krb': 
                   3127:                     currentform.elements[current.argfield].value = 
                   3128:                         "$in{'kerb_def_dom'}";
                   3129:                 break;
                   3130:               default:
                   3131:                 break;
                   3132:             }
                   3133:         }
                   3134:     }
                   3135:     return;
                   3136: }
1.22      www      3137: 
1.32      matthew  3138: function changed_text(choice,currentform) {
                   3139:     var choicearg = choice + 'arg';
                   3140:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3141:         $Javascript_toUpperCase
1.32      matthew  3142:         // clear old field
                   3143:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3144:             currentform.elements[current.argfield].value = '';
                   3145:         }
                   3146:         current.argfield = choicearg;
                   3147:     }
                   3148:     set_auth_radio_buttons(choice,currentform);
                   3149:     return;
1.20      www      3150: }
1.32      matthew  3151: 
                   3152: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3153:     var numauthchoices = currentform.login.length;
                   3154:     if (typeof numauthchoices  == "undefined") {
                   3155:         return;
                   3156:     } 
1.32      matthew  3157:     var i=0;
1.986     raeburn  3158:     while (i < numauthchoices) {
1.32      matthew  3159:         if (currentform.login[i].value == newvalue) { break; }
                   3160:         i++;
                   3161:     }
1.986     raeburn  3162:     if (i == numauthchoices) {
1.32      matthew  3163:         return;
                   3164:     }
                   3165:     current.radiovalue = newvalue;
                   3166:     currentform.login[i].checked = true;
                   3167:     return;
                   3168: }
                   3169: END
                   3170:     return $result;
                   3171: }
                   3172: 
1.1106    raeburn  3173: sub authform_authorwarning {
1.32      matthew  3174:     my $result='';
1.144     matthew  3175:     $result='<i>'.
                   3176:         &mt('As a general rule, only authors or co-authors should be '.
                   3177:             'filesystem authenticated '.
                   3178:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3179:     return $result;
                   3180: }
                   3181: 
1.1106    raeburn  3182: sub authform_nochange {
1.32      matthew  3183:     my %in = (
                   3184:               formname => 'document.cu',
                   3185:               kerb_def_dom => 'MSU.EDU',
                   3186:               @_,
                   3187:           );
1.1106    raeburn  3188:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3189:     my $result;
1.1104    raeburn  3190:     if (!$authnum) {
1.1105    raeburn  3191:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3192:     } else {
                   3193:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3194:                   '<input type="radio" name="login" value="nochange" '.
                   3195:                   'checked="checked" onclick="'.
1.281     albertel 3196:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3197: 	    '</label>';
1.586     raeburn  3198:     }
1.32      matthew  3199:     return $result;
                   3200: }
                   3201: 
1.591     raeburn  3202: sub authform_kerberos {
1.32      matthew  3203:     my %in = (
                   3204:               formname => 'document.cu',
                   3205:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3206:               kerb_def_auth => 'krb4',
1.32      matthew  3207:               @_,
                   3208:               );
1.586     raeburn  3209:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3210:         $autharg,$jscall,$disabled);
1.1106    raeburn  3211:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3212:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3213:        $check5 = ' checked="checked"';
1.80      albertel 3214:     } else {
1.772     bisitz   3215:        $check4 = ' checked="checked"';
1.80      albertel 3216:     }
1.1259    raeburn  3217:     if ($in{'readonly'}) {
                   3218:         $disabled = ' disabled="disabled"';
                   3219:     }
1.165     raeburn  3220:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3221:     if (defined($in{'curr_authtype'})) {
                   3222:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3223:             $krbcheck = ' checked="checked"';
1.623     raeburn  3224:             if (defined($in{'mode'})) {
                   3225:                 if ($in{'mode'} eq 'modifyuser') {
                   3226:                     $krbcheck = '';
                   3227:                 }
                   3228:             }
1.591     raeburn  3229:             if (defined($in{'curr_kerb_ver'})) {
                   3230:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3231:                     $check5 = ' checked="checked"';
1.591     raeburn  3232:                     $check4 = '';
                   3233:                 } else {
1.772     bisitz   3234:                     $check4 = ' checked="checked"';
1.591     raeburn  3235:                     $check5 = '';
                   3236:                 }
1.586     raeburn  3237:             }
1.591     raeburn  3238:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3239:                 $krbarg = $in{'curr_autharg'};
                   3240:             }
1.586     raeburn  3241:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3242:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3243:                     $result = 
                   3244:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3245:         $in{'curr_autharg'},$krbver);
                   3246:                 } else {
                   3247:                     $result =
                   3248:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3249:                 }
                   3250:                 return $result; 
                   3251:             }
                   3252:         }
                   3253:     } else {
                   3254:         if ($authnum == 1) {
1.784     bisitz   3255:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3256:         }
                   3257:     }
1.586     raeburn  3258:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3259:         return;
1.587     raeburn  3260:     } elsif ($authtype eq '') {
1.591     raeburn  3261:         if (defined($in{'mode'})) {
1.587     raeburn  3262:             if ($in{'mode'} eq 'modifycourse') {
                   3263:                 if ($authnum == 1) {
1.1259    raeburn  3264:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3265:                 }
                   3266:             }
                   3267:         }
1.586     raeburn  3268:     }
                   3269:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3270:     if ($authtype eq '') {
                   3271:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3272:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3273:                     $krbcheck.$disabled.' />';
1.586     raeburn  3274:     }
                   3275:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3276:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3277:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3278:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3279:          $in{'curr_authtype'} eq 'krb4')) {
                   3280:         $result .= &mt
1.144     matthew  3281:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3282:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3283:          '<label>'.$authtype,
1.281     albertel 3284:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3285:              'value="'.$krbarg.'" '.
1.1259    raeburn  3286:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3287:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3288:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3289: 	 '</label>');
1.586     raeburn  3290:     } elsif ($can_assign{'krb4'}) {
                   3291:         $result .= &mt
                   3292:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3293:          '[_3] Version 4 [_4]',
                   3294:          '<label>'.$authtype,
                   3295:          '</label><input type="text" size="10" name="krbarg" '.
                   3296:              'value="'.$krbarg.'" '.
1.1259    raeburn  3297:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3298:          '<label><input type="hidden" name="krbver" value="4" />',
                   3299:          '</label>');
                   3300:     } elsif ($can_assign{'krb5'}) {
                   3301:         $result .= &mt
                   3302:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3303:          '[_3] Version 5 [_4]',
                   3304:          '<label>'.$authtype,
                   3305:          '</label><input type="text" size="10" name="krbarg" '.
                   3306:              'value="'.$krbarg.'" '.
1.1259    raeburn  3307:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3308:          '<label><input type="hidden" name="krbver" value="5" />',
                   3309:          '</label>');
                   3310:     }
1.32      matthew  3311:     return $result;
                   3312: }
                   3313: 
1.1106    raeburn  3314: sub authform_internal {
1.586     raeburn  3315:     my %in = (
1.32      matthew  3316:                 formname => 'document.cu',
                   3317:                 kerb_def_dom => 'MSU.EDU',
                   3318:                 @_,
                   3319:                 );
1.1259    raeburn  3320:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3321:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3322:     if ($in{'readonly'}) {
                   3323:         $disabled = ' disabled="disabled"';
                   3324:     }
1.591     raeburn  3325:     if (defined($in{'curr_authtype'})) {
                   3326:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3327:             if ($can_assign{'int'}) {
1.772     bisitz   3328:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3329:                 if (defined($in{'mode'})) {
                   3330:                     if ($in{'mode'} eq 'modifyuser') {
                   3331:                         $intcheck = '';
                   3332:                     }
                   3333:                 }
1.591     raeburn  3334:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3335:                     $intarg = $in{'curr_autharg'};
                   3336:                 }
                   3337:             } else {
                   3338:                 $result = &mt('Currently internally authenticated.');
                   3339:                 return $result;
1.165     raeburn  3340:             }
                   3341:         }
1.586     raeburn  3342:     } else {
                   3343:         if ($authnum == 1) {
1.784     bisitz   3344:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3345:         }
                   3346:     }
                   3347:     if (!$can_assign{'int'}) {
                   3348:         return;
1.587     raeburn  3349:     } elsif ($authtype eq '') {
1.591     raeburn  3350:         if (defined($in{'mode'})) {
1.587     raeburn  3351:             if ($in{'mode'} eq 'modifycourse') {
                   3352:                 if ($authnum == 1) {
1.1259    raeburn  3353:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3354:                 }
                   3355:             }
                   3356:         }
1.165     raeburn  3357:     }
1.586     raeburn  3358:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3359:     if ($authtype eq '') {
                   3360:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3361:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3362:     }
1.605     bisitz   3363:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3364:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3365:     $result = &mt
1.144     matthew  3366:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3367:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3368:     $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  3369:     return $result;
                   3370: }
                   3371: 
1.1104    raeburn  3372: sub authform_local {
1.32      matthew  3373:     my %in = (
                   3374:               formname => 'document.cu',
                   3375:               kerb_def_dom => 'MSU.EDU',
                   3376:               @_,
                   3377:               );
1.1259    raeburn  3378:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3379:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3380:     if ($in{'readonly'}) {
                   3381:         $disabled = ' disabled="disabled"';
                   3382:     } 
1.591     raeburn  3383:     if (defined($in{'curr_authtype'})) {
                   3384:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3385:             if ($can_assign{'loc'}) {
1.772     bisitz   3386:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3387:                 if (defined($in{'mode'})) {
                   3388:                     if ($in{'mode'} eq 'modifyuser') {
                   3389:                         $loccheck = '';
                   3390:                     }
                   3391:                 }
1.591     raeburn  3392:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3393:                     $locarg = $in{'curr_autharg'};
                   3394:                 }
                   3395:             } else {
                   3396:                 $result = &mt('Currently using local (institutional) authentication.');
                   3397:                 return $result;
1.165     raeburn  3398:             }
                   3399:         }
1.586     raeburn  3400:     } else {
                   3401:         if ($authnum == 1) {
1.784     bisitz   3402:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3403:         }
                   3404:     }
                   3405:     if (!$can_assign{'loc'}) {
                   3406:         return;
1.587     raeburn  3407:     } elsif ($authtype eq '') {
1.591     raeburn  3408:         if (defined($in{'mode'})) {
1.587     raeburn  3409:             if ($in{'mode'} eq 'modifycourse') {
                   3410:                 if ($authnum == 1) {
1.1259    raeburn  3411:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3412:                 }
                   3413:             }
                   3414:         }
1.165     raeburn  3415:     }
1.586     raeburn  3416:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3417:     if ($authtype eq '') {
                   3418:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3419:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3420:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3421:     }
                   3422:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3423:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3424:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3425:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3426:     return $result;
                   3427: }
                   3428: 
1.1106    raeburn  3429: sub authform_filesystem {
1.32      matthew  3430:     my %in = (
                   3431:               formname => 'document.cu',
                   3432:               kerb_def_dom => 'MSU.EDU',
                   3433:               @_,
                   3434:               );
1.1259    raeburn  3435:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3436:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3437:     if ($in{'readonly'}) {
                   3438:         $disabled = ' disabled="disabled"';
                   3439:     }
1.591     raeburn  3440:     if (defined($in{'curr_authtype'})) {
                   3441:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3442:             if ($can_assign{'fsys'}) {
1.772     bisitz   3443:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3444:                 if (defined($in{'mode'})) {
                   3445:                     if ($in{'mode'} eq 'modifyuser') {
                   3446:                         $fsyscheck = '';
                   3447:                     }
                   3448:                 }
1.586     raeburn  3449:             } else {
                   3450:                 $result = &mt('Currently Filesystem Authenticated.');
                   3451:                 return $result;
1.1259    raeburn  3452:             }
1.586     raeburn  3453:         }
                   3454:     } else {
                   3455:         if ($authnum == 1) {
1.784     bisitz   3456:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3457:         }
                   3458:     }
                   3459:     if (!$can_assign{'fsys'}) {
                   3460:         return;
1.587     raeburn  3461:     } elsif ($authtype eq '') {
1.591     raeburn  3462:         if (defined($in{'mode'})) {
1.587     raeburn  3463:             if ($in{'mode'} eq 'modifycourse') {
                   3464:                 if ($authnum == 1) {
1.1259    raeburn  3465:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3466:                 }
                   3467:             }
                   3468:         }
1.586     raeburn  3469:     }
                   3470:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3471:     if ($authtype eq '') {
                   3472:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3473:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3474:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3475:     }
1.1310    raeburn  3476:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3477:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3478:     $result = &mt
1.144     matthew  3479:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3480:          '<label>'.$authtype,'</label>'.$autharg);
                   3481:     return $result;
                   3482: }
                   3483: 
                   3484: sub authform_lti {
                   3485:     my %in = (
                   3486:               formname => 'document.cu',
                   3487:               kerb_def_dom => 'MSU.EDU',
                   3488:               @_,
                   3489:               );
                   3490:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3491:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3492:     if ($in{'readonly'}) {
                   3493:         $disabled = ' disabled="disabled"';
                   3494:     }
                   3495:     if (defined($in{'curr_authtype'})) {
                   3496:         if ($in{'curr_authtype'} eq 'lti') {
                   3497:             if ($can_assign{'lti'}) {
                   3498:                 $lticheck = 'checked="checked" ';
                   3499:                 if (defined($in{'mode'})) {
                   3500:                     if ($in{'mode'} eq 'modifyuser') {
                   3501:                         $lticheck = '';
                   3502:                     }
                   3503:                 }
                   3504:             } else {
                   3505:                 $result = &mt('Currently LTI Authenticated.');
                   3506:                 return $result;
                   3507:             }
                   3508:         }
                   3509:     } else {
                   3510:         if ($authnum == 1) {
                   3511:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3512:         }
                   3513:     }
                   3514:     if (!$can_assign{'lti'}) {
                   3515:         return;
                   3516:     } elsif ($authtype eq '') {
                   3517:         if (defined($in{'mode'})) {
                   3518:             if ($in{'mode'} eq 'modifycourse') {
                   3519:                 if ($authnum == 1) {
                   3520:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3521:                 }
                   3522:             }
                   3523:         }
                   3524:     }
                   3525:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3526:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3527:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3528:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3529:                     $jscall.'"'.$disabled.' />';
                   3530:     }
                   3531:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3532:     if ($authtype) {
                   3533:         $result = &mt('[_1] LTI Authenticated',
                   3534:                       '<label>'.$authtype.'</label>'.$autharg);
                   3535:     } else {
                   3536:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3537:                   $autharg;
                   3538:     }
1.32      matthew  3539:     return $result;
                   3540: }
                   3541: 
1.586     raeburn  3542: sub get_assignable_auth {
                   3543:     my ($dom) = @_;
                   3544:     if ($dom eq '') {
                   3545:         $dom = $env{'request.role.domain'};
                   3546:     }
                   3547:     my %can_assign = (
                   3548:                           krb4 => 1,
                   3549:                           krb5 => 1,
                   3550:                           int  => 1,
                   3551:                           loc  => 1,
1.1310    raeburn  3552:                           lti  => 1,
1.586     raeburn  3553:                      );
                   3554:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3555:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3556:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3557:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3558:             my $context;
                   3559:             if ($env{'request.role'} =~ /^au/) {
                   3560:                 $context = 'author';
1.1259    raeburn  3561:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3562:                 $context = 'domain';
                   3563:             } elsif ($env{'request.course.id'}) {
                   3564:                 $context = 'course';
                   3565:             }
                   3566:             if ($context) {
                   3567:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3568:                    %can_assign = %{$authhash->{$context}}; 
                   3569:                 }
                   3570:             }
                   3571:         }
                   3572:     }
                   3573:     my $authnum = 0;
                   3574:     foreach my $key (keys(%can_assign)) {
                   3575:         if ($can_assign{$key}) {
                   3576:             $authnum ++;
                   3577:         }
                   3578:     }
                   3579:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3580:         $authnum --;
                   3581:     }
                   3582:     return ($authnum,%can_assign);
                   3583: }
                   3584: 
1.1331    raeburn  3585: sub check_passwd_rules {
                   3586:     my ($domain,$plainpass) = @_;
                   3587:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3588:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3589:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3590:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3591:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3592:             if ($passwdconf{'min'} > $min) {
                   3593:                 $min = $passwdconf{'min'};
                   3594:             }
1.1331    raeburn  3595:         }
                   3596:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3597:             $max = $passwdconf{'max'};
                   3598:         }
                   3599:         @chars = @{$passwdconf{'chars'}};
                   3600:     }
                   3601:     if (($min) && (length($plainpass) < $min)) {
                   3602:         push(@brokerule,'min');
                   3603:     }
                   3604:     if (($max) && (length($plainpass) > $max)) {
                   3605:         push(@brokerule,'max');
                   3606:     }
                   3607:     if (@chars) {
                   3608:         my %rules;
                   3609:         map { $rules{$_} = 1; } @chars;
                   3610:         if ($rules{'uc'}) {
                   3611:             unless ($plainpass =~ /[A-Z]/) {
                   3612:                 push(@brokerule,'uc');
                   3613:             }
                   3614:         }
                   3615:         if ($rules{'lc'}) {
1.1332    raeburn  3616:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3617:                 push(@brokerule,'lc');
                   3618:             }
                   3619:         }
                   3620:         if ($rules{'num'}) {
                   3621:             unless ($plainpass =~ /\d/) {
                   3622:                 push(@brokerule,'num');
                   3623:             }
                   3624:         }
                   3625:         if ($rules{'spec'}) {
                   3626:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3627:                 push(@brokerule,'spec');
                   3628:             }
                   3629:         }
                   3630:     }
                   3631:     if (@brokerule) {
                   3632:         my %rulenames = &Apache::lonlocal::texthash(
                   3633:             uc   => 'At least one upper case letter',
                   3634:             lc   => 'At least one lower case letter',
                   3635:             num  => 'At least one number',
                   3636:             spec => 'At least one non-alphanumeric',
                   3637:         );
                   3638:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3639:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3640:         $rulenames{'num'} .= ': 0123456789';
                   3641:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3642:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3643:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3644:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3645:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3646:             if (grep(/^$rule$/,@brokerule)) {
                   3647:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3648:             }
                   3649:         }
                   3650:         $warning .= '</ul>';
                   3651:     }
1.1332    raeburn  3652:     if (wantarray) {
                   3653:         return @brokerule;
                   3654:     }
1.1331    raeburn  3655:     return $warning;
                   3656: }
                   3657: 
1.1376    raeburn  3658: sub passwd_validation_js {
1.1377    raeburn  3659:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3660:     my (%passwdconf,$alertmsg);
                   3661:     if ($context eq 'linkprot') {
                   3662:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3663:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3664:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3665:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3666:             }
                   3667:         }
                   3668:         if ($id eq 'add') {
                   3669:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3670:         } elsif ($id =~ /^\d+$/) {
                   3671:             my $pos = $id+1;
                   3672:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3673:         } else {
                   3674:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3675:         }
                   3676:     } else {
                   3677:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3678:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3679:     }
1.1376    raeburn  3680:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3681:     $numrules = 0;
                   3682:     $min = $Apache::lonnet::passwdmin;
                   3683:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3684:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3685:             if ($passwdconf{'min'} > $min) {
                   3686:                 $min = $passwdconf{'min'};
                   3687:             }
                   3688:         }
                   3689:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3690:             $max = $passwdconf{'max'};
                   3691:             $numrules ++;
                   3692:         }
                   3693:         @chars = @{$passwdconf{'chars'}};
                   3694:         if (@chars) {
                   3695:             $numrules ++;
                   3696:         }
                   3697:     }
                   3698:     if ($min > 0) {
                   3699:         $numrules ++;
                   3700:     }
                   3701:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3702:         if ($min) {
                   3703:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3704:         }
                   3705:         if ($max) {
                   3706:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3707:         }
                   3708:         my (@charalerts,@charrules);
                   3709:         if (@chars) {
                   3710:             if (grep(/^uc$/,@chars)) {
                   3711:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3712:                 push(@charrules,'uc');
                   3713:             }
                   3714:             if (grep(/^lc$/,@chars)) {
                   3715:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3716:                 push(@charrules,'lc');
                   3717:             }
                   3718:             if (grep(/^num$/,@chars)) {
                   3719:                 push(@charalerts,&mt('contain at least one number'));
                   3720:                 push(@charrules,'num');
                   3721:             }
                   3722:             if (grep(/^spec$/,@chars)) {
                   3723:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3724:                 push(@charrules,'spec');
                   3725:             }
                   3726:         }
                   3727:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3728:                     qq|            var currpwval = $currpasswdval;\n|;
                   3729:             if ($min) {
                   3730:                 $intargjs .= qq|
                   3731:             if (currpwval.length < $min) {
                   3732:                 rulesmsg += ' - $alert{min}';
                   3733:             }
                   3734: |;
                   3735:             }
                   3736:             if ($max) {
                   3737:                 $intargjs .= qq|
                   3738:             if (currpwval.length > $max) {
                   3739:                 rulesmsg += ' - $alert{max}';
                   3740:             }
                   3741: |;
                   3742:             }
                   3743:             if (@chars > 0) {
                   3744:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3745:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3746:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3747:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3748:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3749:                 my %rules;
                   3750:                 map { $rules{$_} = 1; } @chars;
                   3751:                 if ($rules{'uc'}) {
                   3752:                     $intargjs .= qq|
                   3753:             var ucRegExp = /[A-Z]/;
                   3754:             if (!ucRegExp.test(currpwval)) {
                   3755:                 brokerules.push('uc');
                   3756:             }
                   3757: |;
                   3758:                 }
                   3759:                 if ($rules{'lc'}) {
                   3760:                     $intargjs .= qq|
                   3761:             var lcRegExp = /[a-z]/;
                   3762:             if (!lcRegExp.test(currpwval)) {
                   3763:                 brokerules.push('lc');
                   3764:             }
                   3765: |;
                   3766:                 }
                   3767:                 if ($rules{'num'}) {
                   3768:                      $intargjs .= qq|
                   3769:             var numRegExp = /[0-9]/;
                   3770:             if (!numRegExp.test(currpwval)) {
                   3771:                 brokerules.push('num');
                   3772:             }
                   3773: |;
                   3774:                 }
                   3775:                 if ($rules{'spec'}) {
                   3776:                      $intargjs .= q|
                   3777:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3778:             if (!specRegExp.test(currpwval)) {
                   3779:                 brokerules.push('spec');
                   3780:             }
                   3781: |;
                   3782:                 }
                   3783:                 $intargjs .= qq|
                   3784:             if (brokerules.length > 0) {
                   3785:                 for (var i=0; i<brokerules.length; i++) {
                   3786:                     for (var j=0; j<charrules.length; j++) {
                   3787:                         if (brokerules[i] == charrules[j]) {
                   3788:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3789:                             break;
                   3790:                         }
                   3791:                     }
                   3792:                 }
                   3793:             }
                   3794: |;
                   3795:             }
                   3796:             $intargjs .= qq|
                   3797:             if (rulesmsg != '') {
                   3798:                 rulesmsg = '$alertmsg'+rulesmsg;
                   3799:                 alert(rulesmsg);
                   3800:                 return false;
                   3801:             }
                   3802: |;
                   3803:     }
                   3804:     return ($numrules,$intargjs);
                   3805: }
                   3806: 
1.80      albertel 3807: ###############################################################
                   3808: ##    Get Kerberos Defaults for Domain                 ##
                   3809: ###############################################################
                   3810: ##
                   3811: ## Returns default kerberos version and an associated argument
                   3812: ## as listed in file domain.tab. If not listed, provides
                   3813: ## appropriate default domain and kerberos version.
                   3814: ##
                   3815: #-------------------------------------------
                   3816: 
                   3817: =pod
                   3818: 
1.648     raeburn  3819: =item * &get_kerberos_defaults()
1.80      albertel 3820: 
                   3821: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3822: version and domain. If not found, it defaults to version 4 and the 
                   3823: domain of the server.
1.80      albertel 3824: 
1.648     raeburn  3825: =over 4
                   3826: 
1.80      albertel 3827: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3828: 
1.648     raeburn  3829: =back
                   3830: 
                   3831: =back
                   3832: 
1.80      albertel 3833: =cut
                   3834: 
                   3835: #-------------------------------------------
                   3836: sub get_kerberos_defaults {
                   3837:     my $domain=shift;
1.641     raeburn  3838:     my ($krbdef,$krbdefdom);
                   3839:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3840:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3841:         $krbdef = $domdefaults{'auth_def'};
                   3842:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3843:     } else {
1.80      albertel 3844:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3845:         my $krbdefdom=$1;
                   3846:         $krbdefdom=~tr/a-z/A-Z/;
                   3847:         $krbdef = "krb4";
                   3848:     }
                   3849:     return ($krbdef,$krbdefdom);
                   3850: }
1.112     bowersj2 3851: 
1.32      matthew  3852: 
1.46      matthew  3853: ###############################################################
                   3854: ##                Thesaurus Functions                        ##
                   3855: ###############################################################
1.20      www      3856: 
1.46      matthew  3857: =pod
1.20      www      3858: 
1.112     bowersj2 3859: =head1 Thesaurus Functions
                   3860: 
                   3861: =over 4
                   3862: 
1.648     raeburn  3863: =item * &initialize_keywords()
1.46      matthew  3864: 
                   3865: Initializes the package variable %Keywords if it is empty.  Uses the
                   3866: package variable $thesaurus_db_file.
                   3867: 
                   3868: =cut
                   3869: 
                   3870: ###################################################
                   3871: 
                   3872: sub initialize_keywords {
                   3873:     return 1 if (scalar keys(%Keywords));
                   3874:     # If we are here, %Keywords is empty, so fill it up
                   3875:     #   Make sure the file we need exists...
                   3876:     if (! -e $thesaurus_db_file) {
                   3877:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3878:                                  " failed because it does not exist");
                   3879:         return 0;
                   3880:     }
                   3881:     #   Set up the hash as a database
                   3882:     my %thesaurus_db;
                   3883:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3884:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3885:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3886:                                  $thesaurus_db_file);
                   3887:         return 0;
                   3888:     } 
                   3889:     #  Get the average number of appearances of a word.
                   3890:     my $avecount = $thesaurus_db{'average.count'};
                   3891:     #  Put keywords (those that appear > average) into %Keywords
                   3892:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3893:         my ($count,undef) = split /:/,$data;
                   3894:         $Keywords{$word}++ if ($count > $avecount);
                   3895:     }
                   3896:     untie %thesaurus_db;
                   3897:     # Remove special values from %Keywords.
1.356     albertel 3898:     foreach my $value ('total.count','average.count') {
                   3899:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3900:   }
1.46      matthew  3901:     return 1;
                   3902: }
                   3903: 
                   3904: ###################################################
                   3905: 
                   3906: =pod
                   3907: 
1.648     raeburn  3908: =item * &keyword($word)
1.46      matthew  3909: 
                   3910: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3911: than the average number of times in the thesaurus database.  Calls 
                   3912: &initialize_keywords
                   3913: 
                   3914: =cut
                   3915: 
                   3916: ###################################################
1.20      www      3917: 
                   3918: sub keyword {
1.46      matthew  3919:     return if (!&initialize_keywords());
                   3920:     my $word=lc(shift());
                   3921:     $word=~s/\W//g;
                   3922:     return exists($Keywords{$word});
1.20      www      3923: }
1.46      matthew  3924: 
                   3925: ###############################################################
                   3926: 
                   3927: =pod 
1.20      www      3928: 
1.648     raeburn  3929: =item * &get_related_words()
1.46      matthew  3930: 
1.160     matthew  3931: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3932: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3933: will be returned.  The order of the words returned is determined by the
                   3934: database which holds them.
                   3935: 
                   3936: Uses global $thesaurus_db_file.
                   3937: 
1.1057    foxr     3938: 
1.46      matthew  3939: =cut
                   3940: 
                   3941: ###############################################################
                   3942: sub get_related_words {
                   3943:     my $keyword = shift;
                   3944:     my %thesaurus_db;
                   3945:     if (! -e $thesaurus_db_file) {
                   3946:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3947:                                  "failed because the file does not exist");
                   3948:         return ();
                   3949:     }
                   3950:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3951:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3952:         return ();
                   3953:     } 
                   3954:     my @Words=();
1.429     www      3955:     my $count=0;
1.46      matthew  3956:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3957: 	# The first element is the number of times
                   3958: 	# the word appears.  We do not need it now.
1.429     www      3959: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3960: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3961: 	my $threshold=$mostfrequentcount/10;
                   3962:         foreach my $possibleword (@RelatedWords) {
                   3963:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3964:             if ($wordcount>$threshold) {
                   3965: 		push(@Words,$word);
                   3966:                 $count++;
                   3967:                 if ($count>10) { last; }
                   3968: 	    }
1.20      www      3969:         }
                   3970:     }
1.46      matthew  3971:     untie %thesaurus_db;
                   3972:     return @Words;
1.14      harris41 3973: }
1.1090    foxr     3974: ###############################################################
                   3975: #
                   3976: #  Spell checking
                   3977: #
                   3978: 
                   3979: =pod
                   3980: 
1.1142    raeburn  3981: =back
                   3982: 
1.1090    foxr     3983: =head1 Spell checking
                   3984: 
                   3985: =over 4
                   3986: 
                   3987: =item * &check_spelling($wordlist $language)
                   3988: 
                   3989: Takes a string containing words and feeds it to an external
                   3990: spellcheck program via a pipeline. Returns a string containing
                   3991: them mis-spelled words.
                   3992: 
                   3993: Parameters:
                   3994: 
                   3995: =over 4
                   3996: 
                   3997: =item - $wordlist
                   3998: 
                   3999: String that will be fed into the spellcheck program.
                   4000: 
                   4001: =item - $language
                   4002: 
                   4003: Language string that specifies the language for which the spell
                   4004: check will be performed.
                   4005: 
                   4006: =back
                   4007: 
                   4008: =back
                   4009: 
                   4010: Note: This sub assumes that aspell is installed.
                   4011: 
                   4012: 
                   4013: =cut
                   4014: 
1.46      matthew  4015: 
1.1090    foxr     4016: sub check_spelling {
                   4017:     my ($wordlist, $language) = @_;
1.1091    foxr     4018:     my @misspellings;
                   4019:     
                   4020:     # Generate the speller and set the langauge.
                   4021:     # if explicitly selected:
1.1090    foxr     4022: 
1.1091    foxr     4023:     my $speller = Text::Aspell->new;
1.1090    foxr     4024:     if ($language) {
1.1091    foxr     4025: 	$speller->set_option('lang', $language);
1.1090    foxr     4026:     }
                   4027: 
1.1091    foxr     4028:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4029: 
1.1091    foxr     4030:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4031: 
1.1091    foxr     4032:     foreach my $word (@words) {
                   4033: 	if(! $speller->check($word)) {
                   4034: 	    push(@misspellings, $word);
1.1090    foxr     4035: 	}
                   4036:     }
1.1091    foxr     4037:     return join(' ', @misspellings);
                   4038:     
1.1090    foxr     4039: }
                   4040: 
1.61      www      4041: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4042: =pod
                   4043: 
1.112     bowersj2 4044: =head1 User Name Functions
                   4045: 
                   4046: =over 4
                   4047: 
1.648     raeburn  4048: =item * &plainname($uname,$udom,$first)
1.81      albertel 4049: 
1.112     bowersj2 4050: Takes a users logon name and returns it as a string in
1.226     albertel 4051: "first middle last generation" form 
                   4052: if $first is set to 'lastname' then it returns it as
                   4053: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4054: 
                   4055: =cut
1.61      www      4056: 
1.295     www      4057: 
1.81      albertel 4058: ###############################################################
1.61      www      4059: sub plainname {
1.226     albertel 4060:     my ($uname,$udom,$first)=@_;
1.537     albertel 4061:     return if (!defined($uname) || !defined($udom));
1.295     www      4062:     my %names=&getnames($uname,$udom);
1.226     albertel 4063:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4064: 					  $names{'middlename'},
                   4065: 					  $names{'lastname'},
                   4066: 					  $names{'generation'},$first);
                   4067:     $name=~s/^\s+//;
1.62      www      4068:     $name=~s/\s+$//;
                   4069:     $name=~s/\s+/ /g;
1.353     albertel 4070:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4071:     return $name;
1.61      www      4072: }
1.66      www      4073: 
                   4074: # -------------------------------------------------------------------- Nickname
1.81      albertel 4075: =pod
                   4076: 
1.648     raeburn  4077: =item * &nickname($uname,$udom)
1.81      albertel 4078: 
                   4079: Gets a users name and returns it as a string as
                   4080: 
                   4081: "&quot;nickname&quot;"
1.66      www      4082: 
1.81      albertel 4083: if the user has a nickname or
                   4084: 
                   4085: "first middle last generation"
                   4086: 
                   4087: if the user does not
                   4088: 
                   4089: =cut
1.66      www      4090: 
                   4091: sub nickname {
                   4092:     my ($uname,$udom)=@_;
1.537     albertel 4093:     return if (!defined($uname) || !defined($udom));
1.295     www      4094:     my %names=&getnames($uname,$udom);
1.68      albertel 4095:     my $name=$names{'nickname'};
1.66      www      4096:     if ($name) {
                   4097:        $name='&quot;'.$name.'&quot;'; 
                   4098:     } else {
                   4099:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4100: 	     $names{'lastname'}.' '.$names{'generation'};
                   4101:        $name=~s/\s+$//;
                   4102:        $name=~s/\s+/ /g;
                   4103:     }
                   4104:     return $name;
                   4105: }
                   4106: 
1.295     www      4107: sub getnames {
                   4108:     my ($uname,$udom)=@_;
1.537     albertel 4109:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4110:     if ($udom eq 'public' && $uname eq 'public') {
                   4111: 	return ('lastname' => &mt('Public'));
                   4112:     }
1.295     www      4113:     my $id=$uname.':'.$udom;
                   4114:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4115:     if ($cached) {
                   4116: 	return %{$names};
                   4117:     } else {
                   4118: 	my %loadnames=&Apache::lonnet::get('environment',
                   4119:                     ['firstname','middlename','lastname','generation','nickname'],
                   4120: 					 $udom,$uname);
                   4121: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4122: 	return %loadnames;
                   4123:     }
                   4124: }
1.61      www      4125: 
1.542     raeburn  4126: # -------------------------------------------------------------------- getemails
1.648     raeburn  4127: 
1.542     raeburn  4128: =pod
                   4129: 
1.648     raeburn  4130: =item * &getemails($uname,$udom)
1.542     raeburn  4131: 
                   4132: Gets a user's email information and returns it as a hash with keys:
                   4133: notification, critnotification, permanentemail
                   4134: 
                   4135: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4136: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4137:  
1.648     raeburn  4138: 
1.542     raeburn  4139: =cut
                   4140: 
1.648     raeburn  4141: 
1.466     albertel 4142: sub getemails {
                   4143:     my ($uname,$udom)=@_;
                   4144:     if ($udom eq 'public' && $uname eq 'public') {
                   4145: 	return;
                   4146:     }
1.467     www      4147:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4148:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4149:     my $id=$uname.':'.$udom;
                   4150:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4151:     if ($cached) {
                   4152: 	return %{$names};
                   4153:     } else {
                   4154: 	my %loadnames=&Apache::lonnet::get('environment',
                   4155:                     			   ['notification','critnotification',
                   4156: 					    'permanentemail'],
                   4157: 					   $udom,$uname);
                   4158: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4159: 	return %loadnames;
                   4160:     }
                   4161: }
                   4162: 
1.551     albertel 4163: sub flush_email_cache {
                   4164:     my ($uname,$udom)=@_;
                   4165:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4166:     if (!$uname) { $uname=$env{'user.name'};   }
                   4167:     return if ($udom eq 'public' && $uname eq 'public');
                   4168:     my $id=$uname.':'.$udom;
                   4169:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4170: }
                   4171: 
1.728     raeburn  4172: # -------------------------------------------------------------------- getlangs
                   4173: 
                   4174: =pod
                   4175: 
                   4176: =item * &getlangs($uname,$udom)
                   4177: 
                   4178: Gets a user's language preference and returns it as a hash with key:
                   4179: language.
                   4180: 
                   4181: =cut
                   4182: 
                   4183: 
                   4184: sub getlangs {
                   4185:     my ($uname,$udom) = @_;
                   4186:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4187:     if (!$uname) { $uname=$env{'user.name'};   }
                   4188:     my $id=$uname.':'.$udom;
                   4189:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4190:     if ($cached) {
                   4191:         return %{$langs};
                   4192:     } else {
                   4193:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4194:                                            $udom,$uname);
                   4195:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4196:         return %loadlangs;
                   4197:     }
                   4198: }
                   4199: 
                   4200: sub flush_langs_cache {
                   4201:     my ($uname,$udom)=@_;
                   4202:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4203:     if (!$uname) { $uname=$env{'user.name'};   }
                   4204:     return if ($udom eq 'public' && $uname eq 'public');
                   4205:     my $id=$uname.':'.$udom;
                   4206:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4207: }
                   4208: 
1.61      www      4209: # ------------------------------------------------------------------ Screenname
1.81      albertel 4210: 
                   4211: =pod
                   4212: 
1.648     raeburn  4213: =item * &screenname($uname,$udom)
1.81      albertel 4214: 
                   4215: Gets a users screenname and returns it as a string
                   4216: 
                   4217: =cut
1.61      www      4218: 
                   4219: sub screenname {
                   4220:     my ($uname,$udom)=@_;
1.258     albertel 4221:     if ($uname eq $env{'user.name'} &&
                   4222: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4223:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4224:     return $names{'screenname'};
1.62      www      4225: }
                   4226: 
1.212     albertel 4227: 
1.802     bisitz   4228: # ------------------------------------------------------------- Confirm Wrapper
                   4229: =pod
                   4230: 
1.1142    raeburn  4231: =item * &confirmwrapper($message)
1.802     bisitz   4232: 
                   4233: Wrap messages about completion of operation in box
                   4234: 
                   4235: =cut
                   4236: 
                   4237: sub confirmwrapper {
                   4238:     my ($message)=@_;
                   4239:     if ($message) {
                   4240:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4241:                .$message."\n"
                   4242:                .'</div>'."\n";
                   4243:     } else {
                   4244:         return $message;
                   4245:     }
                   4246: }
                   4247: 
1.62      www      4248: # ------------------------------------------------------------- Message Wrapper
                   4249: 
                   4250: sub messagewrapper {
1.369     www      4251:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4252:     return 
1.441     albertel 4253:         '<a href="/adm/email?compose=individual&amp;'.
                   4254:         'recname='.$username.'&amp;recdom='.$domain.
                   4255: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4256:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4257: }
1.802     bisitz   4258: 
1.74      www      4259: # --------------------------------------------------------------- Notes Wrapper
                   4260: 
                   4261: sub noteswrapper {
                   4262:     my ($link,$un,$do)=@_;
                   4263:     return 
1.896     amueller 4264: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4265: }
1.802     bisitz   4266: 
1.62      www      4267: # ------------------------------------------------------------- Aboutme Wrapper
                   4268: 
                   4269: sub aboutmewrapper {
1.1070    raeburn  4270:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4271:     if (!defined($username)  && !defined($domain)) {
                   4272:         return;
                   4273:     }
1.1096    raeburn  4274:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4275: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4276: }
                   4277: 
                   4278: # ------------------------------------------------------------ Syllabus Wrapper
                   4279: 
                   4280: sub syllabuswrapper {
1.707     bisitz   4281:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4282:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4283: }
1.14      harris41 4284: 
1.802     bisitz   4285: # -----------------------------------------------------------------------------
                   4286: 
1.208     matthew  4287: sub track_student_link {
1.887     raeburn  4288:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4289:     my $link ="/adm/trackstudent?";
1.208     matthew  4290:     my $title = 'View recent activity';
                   4291:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4292:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4293:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4294:         $title .= ' of this student';
1.268     albertel 4295:     } 
1.208     matthew  4296:     if (defined($target) && $target !~ /^\s*$/) {
                   4297:         $target = qq{target="$target"};
                   4298:     } else {
                   4299:         $target = '';
                   4300:     }
1.268     albertel 4301:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4302:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4303:     $title = &mt($title);
                   4304:     $linktext = &mt($linktext);
1.448     albertel 4305:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4306: 	&help_open_topic('View_recent_activity');
1.208     matthew  4307: }
                   4308: 
1.781     raeburn  4309: sub slot_reservations_link {
                   4310:     my ($linktext,$sname,$sdom,$target) = @_;
                   4311:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4312:     my $title = 'View slot reservation history';
                   4313:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4314:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4315:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4316:         $title .= ' of this student';
                   4317:     }
                   4318:     if (defined($target) && $target !~ /^\s*$/) {
                   4319:         $target = qq{target="$target"};
                   4320:     } else {
                   4321:         $target = '';
                   4322:     }
                   4323:     $title = &mt($title);
                   4324:     $linktext = &mt($linktext);
                   4325:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4326: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4327: 
                   4328: }
                   4329: 
1.508     www      4330: # ===================================================== Display a student photo
                   4331: 
                   4332: 
1.509     albertel 4333: sub student_image_tag {
1.508     www      4334:     my ($domain,$user)=@_;
                   4335:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4336:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4337: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4338:     } else {
                   4339: 	return '';
                   4340:     }
                   4341: }
                   4342: 
1.112     bowersj2 4343: =pod
                   4344: 
                   4345: =back
                   4346: 
                   4347: =head1 Access .tab File Data
                   4348: 
                   4349: =over 4
                   4350: 
1.648     raeburn  4351: =item * &languageids() 
1.112     bowersj2 4352: 
                   4353: returns list of all language ids
                   4354: 
                   4355: =cut
                   4356: 
1.14      harris41 4357: sub languageids {
1.16      harris41 4358:     return sort(keys(%language));
1.14      harris41 4359: }
                   4360: 
1.112     bowersj2 4361: =pod
                   4362: 
1.648     raeburn  4363: =item * &languagedescription() 
1.112     bowersj2 4364: 
                   4365: returns description of a specified language id
                   4366: 
                   4367: =cut
                   4368: 
1.14      harris41 4369: sub languagedescription {
1.125     www      4370:     my $code=shift;
                   4371:     return  ($supported_language{$code}?'* ':'').
                   4372:             $language{$code}.
1.126     www      4373: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4374: }
                   4375: 
1.1048    foxr     4376: =pod
                   4377: 
                   4378: =item * &plainlanguagedescription
                   4379: 
                   4380: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4381: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4382: 
                   4383: =cut
                   4384: 
1.145     www      4385: sub plainlanguagedescription {
                   4386:     my $code=shift;
                   4387:     return $language{$code};
                   4388: }
                   4389: 
1.1048    foxr     4390: =pod
                   4391: 
                   4392: =item * &supportedlanguagecode
                   4393: 
                   4394: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4395: code.
                   4396: 
                   4397: =cut
                   4398: 
1.145     www      4399: sub supportedlanguagecode {
                   4400:     my $code=shift;
                   4401:     return $supported_language{$code};
1.97      www      4402: }
                   4403: 
1.112     bowersj2 4404: =pod
                   4405: 
1.1048    foxr     4406: =item * &latexlanguage()
                   4407: 
                   4408: Given a language key code returns the correspondnig language to use
                   4409: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4410: is no supported hyphenation for the language code.
                   4411: 
                   4412: =cut
                   4413: 
                   4414: sub latexlanguage {
                   4415:     my $code = shift;
                   4416:     return $latex_language{$code};
                   4417: }
                   4418: 
                   4419: =pod
                   4420: 
                   4421: =item * &latexhyphenation()
                   4422: 
                   4423: Same as above but what's supplied is the language as it might be stored
                   4424: in the metadata.
                   4425: 
                   4426: =cut
                   4427: 
                   4428: sub latexhyphenation {
                   4429:     my $key = shift;
                   4430:     return $latex_language_bykey{$key};
                   4431: }
                   4432: 
                   4433: =pod
                   4434: 
1.648     raeburn  4435: =item * &copyrightids() 
1.112     bowersj2 4436: 
                   4437: returns list of all copyrights
                   4438: 
                   4439: =cut
                   4440: 
                   4441: sub copyrightids {
                   4442:     return sort(keys(%cprtag));
                   4443: }
                   4444: 
                   4445: =pod
                   4446: 
1.648     raeburn  4447: =item * &copyrightdescription() 
1.112     bowersj2 4448: 
                   4449: returns description of a specified copyright id
                   4450: 
                   4451: =cut
                   4452: 
                   4453: sub copyrightdescription {
1.166     www      4454:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4455: }
1.197     matthew  4456: 
                   4457: =pod
                   4458: 
1.648     raeburn  4459: =item * &source_copyrightids() 
1.192     taceyjo1 4460: 
                   4461: returns list of all source copyrights
                   4462: 
                   4463: =cut
                   4464: 
                   4465: sub source_copyrightids {
                   4466:     return sort(keys(%scprtag));
                   4467: }
                   4468: 
                   4469: =pod
                   4470: 
1.648     raeburn  4471: =item * &source_copyrightdescription() 
1.192     taceyjo1 4472: 
                   4473: returns description of a specified source copyright id
                   4474: 
                   4475: =cut
                   4476: 
                   4477: sub source_copyrightdescription {
                   4478:     return &mt($scprtag{shift(@_)});
                   4479: }
1.112     bowersj2 4480: 
                   4481: =pod
                   4482: 
1.648     raeburn  4483: =item * &filecategories() 
1.112     bowersj2 4484: 
                   4485: returns list of all file categories
                   4486: 
                   4487: =cut
                   4488: 
                   4489: sub filecategories {
                   4490:     return sort(keys(%category_extensions));
                   4491: }
                   4492: 
                   4493: =pod
                   4494: 
1.648     raeburn  4495: =item * &filecategorytypes() 
1.112     bowersj2 4496: 
                   4497: returns list of file types belonging to a given file
                   4498: category
                   4499: 
                   4500: =cut
                   4501: 
                   4502: sub filecategorytypes {
1.356     albertel 4503:     my ($cat) = @_;
1.1248    raeburn  4504:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4505:         return @{$category_extensions{lc($cat)}};
                   4506:     } else {
                   4507:         return ();
                   4508:     }
1.112     bowersj2 4509: }
                   4510: 
                   4511: =pod
                   4512: 
1.648     raeburn  4513: =item * &fileembstyle() 
1.112     bowersj2 4514: 
                   4515: returns embedding style for a specified file type
                   4516: 
                   4517: =cut
                   4518: 
                   4519: sub fileembstyle {
                   4520:     return $fe{lc(shift(@_))};
1.169     www      4521: }
                   4522: 
1.351     www      4523: sub filemimetype {
                   4524:     return $fm{lc(shift(@_))};
                   4525: }
                   4526: 
1.169     www      4527: 
                   4528: sub filecategoryselect {
                   4529:     my ($name,$value)=@_;
1.189     matthew  4530:     return &select_form($value,$name,
1.970     raeburn  4531:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4532: }
                   4533: 
                   4534: =pod
                   4535: 
1.648     raeburn  4536: =item * &filedescription() 
1.112     bowersj2 4537: 
                   4538: returns description for a specified file type
                   4539: 
                   4540: =cut
                   4541: 
                   4542: sub filedescription {
1.188     matthew  4543:     my $file_description = $fd{lc(shift())};
                   4544:     $file_description =~ s:([\[\]]):~$1:g;
                   4545:     return &mt($file_description);
1.112     bowersj2 4546: }
                   4547: 
                   4548: =pod
                   4549: 
1.648     raeburn  4550: =item * &filedescriptionex() 
1.112     bowersj2 4551: 
                   4552: returns description for a specified file type with
                   4553: extra formatting
                   4554: 
                   4555: =cut
                   4556: 
                   4557: sub filedescriptionex {
                   4558:     my $ex=shift;
1.188     matthew  4559:     my $file_description = $fd{lc($ex)};
                   4560:     $file_description =~ s:([\[\]]):~$1:g;
                   4561:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4562: }
                   4563: 
                   4564: # End of .tab access
                   4565: =pod
                   4566: 
                   4567: =back
                   4568: 
                   4569: =cut
                   4570: 
                   4571: # ------------------------------------------------------------------ File Types
                   4572: sub fileextensions {
                   4573:     return sort(keys(%fe));
                   4574: }
                   4575: 
1.97      www      4576: # ----------------------------------------------------------- Display Languages
                   4577: # returns a hash with all desired display languages
                   4578: #
                   4579: 
                   4580: sub display_languages {
                   4581:     my %languages=();
1.695     raeburn  4582:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4583: 	$languages{$lang}=1;
1.97      www      4584:     }
                   4585:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4586:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4587: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4588: 	    $languages{$lang}=1;
1.97      www      4589:         }
                   4590:     }
                   4591:     return %languages;
1.14      harris41 4592: }
                   4593: 
1.582     albertel 4594: sub languages {
                   4595:     my ($possible_langs) = @_;
1.695     raeburn  4596:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4597:     if (!ref($possible_langs)) {
                   4598: 	if( wantarray ) {
                   4599: 	    return @preferred_langs;
                   4600: 	} else {
                   4601: 	    return $preferred_langs[0];
                   4602: 	}
                   4603:     }
                   4604:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4605:     my @preferred_possibilities;
                   4606:     foreach my $preferred_lang (@preferred_langs) {
                   4607: 	if (exists($possibilities{$preferred_lang})) {
                   4608: 	    push(@preferred_possibilities, $preferred_lang);
                   4609: 	}
                   4610:     }
                   4611:     if( wantarray ) {
                   4612: 	return @preferred_possibilities;
                   4613:     }
                   4614:     return $preferred_possibilities[0];
                   4615: }
                   4616: 
1.742     raeburn  4617: sub user_lang {
                   4618:     my ($touname,$toudom,$fromcid) = @_;
                   4619:     my @userlangs;
                   4620:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4621:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4622:                     $env{'course.'.$fromcid.'.languages'}));
                   4623:     } else {
                   4624:         my %langhash = &getlangs($touname,$toudom);
                   4625:         if ($langhash{'languages'} ne '') {
                   4626:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4627:         } else {
                   4628:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4629:             if ($domdefs{'lang_def'} ne '') {
                   4630:                 @userlangs = ($domdefs{'lang_def'});
                   4631:             }
                   4632:         }
                   4633:     }
                   4634:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4635:     my $user_lh = Apache::localize->get_handle(@languages);
                   4636:     return $user_lh;
                   4637: }
                   4638: 
                   4639: 
1.112     bowersj2 4640: ###############################################################
                   4641: ##               Student Answer Attempts                     ##
                   4642: ###############################################################
                   4643: 
                   4644: =pod
                   4645: 
                   4646: =head1 Alternate Problem Views
                   4647: 
                   4648: =over 4
                   4649: 
1.648     raeburn  4650: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4651:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4652: 
                   4653: Return string with previous attempt on problem. Arguments:
                   4654: 
                   4655: =over 4
                   4656: 
                   4657: =item * $symb: Problem, including path
                   4658: 
                   4659: =item * $username: username of the desired student
                   4660: 
                   4661: =item * $domain: domain of the desired student
1.14      harris41 4662: 
1.112     bowersj2 4663: =item * $course: Course ID
1.14      harris41 4664: 
1.112     bowersj2 4665: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4666:     something
1.14      harris41 4667: 
1.112     bowersj2 4668: =item * $regexp: if string matches this regexp, the string will be
                   4669:     sent to $gradesub
1.14      harris41 4670: 
1.112     bowersj2 4671: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4672: 
1.1199    raeburn  4673: =item * $usec: section of the desired student
                   4674: 
                   4675: =item * $identifier: counter for student (multiple students one problem) or 
                   4676:     problem (one student; whole sequence).
                   4677: 
1.112     bowersj2 4678: =back
1.14      harris41 4679: 
1.112     bowersj2 4680: The output string is a table containing all desired attempts, if any.
1.16      harris41 4681: 
1.112     bowersj2 4682: =cut
1.1       albertel 4683: 
                   4684: sub get_previous_attempt {
1.1199    raeburn  4685:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4686:   my $prevattempts='';
1.43      ng       4687:   no strict 'refs';
1.1       albertel 4688:   if ($symb) {
1.3       albertel 4689:     my (%returnhash)=
                   4690:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4691:     if ($returnhash{'version'}) {
                   4692:       my %lasthash=();
                   4693:       my $version;
                   4694:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4695:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4696:             if ($key =~ /\.rawrndseed$/) {
                   4697:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4698:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4699:             } else {
                   4700:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4701:             }
1.19      harris41 4702:         }
1.1       albertel 4703:       }
1.596     albertel 4704:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4705:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4706:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4707:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4708:       foreach my $key (sort(keys(%lasthash))) {
                   4709: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4710: 	if ($#parts > 0) {
1.31      albertel 4711: 	  my $data=$parts[-1];
1.989     raeburn  4712:           next if ($data eq 'foilorder');
1.31      albertel 4713: 	  pop(@parts);
1.1010    www      4714:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4715:           if ($data eq 'type') {
                   4716:               unless ($showsurv) {
                   4717:                   my $id = join(',',@parts);
                   4718:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4719:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4720:                       $lasthidden{$ign.'.'.$id} = 1;
                   4721:                   }
1.945     raeburn  4722:               }
1.1199    raeburn  4723:               if ($identifier ne '') {
                   4724:                   my $id = join(',',@parts);
                   4725:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4726:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4727:                       $hidestatus{$ign.'.'.$id} = 1;
                   4728:                   }
                   4729:               }
                   4730:           } elsif ($data eq 'regrader') {
                   4731:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4732:                   my $id = join(',',@parts);
                   4733:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4734:               }
1.1010    www      4735:           } 
1.31      albertel 4736: 	} else {
1.41      ng       4737: 	  if ($#parts == 0) {
                   4738: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4739: 	  } else {
                   4740: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4741: 	  }
1.31      albertel 4742: 	}
1.16      harris41 4743:       }
1.596     albertel 4744:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4745:       if ($getattempt eq '') {
1.1199    raeburn  4746:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4747:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4748:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4749:                 foreach my $id (keys(%regraded)) {
                   4750:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4751:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4752:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4753:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4754:                     }
                   4755:                 }
                   4756:             }
1.1200    raeburn  4757:         }
                   4758: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4759:             my (@hidden,@unsolved);
1.945     raeburn  4760:             if (%typeparts) {
                   4761:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4762:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4763:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4764:                         push(@hidden,$id);
1.1199    raeburn  4765:                     } elsif ($identifier ne '') {
                   4766:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4767:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4768:                                 ($hidestatus{$id})) {
1.1200    raeburn  4769:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4770:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4771:                                 push(@{$solved{$id}},$version);
                   4772:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4773:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4774:                                 my $skip;
                   4775:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4776:                                     foreach my $reset (@{$resets{$id}}) {
                   4777:                                         if ($reset > $solved{$id}[-1]) {
                   4778:                                             $skip=1;
                   4779:                                             last;
                   4780:                                         }
                   4781:                                     }
                   4782:                                 }
                   4783:                                 unless ($skip) {
                   4784:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4785:                                     push(@unsolved,$partslist);
                   4786:                                 }
                   4787:                             }
                   4788:                         }
1.945     raeburn  4789:                     }
                   4790:                 }
                   4791:             }
                   4792:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4793:                            '<td>'.&mt('Transaction [_1]',$version);
                   4794:             if (@unsolved) {
                   4795:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4796:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4797:                                  &mt('Hide').'</label></span>';
                   4798:             }
                   4799:             $prevattempts .= '</td>';
1.945     raeburn  4800:             if (@hidden) {
                   4801:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4802:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4803:                     my $hide;
                   4804:                     foreach my $id (@hidden) {
                   4805:                         if ($key =~ /^\Q$id\E/) {
                   4806:                             $hide = 1;
                   4807:                             last;
                   4808:                         }
                   4809:                     }
                   4810:                     if ($hide) {
                   4811:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4812:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4813:                             my $value = &format_previous_attempt_value($key,
                   4814:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4815:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4816:                         } else {
                   4817:                             $prevattempts.='<td>&nbsp;</td>';
                   4818:                         }
                   4819:                     } else {
                   4820:                         if ($key =~ /\./) {
1.1212    raeburn  4821:                             my $value = $returnhash{$version.':'.$key};
                   4822:                             if ($key =~ /\.rndseed$/) {
                   4823:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4824:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4825:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4826:                                 }
                   4827:                             }
                   4828:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4829:                                            '&nbsp;</td>';
1.945     raeburn  4830:                         } else {
                   4831:                             $prevattempts.='<td>&nbsp;</td>';
                   4832:                         }
                   4833:                     }
                   4834:                 }
                   4835:             } else {
                   4836: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4837:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4838:                     my $value = $returnhash{$version.':'.$key};
                   4839:                     if ($key =~ /\.rndseed$/) {
                   4840:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4841:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4842:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4843:                         }
                   4844:                     }
                   4845:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4846:                                    '&nbsp;</td>';
1.945     raeburn  4847: 	        }
                   4848:             }
                   4849: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4850: 	 }
1.1       albertel 4851:       }
1.945     raeburn  4852:       my @currhidden = keys(%lasthidden);
1.596     albertel 4853:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4854:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4855:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4856:           if (%typeparts) {
                   4857:               my $hidden;
                   4858:               foreach my $id (@currhidden) {
                   4859:                   if ($key =~ /^\Q$id\E/) {
                   4860:                       $hidden = 1;
                   4861:                       last;
                   4862:                   }
                   4863:               }
                   4864:               if ($hidden) {
                   4865:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4866:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4867:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4868:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4869:                           $value = &$gradesub($value);
                   4870:                       }
1.1173    kruse    4871:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4872:                   } else {
                   4873:                       $prevattempts.='<td>&nbsp;</td>';
                   4874:                   }
                   4875:               } else {
                   4876:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4877:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4878:                       $value = &$gradesub($value);
                   4879:                   }
1.1173    kruse    4880:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4881:               }
                   4882:           } else {
                   4883: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4884: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4885:                   $value = &$gradesub($value);
                   4886:               }
1.1173    kruse    4887: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4888:           }
1.16      harris41 4889:       }
1.596     albertel 4890:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4891:     } else {
1.1305    raeburn  4892:       my $msg;
                   4893:       if ($symb =~ /ext\.tool$/) {
                   4894:           $msg = &mt('No grade passed back.');
                   4895:       } else {
                   4896:           $msg = &mt('Nothing submitted - no attempts.');
                   4897:       }
1.596     albertel 4898:       $prevattempts=
                   4899: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  4900: 	  '<td>'.$msg.'</td>'.
1.596     albertel 4901: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4902:     }
                   4903:   } else {
1.596     albertel 4904:     $prevattempts=
                   4905: 	  &start_data_table().&start_data_table_row().
                   4906: 	  '<td>'.&mt('No data.').'</td>'.
                   4907: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4908:   }
1.10      albertel 4909: }
                   4910: 
1.581     albertel 4911: sub format_previous_attempt_value {
                   4912:     my ($key,$value) = @_;
1.1011    www      4913:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4914:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4915:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4916:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4917:     } elsif ($key =~ /answerstring$/) {
                   4918:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4919:         my @answer = %answers;
                   4920:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4921:         my @anskeys = sort(keys(%answers));
                   4922:         if (@anskeys == 1) {
                   4923:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4924:             if ($answer =~ m{\0}) {
                   4925:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4926:             }
                   4927:             my $tag_internal_answer_name = 'INTERNAL';
                   4928:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4929:                 $value = $answer; 
                   4930:             } else {
                   4931:                 $value = $anskeys[0].'='.$answer;
                   4932:             }
                   4933:         } else {
                   4934:             foreach my $ans (@anskeys) {
                   4935:                 my $answer = $answers{$ans};
1.1001    raeburn  4936:                 if ($answer =~ m{\0}) {
                   4937:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4938:                 }
                   4939:                 $value .=  $ans.'='.$answer.'<br />';;
                   4940:             } 
                   4941:         }
1.581     albertel 4942:     } else {
1.1173    kruse    4943:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4944:     }
                   4945:     return $value;
                   4946: }
                   4947: 
                   4948: 
1.107     albertel 4949: sub relative_to_absolute {
                   4950:     my ($url,$output)=@_;
                   4951:     my $parser=HTML::TokeParser->new(\$output);
                   4952:     my $token;
                   4953:     my $thisdir=$url;
                   4954:     my @rlinks=();
                   4955:     while ($token=$parser->get_token) {
                   4956: 	if ($token->[0] eq 'S') {
                   4957: 	    if ($token->[1] eq 'a') {
                   4958: 		if ($token->[2]->{'href'}) {
                   4959: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4960: 		}
                   4961: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4962: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4963: 	    } elsif ($token->[1] eq 'base') {
                   4964: 		$thisdir=$token->[2]->{'href'};
                   4965: 	    }
                   4966: 	}
                   4967:     }
                   4968:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4969:     foreach my $link (@rlinks) {
1.726     raeburn  4970: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4971: 		($link=~/^\//) ||
                   4972: 		($link=~/^javascript:/i) ||
                   4973: 		($link=~/^mailto:/i) ||
                   4974: 		($link=~/^\#/)) {
                   4975: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4976: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4977: 	}
                   4978:     }
                   4979: # -------------------------------------------------- Deal with Applet codebases
                   4980:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4981:     return $output;
                   4982: }
                   4983: 
1.112     bowersj2 4984: =pod
                   4985: 
1.648     raeburn  4986: =item * &get_student_view()
1.112     bowersj2 4987: 
                   4988: show a snapshot of what student was looking at
                   4989: 
                   4990: =cut
                   4991: 
1.10      albertel 4992: sub get_student_view {
1.186     albertel 4993:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4994:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4995:   my (%form);
1.10      albertel 4996:   my @elements=('symb','courseid','domain','username');
                   4997:   foreach my $element (@elements) {
1.186     albertel 4998:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4999:   }
1.186     albertel 5000:   if (defined($moreenv)) {
                   5001:       %form=(%form,%{$moreenv});
                   5002:   }
1.236     albertel 5003:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5004:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5005:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5006:       $feedurl =~ s{^/adm/wrapper}{};
                   5007:   }
1.650     www      5008:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5009:   $userview=~s/\<body[^\>]*\>//gi;
                   5010:   $userview=~s/\<\/body\>//gi;
                   5011:   $userview=~s/\<html\>//gi;
                   5012:   $userview=~s/\<\/html\>//gi;
                   5013:   $userview=~s/\<head\>//gi;
                   5014:   $userview=~s/\<\/head\>//gi;
                   5015:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5016:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5017:   if (wantarray) {
                   5018:      return ($userview,$response);
                   5019:   } else {
                   5020:      return $userview;
                   5021:   }
                   5022: }
                   5023: 
                   5024: sub get_student_view_with_retries {
                   5025:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5026: 
                   5027:     my $ok = 0;                 # True if we got a good response.
                   5028:     my $content;
                   5029:     my $response;
                   5030: 
                   5031:     # Try to get the student_view done. within the retries count:
                   5032:     
                   5033:     do {
                   5034:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5035:          $ok      = $response->is_success;
                   5036:          if (!$ok) {
                   5037:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5038:          }
                   5039:          $retries--;
                   5040:     } while (!$ok && ($retries > 0));
                   5041:     
                   5042:     if (!$ok) {
                   5043:        $content = '';          # On error return an empty content.
                   5044:     }
1.651     www      5045:     if (wantarray) {
                   5046:        return ($content, $response);
                   5047:     } else {
                   5048:        return $content;
                   5049:     }
1.11      albertel 5050: }
                   5051: 
1.1349    raeburn  5052: sub css_links {
                   5053:     my ($currsymb,$level) = @_;
                   5054:     my ($links,@symbs,%cssrefs,%httpref);
                   5055:     if ($level eq 'map') {
                   5056:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5057:         if (ref($navmap)) {
                   5058:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5059:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5060:             foreach my $res (@resources) {
                   5061:                 if (ref($res) && $res->symb()) {
                   5062:                     push(@symbs,$res->symb());
                   5063:                 }
                   5064:             }
                   5065:         }
                   5066:     } else {
                   5067:         @symbs = ($currsymb);
                   5068:     }
                   5069:     foreach my $symb (@symbs) {
                   5070:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5071:         if ($css_href =~ /\S/) {
                   5072:             unless ($css_href =~ m{https?://}) {
                   5073:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5074:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5075:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5076:                 unless ($css_href =~ m{^/}) {
                   5077:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5078:                 }
                   5079:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5080:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5081:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5082:                         my $thisurl = $proburl;
                   5083:                         if ($env{'httpref.'.$proburl}) {
                   5084:                             $thisurl = $env{'httpref.'.$proburl};
                   5085:                         }
                   5086:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5087:                     }
                   5088:                 }
                   5089:             }
                   5090:             $cssrefs{$css_href} = 1;
                   5091:         }
                   5092:     }
                   5093:     if (keys(%httpref)) {
                   5094:         &Apache::lonnet::appenv(\%httpref);
                   5095:     }
                   5096:     if (keys(%cssrefs)) {
                   5097:         foreach my $css_href (keys(%cssrefs)) {
                   5098:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5099:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5100:         }
                   5101:     }
                   5102:     return $links;
                   5103: }
                   5104: 
1.112     bowersj2 5105: =pod
                   5106: 
1.648     raeburn  5107: =item * &get_student_answers() 
1.112     bowersj2 5108: 
                   5109: show a snapshot of how student was answering problem
                   5110: 
                   5111: =cut
                   5112: 
1.11      albertel 5113: sub get_student_answers {
1.100     sakharuk 5114:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5115:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5116:   my (%moreenv);
1.11      albertel 5117:   my @elements=('symb','courseid','domain','username');
                   5118:   foreach my $element (@elements) {
1.186     albertel 5119:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5120:   }
1.186     albertel 5121:   $moreenv{'grade_target'}='answer';
                   5122:   %moreenv=(%form,%moreenv);
1.497     raeburn  5123:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5124:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5125:   return $userview;
1.1       albertel 5126: }
1.116     albertel 5127: 
                   5128: =pod
                   5129: 
                   5130: =item * &submlink()
                   5131: 
1.242     albertel 5132: Inputs: $text $uname $udom $symb $target
1.116     albertel 5133: 
                   5134: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5135: 
                   5136: =cut
                   5137: 
                   5138: ###############################################
                   5139: sub submlink {
1.242     albertel 5140:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5141:     if (!($uname && $udom)) {
                   5142: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5143: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5144: 	if (!$symb) { $symb=$cursymb; }
                   5145:     }
1.254     matthew  5146:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5147:     $symb=&escape($symb);
1.960     bisitz   5148:     if ($target) { $target=" target=\"$target\""; }
                   5149:     return
                   5150:         '<a href="/adm/grades?command=submission'.
                   5151:         '&amp;symb='.$symb.
                   5152:         '&amp;student='.$uname.
                   5153:         '&amp;userdom='.$udom.'"'.
                   5154:         $target.'>'.$text.'</a>';
1.242     albertel 5155: }
                   5156: ##############################################
                   5157: 
                   5158: =pod
                   5159: 
                   5160: =item * &pgrdlink()
                   5161: 
                   5162: Inputs: $text $uname $udom $symb $target
                   5163: 
                   5164: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5165: 
                   5166: =cut
                   5167: 
                   5168: ###############################################
                   5169: sub pgrdlink {
                   5170:     my $link=&submlink(@_);
                   5171:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5172:     return $link;
                   5173: }
                   5174: ##############################################
                   5175: 
                   5176: =pod
                   5177: 
                   5178: =item * &pprmlink()
                   5179: 
                   5180: Inputs: $text $uname $udom $symb $target
                   5181: 
                   5182: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5183: student and a specific resource
1.242     albertel 5184: 
                   5185: =cut
                   5186: 
                   5187: ###############################################
                   5188: sub pprmlink {
                   5189:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5190:     if (!($uname && $udom)) {
                   5191: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5192: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5193: 	if (!$symb) { $symb=$cursymb; }
                   5194:     }
1.254     matthew  5195:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5196:     $symb=&escape($symb);
1.242     albertel 5197:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5198:     return '<a href="/adm/parmset?command=set&amp;'.
                   5199: 	'symb='.$symb.'&amp;uname='.$uname.
                   5200: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5201: }
                   5202: ##############################################
1.37      matthew  5203: 
1.112     bowersj2 5204: =pod
                   5205: 
                   5206: =back
                   5207: 
                   5208: =cut
                   5209: 
1.37      matthew  5210: ###############################################
1.51      www      5211: 
                   5212: 
                   5213: sub timehash {
1.687     raeburn  5214:     my ($thistime) = @_;
                   5215:     my $timezone = &Apache::lonlocal::gettimezone();
                   5216:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5217:                      ->set_time_zone($timezone);
                   5218:     my $wday = $dt->day_of_week();
                   5219:     if ($wday == 7) { $wday = 0; }
                   5220:     return ( 'second' => $dt->second(),
                   5221:              'minute' => $dt->minute(),
                   5222:              'hour'   => $dt->hour(),
                   5223:              'day'     => $dt->day_of_month(),
                   5224:              'month'   => $dt->month(),
                   5225:              'year'    => $dt->year(),
                   5226:              'weekday' => $wday,
                   5227:              'dayyear' => $dt->day_of_year(),
                   5228:              'dlsav'   => $dt->is_dst() );
1.51      www      5229: }
                   5230: 
1.370     www      5231: sub utc_string {
                   5232:     my ($date)=@_;
1.371     www      5233:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5234: }
                   5235: 
1.51      www      5236: sub maketime {
                   5237:     my %th=@_;
1.687     raeburn  5238:     my ($epoch_time,$timezone,$dt);
                   5239:     $timezone = &Apache::lonlocal::gettimezone();
                   5240:     eval {
                   5241:         $dt = DateTime->new( year   => $th{'year'},
                   5242:                              month  => $th{'month'},
                   5243:                              day    => $th{'day'},
                   5244:                              hour   => $th{'hour'},
                   5245:                              minute => $th{'minute'},
                   5246:                              second => $th{'second'},
                   5247:                              time_zone => $timezone,
                   5248:                          );
                   5249:     };
                   5250:     if (!$@) {
                   5251:         $epoch_time = $dt->epoch;
                   5252:         if ($epoch_time) {
                   5253:             return $epoch_time;
                   5254:         }
                   5255:     }
1.51      www      5256:     return POSIX::mktime(
                   5257:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5258:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5259: }
                   5260: 
                   5261: #########################################
1.51      www      5262: 
                   5263: sub findallcourses {
1.482     raeburn  5264:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5265:     my %roles;
                   5266:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5267:     my %courses;
1.51      www      5268:     my $now=time;
1.482     raeburn  5269:     if (!defined($uname)) {
                   5270:         $uname = $env{'user.name'};
                   5271:     }
                   5272:     if (!defined($udom)) {
                   5273:         $udom = $env{'user.domain'};
                   5274:     }
                   5275:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5276:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5277:         if (!%roles) {
                   5278:             %roles = (
                   5279:                        cc => 1,
1.907     raeburn  5280:                        co => 1,
1.482     raeburn  5281:                        in => 1,
                   5282:                        ep => 1,
                   5283:                        ta => 1,
                   5284:                        cr => 1,
                   5285:                        st => 1,
                   5286:              );
                   5287:         }
                   5288:         foreach my $entry (keys(%roleshash)) {
                   5289:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5290:             if ($trole =~ /^cr/) { 
                   5291:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5292:             } else {
                   5293:                 next if (!exists($roles{$trole}));
                   5294:             }
                   5295:             if ($tend) {
                   5296:                 next if ($tend < $now);
                   5297:             }
                   5298:             if ($tstart) {
                   5299:                 next if ($tstart > $now);
                   5300:             }
1.1058    raeburn  5301:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5302:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5303:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5304:             if ($secpart eq '') {
                   5305:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5306:                 $sec = 'none';
1.1058    raeburn  5307:                 $value .= $cnum.'/';
1.482     raeburn  5308:             } else {
                   5309:                 $cnum = $cnumpart;
                   5310:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5311:                 $value .= $cnum.'/'.$sec;
                   5312:             }
                   5313:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5314:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5315:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5316:                 }
                   5317:             } else {
                   5318:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5319:             }
1.482     raeburn  5320:         }
                   5321:     } else {
                   5322:         foreach my $key (keys(%env)) {
1.483     albertel 5323: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5324:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5325: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5326: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5327: 	        next if (%roles && !exists($roles{$role}));
                   5328: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5329:                 my $active=1;
                   5330:                 if ($starttime) {
                   5331: 		    if ($now<$starttime) { $active=0; }
                   5332:                 }
                   5333:                 if ($endtime) {
                   5334:                     if ($now>$endtime) { $active=0; }
                   5335:                 }
                   5336:                 if ($active) {
1.1058    raeburn  5337:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5338:                     if ($sec eq '') {
                   5339:                         $sec = 'none';
1.1058    raeburn  5340:                     } else {
                   5341:                         $value .= $sec;
                   5342:                     }
                   5343:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5344:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5345:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5346:                         }
                   5347:                     } else {
                   5348:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5349:                     }
1.474     raeburn  5350:                 }
                   5351:             }
1.51      www      5352:         }
                   5353:     }
1.474     raeburn  5354:     return %courses;
1.51      www      5355: }
1.37      matthew  5356: 
1.54      www      5357: ###############################################
1.474     raeburn  5358: 
                   5359: sub blockcheck {
1.1372    raeburn  5360:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5361:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5362:         my ($has_evb,$check_ipaccess);
                   5363:         my $dom = $env{'user.domain'};
                   5364:         if ($env{'request.course.id'}) {
                   5365:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5366:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5367:             my $checkrole = "cm./$cdom/$cnum";
                   5368:             my $sec = $env{'request.course.sec'};
                   5369:             if ($sec ne '') {
                   5370:                 $checkrole .= "/$sec";
                   5371:             }
                   5372:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5373:                 ($env{'request.role'} !~ /^st/)) {
                   5374:                 $has_evb = 1;
                   5375:             }
                   5376:             unless ($has_evb) {
                   5377:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5378:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5379:                     if ($udom eq $cdom) {
                   5380:                         $check_ipaccess = 1;
                   5381:                     }
                   5382:                 }
                   5383:             }
1.1375    raeburn  5384:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5385:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5386:             my $checkrole;
                   5387:             if ($env{'request.role.domain'} eq '') {
                   5388:                 $checkrole = "cm./$env{'user.domain'}/";
                   5389:             } else {
                   5390:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5391:             }
                   5392:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5393:                 $has_evb = 1;
                   5394:             }
1.1372    raeburn  5395:         }
                   5396:         unless ($has_evb || $check_ipaccess) {
                   5397:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5398:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5399:                 $dom = $udom;
                   5400:             }
                   5401:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5402:                 $check_ipaccess = 1;
                   5403:             } else {
                   5404:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5405:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5406:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5407:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5408:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5409:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5410:                         $check_ipaccess = 1;
                   5411:                     }
                   5412:                 }
                   5413:             }
                   5414:         }
                   5415:         if ($check_ipaccess) {
                   5416:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5417:             unless (defined($cached)) {
                   5418:                 my %domconfig =
                   5419:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5420:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5421:             }
                   5422:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5423:                 foreach my $id (keys(%{$ipaccessref})) {
                   5424:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5425:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5426:                         if ($range) {
                   5427:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5428:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5429:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5430:                                         return ('','','',$id,$dom);
                   5431:                                         last;
                   5432:                                     }
                   5433:                                 }
                   5434:                             }
                   5435:                         }
                   5436:                     }
                   5437:                 }
                   5438:             }
                   5439:         }
1.1373    raeburn  5440:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5441:             return ();
                   5442:         }
1.1372    raeburn  5443:     }
1.1189    raeburn  5444:     if (defined($udom) && defined($uname)) {
                   5445:         # If uname and udom are for a course, check for blocks in the course.
                   5446:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5447:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5448:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5449:             return ($startblock,$endblock,$triggerblock);
                   5450:         }
                   5451:     } else {
1.490     raeburn  5452:         $udom = $env{'user.domain'};
                   5453:         $uname = $env{'user.name'};
                   5454:     }
                   5455: 
1.502     raeburn  5456:     my $startblock = 0;
                   5457:     my $endblock = 0;
1.1062    raeburn  5458:     my $triggerblock = '';
1.1373    raeburn  5459:     my %live_courses;
                   5460:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5461:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5462:     }
1.474     raeburn  5463: 
1.490     raeburn  5464:     # If uname is for a user, and activity is course-specific, i.e.,
                   5465:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5466: 
1.490     raeburn  5467:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5468:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5469:          $activity eq 'search' || $activity eq 'reinit' ||
                   5470:          $activity eq 'alert') &&
1.1189    raeburn  5471:         ($env{'request.course.id'})) {
1.490     raeburn  5472:         foreach my $key (keys(%live_courses)) {
                   5473:             if ($key ne $env{'request.course.id'}) {
                   5474:                 delete($live_courses{$key});
                   5475:             }
                   5476:         }
                   5477:     }
                   5478: 
                   5479:     my $otheruser = 0;
                   5480:     my %own_courses;
                   5481:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5482:         # Resource belongs to user other than current user.
                   5483:         $otheruser = 1;
                   5484:         # Gather courses for current user
                   5485:         %own_courses = 
                   5486:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5487:     }
                   5488: 
                   5489:     # Gather active course roles - course coordinator, instructor, 
                   5490:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5491: 
                   5492:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5493:         my ($cdom,$cnum);
                   5494:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5495:             $cdom = $env{'course.'.$course.'.domain'};
                   5496:             $cnum = $env{'course.'.$course.'.num'};
                   5497:         } else {
1.490     raeburn  5498:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5499:         }
                   5500:         my $no_ownblock = 0;
                   5501:         my $no_userblock = 0;
1.533     raeburn  5502:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5503:             # Check if current user has 'evb' priv for this
                   5504:             if (defined($own_courses{$course})) {
                   5505:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5506:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5507:                     if ($sec ne 'none') {
                   5508:                         $checkrole .= '/'.$sec;
                   5509:                     }
                   5510:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5511:                         $no_ownblock = 1;
                   5512:                         last;
                   5513:                     }
                   5514:                 }
                   5515:             }
                   5516:             # if they have 'evb' priv and are currently not playing student
                   5517:             next if (($no_ownblock) &&
                   5518:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5519:         }
1.474     raeburn  5520:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5521:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5522:             if ($sec ne 'none') {
1.482     raeburn  5523:                 $checkrole .= '/'.$sec;
1.474     raeburn  5524:             }
1.490     raeburn  5525:             if ($otheruser) {
                   5526:                 # Resource belongs to user other than current user.
                   5527:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5528:                 my (%allroles,%userroles);
                   5529:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5530:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5531:                         my ($trole,$tdom,$tnum,$tsec);
                   5532:                         if ($entry =~ /^cr/) {
                   5533:                             ($trole,$tdom,$tnum,$tsec) = 
                   5534:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5535:                         } else {
                   5536:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5537:                         }
                   5538:                         my ($spec,$area,$trest);
                   5539:                         $area = '/'.$tdom.'/'.$tnum;
                   5540:                         $trest = $tnum;
                   5541:                         if ($tsec ne '') {
                   5542:                             $area .= '/'.$tsec;
                   5543:                             $trest .= '/'.$tsec;
                   5544:                         }
                   5545:                         $spec = $trole.'.'.$area;
                   5546:                         if ($trole =~ /^cr/) {
                   5547:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5548:                                                               $tdom,$spec,$trest,$area);
                   5549:                         } else {
                   5550:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5551:                                                                 $tdom,$spec,$trest,$area);
                   5552:                         }
                   5553:                     }
1.1276    raeburn  5554:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5555:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5556:                         if ($1) {
                   5557:                             $no_userblock = 1;
                   5558:                             last;
                   5559:                         }
1.486     raeburn  5560:                     }
                   5561:                 }
1.490     raeburn  5562:             } else {
                   5563:                 # Resource belongs to current user
                   5564:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5565:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5566:                     $no_ownblock = 1;
                   5567:                     last;
                   5568:                 }
1.474     raeburn  5569:             }
                   5570:         }
                   5571:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5572:         next if (($no_ownblock) &&
1.491     albertel 5573:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5574:         next if ($no_userblock);
1.474     raeburn  5575: 
1.1303    raeburn  5576:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5577:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5578: 
1.1062    raeburn  5579:         my ($start,$end,$trigger) = 
1.1347    raeburn  5580:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5581:         if (($start != 0) && 
                   5582:             (($startblock == 0) || ($startblock > $start))) {
                   5583:             $startblock = $start;
1.1062    raeburn  5584:             if ($trigger ne '') {
                   5585:                 $triggerblock = $trigger;
                   5586:             }
1.502     raeburn  5587:         }
                   5588:         if (($end != 0)  &&
                   5589:             (($endblock == 0) || ($endblock < $end))) {
                   5590:             $endblock = $end;
1.1062    raeburn  5591:             if ($trigger ne '') {
                   5592:                 $triggerblock = $trigger;
                   5593:             }
1.502     raeburn  5594:         }
1.490     raeburn  5595:     }
1.1062    raeburn  5596:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5597: }
                   5598: 
                   5599: sub get_blocks {
1.1347    raeburn  5600:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5601:     my $startblock = 0;
                   5602:     my $endblock = 0;
1.1062    raeburn  5603:     my $triggerblock = '';
1.490     raeburn  5604:     my $course = $cdom.'_'.$cnum;
                   5605:     $setters->{$course} = {};
                   5606:     $setters->{$course}{'staff'} = [];
                   5607:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5608:     $setters->{$course}{'triggers'} = [];
                   5609:     my (@blockers,%triggered);
                   5610:     my $now = time;
                   5611:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5612:     if ($activity eq 'docs') {
1.1348    raeburn  5613:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5614:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5615:             $blocked = 1;
                   5616:             $nosymbcache = 1;
1.1348    raeburn  5617:             $noenccheck = 1;
1.1347    raeburn  5618:         }
1.1348    raeburn  5619:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5620:         foreach my $block (@blockers) {
                   5621:             if ($block =~ /^firstaccess____(.+)$/) {
                   5622:                 my $item = $1;
                   5623:                 my $type = 'map';
                   5624:                 my $timersymb = $item;
                   5625:                 if ($item eq 'course') {
                   5626:                     $type = 'course';
                   5627:                 } elsif ($item =~ /___\d+___/) {
                   5628:                     $type = 'resource';
                   5629:                 } else {
                   5630:                     $timersymb = &Apache::lonnet::symbread($item);
                   5631:                 }
                   5632:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5633:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5634:                 $triggered{$block} = {
                   5635:                                        start => $start,
                   5636:                                        end   => $end,
                   5637:                                        type  => $type,
                   5638:                                      };
                   5639:             }
                   5640:         }
                   5641:     } else {
                   5642:         foreach my $block (keys(%commblocks)) {
                   5643:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5644:                 my ($start,$end) = ($1,$2);
                   5645:                 if ($start <= time && $end >= time) {
                   5646:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5647:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5648:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5649:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5650:                                     push(@blockers,$block);
                   5651:                                 }
                   5652:                             }
                   5653:                         }
                   5654:                     }
                   5655:                 }
                   5656:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5657:                 my $item = $1;
                   5658:                 my $timersymb = $item; 
                   5659:                 my $type = 'map';
                   5660:                 if ($item eq 'course') {
                   5661:                     $type = 'course';
                   5662:                 } elsif ($item =~ /___\d+___/) {
                   5663:                     $type = 'resource';
                   5664:                 } else {
                   5665:                     $timersymb = &Apache::lonnet::symbread($item);
                   5666:                 }
                   5667:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5668:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5669:                 if ($start && $end) {
                   5670:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5671:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5672:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5673:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5674:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5675:                                         push(@blockers,$block);
                   5676:                                         $triggered{$block} = {
                   5677:                                                                start => $start,
                   5678:                                                                end   => $end,
                   5679:                                                                type  => $type,
                   5680:                                                              };
                   5681:                                     }
                   5682:                                 }
                   5683:                             }
1.1062    raeburn  5684:                         }
                   5685:                     }
1.490     raeburn  5686:                 }
1.1062    raeburn  5687:             }
                   5688:         }
                   5689:     }
                   5690:     foreach my $blocker (@blockers) {
                   5691:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5692:             &parse_block_record($commblocks{$blocker});
                   5693:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5694:         my ($start,$end,$triggertype);
                   5695:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5696:             ($start,$end) = ($1,$2);
                   5697:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5698:             $start = $triggered{$blocker}{'start'};
                   5699:             $end = $triggered{$blocker}{'end'};
                   5700:             $triggertype = $triggered{$blocker}{'type'};
                   5701:         }
                   5702:         if ($start) {
                   5703:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5704:             if ($triggertype) {
                   5705:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5706:             } else {
                   5707:                 push(@{$$setters{$course}{'triggers'}},0);
                   5708:             }
                   5709:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5710:                 $startblock = $start;
                   5711:                 if ($triggertype) {
                   5712:                     $triggerblock = $blocker;
1.474     raeburn  5713:                 }
                   5714:             }
1.1062    raeburn  5715:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5716:                $endblock = $end;
                   5717:                if ($triggertype) {
                   5718:                    $triggerblock = $blocker;
                   5719:                }
                   5720:             }
1.474     raeburn  5721:         }
                   5722:     }
1.1062    raeburn  5723:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5724: }
                   5725: 
                   5726: sub parse_block_record {
                   5727:     my ($record) = @_;
                   5728:     my ($setuname,$setudom,$title,$blocks);
                   5729:     if (ref($record) eq 'HASH') {
                   5730:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5731:         $title = &unescape($record->{'event'});
                   5732:         $blocks = $record->{'blocks'};
                   5733:     } else {
                   5734:         my @data = split(/:/,$record,3);
                   5735:         if (scalar(@data) eq 2) {
                   5736:             $title = $data[1];
                   5737:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5738:         } else {
                   5739:             ($setuname,$setudom,$title) = @data;
                   5740:         }
                   5741:         $blocks = { 'com' => 'on' };
                   5742:     }
                   5743:     return ($setuname,$setudom,$title,$blocks);
                   5744: }
                   5745: 
1.854     kalberla 5746: sub blocking_status {
1.1372    raeburn  5747:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5748:     my %setters;
1.890     droeschl 5749: 
1.1061    raeburn  5750: # check for active blocking
1.1372    raeburn  5751:     if ($clientip eq '') {
                   5752:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5753:     }
                   5754:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5755:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5756:     my $blocked = 0;
1.1372    raeburn  5757:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5758:         $blocked = 1;
                   5759:     }
1.890     droeschl 5760: 
1.1061    raeburn  5761: # caller just wants to know whether a block is active
                   5762:     if (!wantarray) { return $blocked; }
                   5763: 
                   5764: # build a link to a popup window containing the details
                   5765:     my $querystring  = "?activity=$activity";
1.1351    raeburn  5766: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5767:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  5768:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   5769:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5770:     } elsif ($activity eq 'docs') {
1.1347    raeburn  5771:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5772:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5773:         if ($symb) {
                   5774:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5775:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5776:         }
1.1062    raeburn  5777:     }
1.1061    raeburn  5778: 
                   5779:     my $output .= <<'END_MYBLOCK';
                   5780: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5781:     var options = "width=" + w + ",height=" + h + ",";
                   5782:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5783:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5784:     var newWin = window.open(url, wdwName, options);
                   5785:     newWin.focus();
                   5786: }
1.890     droeschl 5787: END_MYBLOCK
1.854     kalberla 5788: 
1.1061    raeburn  5789:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5790:   
1.1061    raeburn  5791:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5792:     my $text = &mt('Communication Blocked');
1.1217    raeburn  5793:     my $class = 'LC_comblock';
1.1062    raeburn  5794:     if ($activity eq 'docs') {
                   5795:         $text = &mt('Content Access Blocked');
1.1217    raeburn  5796:         $class = '';
1.1063    raeburn  5797:     } elsif ($activity eq 'printout') {
                   5798:         $text = &mt('Printing Blocked');
1.1232    raeburn  5799:     } elsif ($activity eq 'passwd') {
                   5800:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  5801:     } elsif ($activity eq 'grades') {
                   5802:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  5803:     } elsif ($activity eq 'search') {
                   5804:         $text = &mt('Search Blocked');
1.1282    raeburn  5805:     } elsif ($activity eq 'alert') {
                   5806:         $text = &mt('Checking Critical Messages Blocked');
                   5807:     } elsif ($activity eq 'reinit') {
                   5808:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  5809:     } elsif ($activity eq 'about') {
                   5810:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  5811:     } elsif ($activity eq 'wishlist') {
                   5812:         $text = &mt('Access to Stored Links Blocked');
                   5813:     } elsif ($activity eq 'annotate') {
                   5814:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5815:     }
1.1061    raeburn  5816:     $output .= <<"END_BLOCK";
1.1217    raeburn  5817: <div class='$class'>
1.869     kalberla 5818:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5819:   title='$text'>
                   5820:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5821:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5822:   title='$text'>$text</a>
1.867     kalberla 5823: </div>
                   5824: 
                   5825: END_BLOCK
1.474     raeburn  5826: 
1.1061    raeburn  5827:     return ($blocked, $output);
1.854     kalberla 5828: }
1.490     raeburn  5829: 
1.60      matthew  5830: ###############################################
                   5831: 
1.682     raeburn  5832: sub check_ip_acc {
1.1201    raeburn  5833:     my ($acc,$clientip)=@_;
1.682     raeburn  5834:     &Apache::lonxml::debug("acc is $acc");
                   5835:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5836:         return 1;
                   5837:     }
1.1339    raeburn  5838:     my ($ip,$allowed);
                   5839:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5840:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5841:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5842:     } else {
1.1350    raeburn  5843:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5844:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  5845:     }
1.682     raeburn  5846: 
                   5847:     my $name;
1.1219    raeburn  5848:     my %access = (
                   5849:                      allowfrom => 1,
                   5850:                      denyfrom  => 0,
                   5851:                  );
                   5852:     my @allows;
                   5853:     my @denies;
                   5854:     foreach my $item (split(',',$acc)) {
                   5855:         $item =~ s/^\s*//;
                   5856:         $item =~ s/\s*$//;
                   5857:         my $pattern;
                   5858:         if ($item =~ /^\!(.+)$/) {
                   5859:             push(@denies,$1);
                   5860:         } else {
                   5861:             push(@allows,$item);
                   5862:         }
                   5863:    }
                   5864:    my $numdenies = scalar(@denies);
                   5865:    my $numallows = scalar(@allows);
                   5866:    my $count = 0;
                   5867:    foreach my $pattern (@denies,@allows) {
                   5868:         $count ++; 
                   5869:         my $acctype = 'allowfrom';
                   5870:         if ($count <= $numdenies) {
                   5871:             $acctype = 'denyfrom';
                   5872:         }
1.682     raeburn  5873:         if ($pattern =~ /\*$/) {
                   5874:             #35.8.*
                   5875:             $pattern=~s/\*//;
1.1219    raeburn  5876:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5877:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5878:             #35.8.3.[34-56]
                   5879:             my $low=$2;
                   5880:             my $high=$3;
                   5881:             $pattern=$1;
                   5882:             if ($ip =~ /^\Q$pattern\E/) {
                   5883:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  5884:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5885:             }
                   5886:         } elsif ($pattern =~ /^\*/) {
                   5887:             #*.msu.edu
                   5888:             $pattern=~s/\*//;
                   5889:             if (!defined($name)) {
                   5890:                 use Socket;
                   5891:                 my $netaddr=inet_aton($ip);
                   5892:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5893:             }
1.1219    raeburn  5894:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5895:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5896:             #127.0.0.1
1.1219    raeburn  5897:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5898:         } else {
                   5899:             #some.name.com
                   5900:             if (!defined($name)) {
                   5901:                 use Socket;
                   5902:                 my $netaddr=inet_aton($ip);
                   5903:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5904:             }
1.1219    raeburn  5905:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5906:         }
                   5907:         if ($allowed =~ /^(0|1)$/) { last; }
                   5908:     }
                   5909:     if ($allowed eq '') {
                   5910:         if ($numdenies && !$numallows) {
                   5911:             $allowed = 1;
                   5912:         } else {
                   5913:             $allowed = 0;
1.682     raeburn  5914:         }
                   5915:     }
                   5916:     return $allowed;
                   5917: }
                   5918: 
                   5919: ###############################################
                   5920: 
1.60      matthew  5921: =pod
                   5922: 
1.112     bowersj2 5923: =head1 Domain Template Functions
                   5924: 
                   5925: =over 4
                   5926: 
                   5927: =item * &determinedomain()
1.60      matthew  5928: 
                   5929: Inputs: $domain (usually will be undef)
                   5930: 
1.63      www      5931: Returns: Determines which domain should be used for designs
1.60      matthew  5932: 
                   5933: =cut
1.54      www      5934: 
1.60      matthew  5935: ###############################################
1.63      www      5936: sub determinedomain {
                   5937:     my $domain=shift;
1.531     albertel 5938:     if (! $domain) {
1.60      matthew  5939:         # Determine domain if we have not been given one
1.893     raeburn  5940:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5941:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5942:         if ($env{'request.role.domain'}) { 
                   5943:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5944:         }
                   5945:     }
1.63      www      5946:     return $domain;
                   5947: }
                   5948: ###############################################
1.517     raeburn  5949: 
1.518     albertel 5950: sub devalidate_domconfig_cache {
                   5951:     my ($udom)=@_;
                   5952:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5953: }
                   5954: 
                   5955: # ---------------------- Get domain configuration for a domain
                   5956: sub get_domainconf {
                   5957:     my ($udom) = @_;
                   5958:     my $cachetime=1800;
                   5959:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5960:     if (defined($cached)) { return %{$result}; }
                   5961: 
                   5962:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5963: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5964:     my (%designhash,%legacy);
1.518     albertel 5965:     if (keys(%domconfig) > 0) {
                   5966:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5967:             if (keys(%{$domconfig{'login'}})) {
                   5968:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5969:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5970:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5971:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5972:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5973:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5974:                                         if ($key eq 'loginvia') {
                   5975:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5976:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5977:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5978:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5979: 
                   5980:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5981:                                                 } else {
                   5982:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5983:                                                 }
1.948     raeburn  5984:                                             }
1.1208    raeburn  5985:                                         } elsif ($key eq 'headtag') {
                   5986:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5987:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5988:                                             }
1.946     raeburn  5989:                                         }
1.1208    raeburn  5990:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5991:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5992:                                         }
1.946     raeburn  5993:                                     }
                   5994:                                 }
                   5995:                             }
1.1366    raeburn  5996:                         } elsif ($key eq 'saml') {
                   5997:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5998:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5999:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6000:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6001:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6002:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6003:                                         }
                   6004:                                     }
                   6005:                                 }
                   6006:                             }
1.946     raeburn  6007:                         } else {
                   6008:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6009:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6010:                                     $domconfig{'login'}{$key}{$img};
                   6011:                             }
1.699     raeburn  6012:                         }
                   6013:                     } else {
                   6014:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6015:                     }
1.632     raeburn  6016:                 }
                   6017:             } else {
                   6018:                 $legacy{'login'} = 1;
1.518     albertel 6019:             }
1.632     raeburn  6020:         } else {
                   6021:             $legacy{'login'} = 1;
1.518     albertel 6022:         }
                   6023:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6024:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6025:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6026:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6027:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6028:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6029:                         }
1.518     albertel 6030:                     }
                   6031:                 }
1.632     raeburn  6032:             } else {
                   6033:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6034:             }
1.632     raeburn  6035:         } else {
                   6036:             $legacy{'rolecolors'} = 1;
1.518     albertel 6037:         }
1.948     raeburn  6038:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6039:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6040:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6041:             }
                   6042:         }
1.632     raeburn  6043:         if (keys(%legacy) > 0) {
                   6044:             my %legacyhash = &get_legacy_domconf($udom);
                   6045:             foreach my $item (keys(%legacyhash)) {
                   6046:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6047:                     if ($legacy{'login'}) { 
                   6048:                         $designhash{$item} = $legacyhash{$item};
                   6049:                     }
                   6050:                 } else {
                   6051:                     if ($legacy{'rolecolors'}) {
                   6052:                         $designhash{$item} = $legacyhash{$item};
                   6053:                     }
1.518     albertel 6054:                 }
                   6055:             }
                   6056:         }
1.632     raeburn  6057:     } else {
                   6058:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6059:     }
                   6060:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6061: 				  $cachetime);
                   6062:     return %designhash;
                   6063: }
                   6064: 
1.632     raeburn  6065: sub get_legacy_domconf {
                   6066:     my ($udom) = @_;
                   6067:     my %legacyhash;
                   6068:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6069:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6070:     if (-e $designfile) {
1.1317    raeburn  6071:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6072:             while (my $line = <$fh>) {
                   6073:                 next if ($line =~ /^\#/);
                   6074:                 chomp($line);
                   6075:                 my ($key,$val)=(split(/\=/,$line));
                   6076:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6077:             }
                   6078:             close($fh);
                   6079:         }
                   6080:     }
1.1026    raeburn  6081:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6082:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6083:     }
                   6084:     return %legacyhash;
                   6085: }
                   6086: 
1.63      www      6087: =pod
                   6088: 
1.112     bowersj2 6089: =item * &domainlogo()
1.63      www      6090: 
                   6091: Inputs: $domain (usually will be undef)
                   6092: 
                   6093: Returns: A link to a domain logo, if the domain logo exists.
                   6094: If the domain logo does not exist, a description of the domain.
                   6095: 
                   6096: =cut
1.112     bowersj2 6097: 
1.63      www      6098: ###############################################
                   6099: sub domainlogo {
1.517     raeburn  6100:     my $domain = &determinedomain(shift);
1.518     albertel 6101:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6102:     # See if there is a logo
                   6103:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6104:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6105:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6106: 	    if ($imgsrc =~ m{^/res/}) {
                   6107: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6108: 		&Apache::lonnet::repcopy($local_name);
                   6109: 	    }
                   6110: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6111:         }
                   6112:         my $alttext = $domain;
                   6113:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6114:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6115:         }
                   6116:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6117:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6118:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6119:     } else {
1.60      matthew  6120:         return '';
1.59      www      6121:     }
                   6122: }
1.63      www      6123: ##############################################
                   6124: 
                   6125: =pod
                   6126: 
1.112     bowersj2 6127: =item * &designparm()
1.63      www      6128: 
                   6129: Inputs: $which parameter; $domain (usually will be undef)
                   6130: 
                   6131: Returns: value of designparamter $which
                   6132: 
                   6133: =cut
1.112     bowersj2 6134: 
1.397     albertel 6135: 
1.400     albertel 6136: ##############################################
1.397     albertel 6137: sub designparm {
                   6138:     my ($which,$domain)=@_;
                   6139:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6140:         return $env{'environment.color.'.$which};
1.96      www      6141:     }
1.63      www      6142:     $domain=&determinedomain($domain);
1.1016    raeburn  6143:     my %domdesign;
                   6144:     unless ($domain eq 'public') {
                   6145:         %domdesign = &get_domainconf($domain);
                   6146:     }
1.520     raeburn  6147:     my $output;
1.517     raeburn  6148:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6149:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6150:     } else {
1.520     raeburn  6151:         $output = $defaultdesign{$which};
                   6152:     }
                   6153:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6154:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6155:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6156:             if ($output =~ m{^/res/}) {
                   6157:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6158:                 &Apache::lonnet::repcopy($local_name);
                   6159:             }
1.520     raeburn  6160:             $output = &lonhttpdurl($output);
                   6161:         }
1.63      www      6162:     }
1.520     raeburn  6163:     return $output;
1.63      www      6164: }
1.59      www      6165: 
1.822     bisitz   6166: ##############################################
                   6167: =pod
                   6168: 
1.832     bisitz   6169: =item * &authorspace()
                   6170: 
1.1028    raeburn  6171: Inputs: $url (usually will be undef).
1.832     bisitz   6172: 
1.1132    raeburn  6173: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6174:          directory being viewed (or for which action is being taken). 
                   6175:          If $url is provided, and begins /priv/<domain>/<uname>
                   6176:          the path will be that portion of the $context argument.
                   6177:          Otherwise the path will be for the author space of the current
                   6178:          user when the current role is author, or for that of the 
                   6179:          co-author/assistant co-author space when the current role 
                   6180:          is co-author or assistant co-author.
1.832     bisitz   6181: 
                   6182: =cut
                   6183: 
                   6184: sub authorspace {
1.1028    raeburn  6185:     my ($url) = @_;
                   6186:     if ($url ne '') {
                   6187:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6188:            return $1;
                   6189:         }
                   6190:     }
1.832     bisitz   6191:     my $caname = '';
1.1024    www      6192:     my $cadom = '';
1.1028    raeburn  6193:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6194:         ($cadom,$caname) =
1.832     bisitz   6195:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6196:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6197:         $caname = $env{'user.name'};
1.1024    www      6198:         $cadom = $env{'user.domain'};
1.832     bisitz   6199:     }
1.1028    raeburn  6200:     if (($caname ne '') && ($cadom ne '')) {
                   6201:         return "/priv/$cadom/$caname/";
                   6202:     }
                   6203:     return;
1.832     bisitz   6204: }
                   6205: 
                   6206: ##############################################
                   6207: =pod
                   6208: 
1.822     bisitz   6209: =item * &head_subbox()
                   6210: 
                   6211: Inputs: $content (contains HTML code with page functions, etc.)
                   6212: 
                   6213: Returns: HTML div with $content
                   6214:          To be included in page header
                   6215: 
                   6216: =cut
                   6217: 
                   6218: sub head_subbox {
                   6219:     my ($content)=@_;
                   6220:     my $output =
1.993     raeburn  6221:         '<div class="LC_head_subbox">'
1.822     bisitz   6222:        .$content
                   6223:        .'</div>'
                   6224: }
                   6225: 
                   6226: ##############################################
                   6227: =pod
                   6228: 
                   6229: =item * &CSTR_pageheader()
                   6230: 
1.1026    raeburn  6231: Input: (optional) filename from which breadcrumb trail is built.
                   6232:        In most cases no input as needed, as $env{'request.filename'}
                   6233:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6234:        frameset flag
                   6235:        If page header is being requested for use in a frameset, then
                   6236:        the second (option) argument -- frameset will be true, and
                   6237:        the target attribute set for links should be target="_parent".
1.822     bisitz   6238: 
                   6239: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6240:          To be included on Authoring Space pages
1.822     bisitz   6241: 
                   6242: =cut
                   6243: 
                   6244: sub CSTR_pageheader {
1.1379    raeburn  6245:     my ($trailfile,$frameset) = @_;
1.1026    raeburn  6246:     if ($trailfile eq '') {
                   6247:         $trailfile = $env{'request.filename'};
                   6248:     }
                   6249: 
                   6250: # this is for resources; directories have customtitle, and crumbs
                   6251: # and select recent are created in lonpubdir.pm
                   6252: 
                   6253:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6254:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6255:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6256:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6257:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6258: 
                   6259:     my $parentpath = '';
                   6260:     my $lastitem = '';
                   6261:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6262:         $parentpath = $1;
                   6263:         $lastitem = $2;
                   6264:     } else {
                   6265:         $lastitem = $thisdisfn;
                   6266:     }
1.921     bisitz   6267: 
1.1246    raeburn  6268:     my ($crsauthor,$title);
                   6269:     if (($env{'request.course.id'}) &&
                   6270:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6271:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6272:         $crsauthor = 1;
                   6273:         $title = &mt('Course Authoring Space');
                   6274:     } else {
                   6275:         $title = &mt('Authoring Space');
                   6276:     }
                   6277: 
1.1379    raeburn  6278:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6279:     if ($frameset) {
                   6280:         $target = ' target="_parent"';
                   6281:         $crumbtarget = '_parent';
                   6282:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6283:         $target = '';
                   6284:         $crumbtarget = '';
1.1379    raeburn  6285:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6286:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6287:         $crumbtarget = $env{'request.deeplink.target'};
                   6288:     }
1.1313    raeburn  6289: 
1.921     bisitz   6290:     my $output =
1.822     bisitz   6291:          '<div>'
                   6292:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6293:         .'<b>'.$title.'</b> '
1.1314    raeburn  6294:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6295:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6296: 
                   6297:     if ($lastitem) {
                   6298:         $output .=
                   6299:              '<span class="LC_filename">'
                   6300:             .$lastitem
                   6301:             .'</span>';
                   6302:     }
1.1245    raeburn  6303: 
1.1246    raeburn  6304:     if ($crsauthor) {
1.1379    raeburn  6305:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6306:     } else {
                   6307:         $output .=
                   6308:              '<br />'
1.1314    raeburn  6309:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6310:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6311:             .'</form>'
1.1379    raeburn  6312:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6313:     }
                   6314:     $output .= '</div>';
1.921     bisitz   6315: 
                   6316:     return $output;
1.822     bisitz   6317: }
                   6318: 
1.60      matthew  6319: ###############################################
                   6320: ###############################################
                   6321: 
                   6322: =pod
                   6323: 
1.112     bowersj2 6324: =back
                   6325: 
1.549     albertel 6326: =head1 HTML Helpers
1.112     bowersj2 6327: 
                   6328: =over 4
                   6329: 
                   6330: =item * &bodytag()
1.60      matthew  6331: 
                   6332: Returns a uniform header for LON-CAPA web pages.
                   6333: 
                   6334: Inputs: 
                   6335: 
1.112     bowersj2 6336: =over 4
                   6337: 
                   6338: =item * $title, A title to be displayed on the page.
                   6339: 
                   6340: =item * $function, the current role (can be undef).
                   6341: 
                   6342: =item * $addentries, extra parameters for the <body> tag.
                   6343: 
                   6344: =item * $bodyonly, if defined, only return the <body> tag.
                   6345: 
                   6346: =item * $domain, if defined, force a given domain.
                   6347: 
                   6348: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6349:             text interface only)
1.60      matthew  6350: 
1.814     bisitz   6351: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6352:                      navigational links
1.317     albertel 6353: 
1.338     albertel 6354: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6355: 
1.460     albertel 6356: =item * $args, optional argument valid values are
                   6357:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6358:             use_absolute     -> for external resource or syllabus, this will
                   6359:                                 contain https://<hostname> if server uses
                   6360:                                 https (as per hosts.tab), but request is for http
                   6361:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6362: 
1.1096    raeburn  6363: =item * $advtoolsref, optional argument, ref to an array containing
                   6364:             inlineremote items to be added in "Functions" menu below
                   6365:             breadcrumbs.
                   6366: 
1.1316    raeburn  6367: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6368:             course, if LON-CAPA is in LTI Provider context. Value is
                   6369:             the scope of use, i.e., launch was for access to a single, a map
                   6370:             or the entire course.
                   6371: 
                   6372: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6373:             context, this will contain the URL for the landing item in
                   6374:             the course, after launch from an LTI Consumer
                   6375: 
1.1318    raeburn  6376: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6377:             context, this will contain a reference to hash of items
                   6378:             to be included in the page header and/or inline menu.
                   6379: 
1.1385    raeburn  6380: =item * $menucoll, optional argument, if specific menu collection is in
                   6381:             effect, either set as the default for the course, or set for
                   6382:             the deeplink paramater for $env{'request.deeplink.login'}
                   6383:             then $menucoll will be the number of that collection. 
                   6384: 
                   6385: =item * $menuref, optional argument, reference to a hash, containing the
                   6386:             menu options included for the menu in effect, based on the
                   6387:             configuration for the numbered menu collection in use.  
                   6388: 
                   6389: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6390:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6391:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6392:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6393:             being called a second time.
                   6394: 
1.112     bowersj2 6395: =back
                   6396: 
1.60      matthew  6397: Returns: A uniform header for LON-CAPA web pages.  
                   6398: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6399: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6400: other decorations will be returned.
                   6401: 
                   6402: =cut
                   6403: 
1.54      www      6404: sub bodytag {
1.831     bisitz   6405:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6406:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6407:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6408: 
1.954     raeburn  6409:     my $public;
                   6410:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6411:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6412:         $public = 1;
                   6413:     }
1.460     albertel 6414:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6415:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6416:     my $hostname = $args->{'hostname'};
1.339     albertel 6417: 
1.183     matthew  6418:     $function = &get_users_function() if (!$function);
1.339     albertel 6419:     my $img =    &designparm($function.'.img',$domain);
                   6420:     my $font =   &designparm($function.'.font',$domain);
                   6421:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6422: 
1.803     bisitz   6423:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6424: 		   'bgcolor' => $pgbg,
1.339     albertel 6425: 		   'text'    => $font,
                   6426:                    'alink'   => &designparm($function.'.alink',$domain),
                   6427: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6428: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6429:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6430: 
1.63      www      6431:  # role and realm
1.1178    raeburn  6432:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6433:     if ($realm) {
                   6434:         $realm = '/'.$realm;
                   6435:     }
1.1357    raeburn  6436:     if ($role eq 'ca') {
1.479     albertel 6437:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6438:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6439:     } 
1.55      www      6440: # realm
1.1357    raeburn  6441:     my ($cid,$sec);
1.258     albertel 6442:     if ($env{'request.course.id'}) {
1.1357    raeburn  6443:         $cid = $env{'request.course.id'};
                   6444:         if ($env{'request.course.sec'}) {
                   6445:             $sec = $env{'request.course.sec'};
                   6446:         }
                   6447:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6448:         if (&Apache::lonnet::is_course($1,$2)) {
                   6449:             $cid = $1.'_'.$2;
                   6450:             $sec = $3;
                   6451:         }
                   6452:     }
                   6453:     if ($cid) {
1.378     raeburn  6454:         if ($env{'request.role'} !~ /^cr/) {
                   6455:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6456:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6457:             if ($env{'request.role.desc'}) {
                   6458:                 $role = $env{'request.role.desc'};
                   6459:             } else {
                   6460:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6461:             }
1.1257    raeburn  6462:         } else {
                   6463:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6464:         }
1.1357    raeburn  6465:         if ($sec) {
                   6466:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6467:         }   
1.1357    raeburn  6468: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6469:     } else {
                   6470:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6471:     }
1.433     albertel 6472: 
1.359     albertel 6473:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6474: 
1.438     albertel 6475:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6476: 
1.101     www      6477: # construct main body tag
1.359     albertel 6478:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6479: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6480: 
1.1131    raeburn  6481:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6482: 
1.1130    raeburn  6483:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6484:         return $bodytag;
1.1130    raeburn  6485:     }
1.359     albertel 6486: 
1.954     raeburn  6487:     if ($public) {
1.433     albertel 6488: 	undef($role);
                   6489:     }
1.1318    raeburn  6490: 
1.1359    raeburn  6491:     my $showcrstitle = 1;
1.1357    raeburn  6492:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6493:         if (ref($ltimenu) eq 'HASH') {
                   6494:             unless ($ltimenu->{'role'}) {
                   6495:                 undef($role);
                   6496:             }
                   6497:             unless ($ltimenu->{'coursetitle'}) {
                   6498:                 $realm='&nbsp;';
1.1359    raeburn  6499:                 $showcrstitle = 0;
                   6500:             }
                   6501:         }
                   6502:     } elsif (($cid) && ($menucoll)) {
                   6503:         if (ref($menuref) eq 'HASH') {
                   6504:             unless ($menuref->{'role'}) {
                   6505:                 undef($role);
                   6506:             }
                   6507:             unless ($menuref->{'crs'}) {
                   6508:                 $realm='&nbsp;';
                   6509:                 $showcrstitle = 0;
1.1318    raeburn  6510:             }
                   6511:         }
                   6512:     }
                   6513: 
1.762     bisitz   6514:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6515:     #
                   6516:     # Extra info if you are the DC
                   6517:     my $dc_info = '';
1.1359    raeburn  6518:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6519:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6520:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6521:         $dc_info =~ s/\s+$//;
1.359     albertel 6522:     }
                   6523: 
1.1237    raeburn  6524:     my $crstype;
1.1357    raeburn  6525:     if ($cid) {
                   6526:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6527:     } elsif ($args->{'crstype'}) {
                   6528:         $crstype = $args->{'crstype'};
                   6529:     }
                   6530:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6531:         undef($role);
                   6532:     } else {
1.1242    raeburn  6533:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6534:     }
1.853     droeschl 6535: 
1.903     droeschl 6536:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6537: 
                   6538:         #    if ($env{'request.state'} eq 'construct') {
                   6539:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6540:         #    }
                   6541: 
1.1130    raeburn  6542:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6543:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6544: 
1.1318    raeburn  6545:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6546:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6547:                                                               $args->{'links_disabled'},
                   6548:                                                               $args->{'links_target'});
1.359     albertel 6549: 
1.1318    raeburn  6550:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6551:                 if ($dc_info) {
                   6552:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6553:                 }
                   6554:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6555:                                <em>$realm</em> $dc_info</div>|;
                   6556:                 return $bodytag;
                   6557:             }
1.894     droeschl 6558: 
1.1318    raeburn  6559:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6560:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6561:             }
1.916     droeschl 6562: 
1.1318    raeburn  6563:             $bodytag .= $right;
1.852     droeschl 6564: 
1.1318    raeburn  6565:             if ($dc_info) {
                   6566:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6567:             }
                   6568:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6569:         }
1.916     droeschl 6570: 
1.1169    raeburn  6571:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6572:         if ($args->{'no_secondary_menu'}) {
                   6573:             return $bodytag;
                   6574:         }
1.1169    raeburn  6575:         #don't show menus for public users
1.954     raeburn  6576:         if (!$public){
1.1318    raeburn  6577:             unless ($args->{'no_inline_menu'}) {
                   6578:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6579:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6580:                                                             $menucoll,$menuref,
1.1380    raeburn  6581:                                                             $args->{'links_disabled'},
                   6582:                                                             $args->{'links_target'});
1.1318    raeburn  6583:             }
1.903     droeschl 6584:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6585:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6586:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6587:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  6588:                                 $args->{'bread_crumbs'},'','',$hostname,
                   6589:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6590:             } elsif ($forcereg) {
                   6591:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  6592:                                 $args->{'group'},$args->{'hide_buttons'},
                   6593:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6594:             } else {
                   6595:                 $bodytag .= 
                   6596:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6597:                                                         $forcereg,$args->{'group'},
                   6598:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6599:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6600:             }
1.903     droeschl 6601:         }else{
                   6602:             # this is to seperate menu from content when there's no secondary
                   6603:             # menu. Especially needed for public accessible ressources.
                   6604:             $bodytag .= '<hr style="clear:both" />';
                   6605:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6606:         }
1.903     droeschl 6607: 
1.235     raeburn  6608:         return $bodytag;
1.182     matthew  6609: }
                   6610: 
1.917     raeburn  6611: sub dc_courseid_toggle {
                   6612:     my ($dc_info) = @_;
1.980     raeburn  6613:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6614:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6615:            &mt('(More ...)').'</a></span>'.
                   6616:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6617: }
                   6618: 
1.330     albertel 6619: sub make_attr_string {
                   6620:     my ($register,$attr_ref) = @_;
                   6621: 
                   6622:     if ($attr_ref && !ref($attr_ref)) {
                   6623: 	die("addentries Must be a hash ref ".
                   6624: 	    join(':',caller(1))." ".
                   6625: 	    join(':',caller(0))." ");
                   6626:     }
                   6627: 
                   6628:     if ($register) {
1.339     albertel 6629: 	my ($on_load,$on_unload);
                   6630: 	foreach my $key (keys(%{$attr_ref})) {
                   6631: 	    if      (lc($key) eq 'onload') {
                   6632: 		$on_load.=$attr_ref->{$key}.';';
                   6633: 		delete($attr_ref->{$key});
                   6634: 
                   6635: 	    } elsif (lc($key) eq 'onunload') {
                   6636: 		$on_unload.=$attr_ref->{$key}.';';
                   6637: 		delete($attr_ref->{$key});
                   6638: 	    }
                   6639: 	}
1.953     droeschl 6640: 	$attr_ref->{'onload'}  = $on_load;
                   6641: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6642:     }
1.339     albertel 6643: 
1.330     albertel 6644:     my $attr_string;
1.1159    raeburn  6645:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6646: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6647:     }
                   6648:     return $attr_string;
                   6649: }
                   6650: 
                   6651: 
1.182     matthew  6652: ###############################################
1.251     albertel 6653: ###############################################
                   6654: 
                   6655: =pod
                   6656: 
                   6657: =item * &endbodytag()
                   6658: 
                   6659: Returns a uniform footer for LON-CAPA web pages.
                   6660: 
1.635     raeburn  6661: Inputs: 1 - optional reference to an args hash
                   6662: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6663: a 'Continue' link is not displayed if the page contains an
                   6664: internal redirect in the <head></head> section,
                   6665: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6666: 
                   6667: =cut
                   6668: 
                   6669: sub endbodytag {
1.635     raeburn  6670:     my ($args) = @_;
1.1080    raeburn  6671:     my $endbodytag;
                   6672:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6673:         $endbodytag='</body>';
                   6674:     }
1.315     albertel 6675:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6676:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  6677:             my ($endbodyjs,$idattr);
                   6678:             if ($env{'internal.head.to_opener'}) {
                   6679:                 my $linkid = 'LC_continue_link';
                   6680:                 $idattr = ' id="'.$linkid.'"';
                   6681:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6682:                 $endbodyjs=<<ENDJS;
                   6683: <script type="text/javascript">
                   6684: // <![CDATA[
                   6685: function ebFunction(evt) {
                   6686:     evt.preventDefault();
                   6687:     var dest = '$redirect_for_js';
                   6688:     if (window.opener != null && !window.opener.closed) {
                   6689:         window.opener.location.href=dest;
                   6690:         window.close();
                   6691:     } else {
                   6692:         window.location.href=dest;
                   6693:     }
                   6694:     return false;
                   6695: }
                   6696: 
                   6697: \$(document).ready(function () {
                   6698:   if (document.getElementById('$linkid')) {
                   6699:     var clickelem = document.getElementById('$linkid');
                   6700:     clickelem.addEventListener('click',ebFunction,false);
                   6701:   }
                   6702: });
                   6703: // ]]>
                   6704: </script>
                   6705: ENDJS
                   6706:             }
1.635     raeburn  6707: 	    $endbodytag=
1.1386    raeburn  6708: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6709: 	        &mt('Continue').'</a>'.
                   6710: 	        $endbodytag;
                   6711:         }
1.315     albertel 6712:     }
1.251     albertel 6713:     return $endbodytag;
                   6714: }
                   6715: 
1.352     albertel 6716: =pod
                   6717: 
                   6718: =item * &standard_css()
                   6719: 
                   6720: Returns a style sheet
                   6721: 
                   6722: Inputs: (all optional)
                   6723:             domain         -> force to color decorate a page for a specific
                   6724:                                domain
                   6725:             function       -> force usage of a specific rolish color scheme
                   6726:             bgcolor        -> override the default page bgcolor
                   6727: 
                   6728: =cut
                   6729: 
1.343     albertel 6730: sub standard_css {
1.345     albertel 6731:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6732:     $function  = &get_users_function() if (!$function);
                   6733:     my $img    = &designparm($function.'.img',   $domain);
                   6734:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6735:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6736:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6737: #second colour for later usage
1.345     albertel 6738:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6739:     my $pgbg_or_bgcolor =
                   6740: 	         $bgcolor ||
1.352     albertel 6741: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6742:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6743:     my $alink  = &designparm($function.'.alink', $domain);
                   6744:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6745:     my $link   = &designparm($function.'.link',  $domain);
                   6746: 
1.602     albertel 6747:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6748:     my $mono                 = 'monospace';
1.850     bisitz   6749:     my $data_table_head      = $sidebg;
                   6750:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6751:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6752:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6753:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6754:     my $mail_new             = '#FFBB77';
                   6755:     my $mail_new_hover       = '#DD9955';
                   6756:     my $mail_read            = '#BBBB77';
                   6757:     my $mail_read_hover      = '#999944';
                   6758:     my $mail_replied         = '#AAAA88';
                   6759:     my $mail_replied_hover   = '#888855';
                   6760:     my $mail_other           = '#99BBBB';
                   6761:     my $mail_other_hover     = '#669999';
1.391     albertel 6762:     my $table_header         = '#DDDDDD';
1.489     raeburn  6763:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6764:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6765:     my $button_hover         = '#BF2317';
1.392     albertel 6766: 
1.608     albertel 6767:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6768:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6769:                                              : '0 3px 0 4px';
1.448     albertel 6770: 
1.523     albertel 6771: 
1.343     albertel 6772:     return <<END;
1.947     droeschl 6773: 
                   6774: /* needed for iframe to allow 100% height in FF */
                   6775: body, html { 
                   6776:     margin: 0;
                   6777:     padding: 0 0.5%;
                   6778:     height: 99%; /* to avoid scrollbars */
                   6779: }
                   6780: 
1.795     www      6781: body {
1.911     bisitz   6782:   font-family: $sans;
                   6783:   line-height:130%;
                   6784:   font-size:0.83em;
                   6785:   color:$font;
1.795     www      6786: }
                   6787: 
1.959     onken    6788: a:focus,
                   6789: a:focus img {
1.795     www      6790:   color: red;
                   6791: }
1.698     harmsja  6792: 
1.911     bisitz   6793: form, .inline {
                   6794:   display: inline;
1.795     www      6795: }
1.721     harmsja  6796: 
1.795     www      6797: .LC_right {
1.911     bisitz   6798:   text-align:right;
1.795     www      6799: }
                   6800: 
                   6801: .LC_middle {
1.911     bisitz   6802:   vertical-align:middle;
1.795     www      6803: }
1.721     harmsja  6804: 
1.1130    raeburn  6805: .LC_floatleft {
                   6806:   float: left;
                   6807: }
                   6808: 
                   6809: .LC_floatright {
                   6810:   float: right;
                   6811: }
                   6812: 
1.911     bisitz   6813: .LC_400Box {
                   6814:   width:400px;
                   6815: }
1.721     harmsja  6816: 
1.947     droeschl 6817: .LC_iframecontainer {
                   6818:     width: 98%;
                   6819:     margin: 0;
                   6820:     position: fixed;
                   6821:     top: 8.5em;
                   6822:     bottom: 0;
                   6823: }
                   6824: 
                   6825: .LC_iframecontainer iframe{
                   6826:     border: none;
                   6827:     width: 100%;
                   6828:     height: 100%;
                   6829: }
                   6830: 
1.778     bisitz   6831: .LC_filename {
                   6832:   font-family: $mono;
                   6833:   white-space:pre;
1.921     bisitz   6834:   font-size: 120%;
1.778     bisitz   6835: }
                   6836: 
                   6837: .LC_fileicon {
                   6838:   border: none;
                   6839:   height: 1.3em;
                   6840:   vertical-align: text-bottom;
                   6841:   margin-right: 0.3em;
                   6842:   text-decoration:none;
                   6843: }
                   6844: 
1.1008    www      6845: .LC_setting {
                   6846:   text-decoration:underline;
                   6847: }
                   6848: 
1.350     albertel 6849: .LC_error {
                   6850:   color: red;
                   6851: }
1.795     www      6852: 
1.1097    bisitz   6853: .LC_warning {
                   6854:   color: darkorange;
                   6855: }
                   6856: 
1.457     albertel 6857: .LC_diff_removed {
1.733     bisitz   6858:   color: red;
1.394     albertel 6859: }
1.532     albertel 6860: 
                   6861: .LC_info,
1.457     albertel 6862: .LC_success,
                   6863: .LC_diff_added {
1.350     albertel 6864:   color: green;
                   6865: }
1.795     www      6866: 
1.802     bisitz   6867: div.LC_confirm_box {
                   6868:   background-color: #FAFAFA;
                   6869:   border: 1px solid $lg_border_color;
                   6870:   margin-right: 0;
                   6871:   padding: 5px;
                   6872: }
                   6873: 
                   6874: div.LC_confirm_box .LC_error img,
                   6875: div.LC_confirm_box .LC_success img {
                   6876:   vertical-align: middle;
                   6877: }
                   6878: 
1.1242    raeburn  6879: .LC_maxwidth {
                   6880:   max-width: 100%;
                   6881:   height: auto;
                   6882: }
                   6883: 
1.1243    raeburn  6884: .LC_textsize_mobile {
                   6885:   \@media only screen and (max-device-width: 480px) {
                   6886:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6887:   }
                   6888: }
                   6889: 
1.440     albertel 6890: .LC_icon {
1.771     droeschl 6891:   border: none;
1.790     droeschl 6892:   vertical-align: middle;
1.771     droeschl 6893: }
                   6894: 
1.543     albertel 6895: .LC_docs_spacer {
                   6896:   width: 25px;
                   6897:   height: 1px;
1.771     droeschl 6898:   border: none;
1.543     albertel 6899: }
1.346     albertel 6900: 
1.532     albertel 6901: .LC_internal_info {
1.735     bisitz   6902:   color: #999999;
1.532     albertel 6903: }
                   6904: 
1.794     www      6905: .LC_discussion {
1.1050    www      6906:   background: $data_table_dark;
1.911     bisitz   6907:   border: 1px solid black;
                   6908:   margin: 2px;
1.794     www      6909: }
                   6910: 
                   6911: .LC_disc_action_left {
1.1050    www      6912:   background: $sidebg;
1.911     bisitz   6913:   text-align: left;
1.1050    www      6914:   padding: 4px;
                   6915:   margin: 2px;
1.794     www      6916: }
                   6917: 
                   6918: .LC_disc_action_right {
1.1050    www      6919:   background: $sidebg;
1.911     bisitz   6920:   text-align: right;
1.1050    www      6921:   padding: 4px;
                   6922:   margin: 2px;
1.794     www      6923: }
                   6924: 
                   6925: .LC_disc_new_item {
1.911     bisitz   6926:   background: white;
                   6927:   border: 2px solid red;
1.1050    www      6928:   margin: 4px;
                   6929:   padding: 4px;
1.794     www      6930: }
                   6931: 
                   6932: .LC_disc_old_item {
1.911     bisitz   6933:   background: white;
1.1050    www      6934:   margin: 4px;
                   6935:   padding: 4px;
1.794     www      6936: }
                   6937: 
1.458     albertel 6938: table.LC_pastsubmission {
                   6939:   border: 1px solid black;
                   6940:   margin: 2px;
                   6941: }
                   6942: 
1.924     bisitz   6943: table#LC_menubuttons {
1.345     albertel 6944:   width: 100%;
                   6945:   background: $pgbg;
1.392     albertel 6946:   border: 2px;
1.402     albertel 6947:   border-collapse: separate;
1.803     bisitz   6948:   padding: 0;
1.345     albertel 6949: }
1.392     albertel 6950: 
1.801     tempelho 6951: table#LC_title_bar a {
                   6952:   color: $fontmenu;
                   6953: }
1.836     bisitz   6954: 
1.807     droeschl 6955: table#LC_title_bar {
1.819     tempelho 6956:   clear: both;
1.836     bisitz   6957:   display: none;
1.807     droeschl 6958: }
                   6959: 
1.795     www      6960: table#LC_title_bar,
1.933     droeschl 6961: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6962: table#LC_title_bar.LC_with_remote {
1.359     albertel 6963:   width: 100%;
1.392     albertel 6964:   border-color: $pgbg;
                   6965:   border-style: solid;
                   6966:   border-width: $border;
1.379     albertel 6967:   background: $pgbg;
1.801     tempelho 6968:   color: $fontmenu;
1.392     albertel 6969:   border-collapse: collapse;
1.803     bisitz   6970:   padding: 0;
1.819     tempelho 6971:   margin: 0;
1.359     albertel 6972: }
1.795     www      6973: 
1.933     droeschl 6974: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6975:     margin: 0;
                   6976:     padding: 0;
1.933     droeschl 6977:     position: relative;
                   6978:     list-style: none;
1.913     droeschl 6979: }
1.933     droeschl 6980: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6981:     display: inline;
                   6982: }
1.933     droeschl 6983: 
                   6984: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6985:     padding: 0;
1.933     droeschl 6986:     margin: 0;
                   6987:     float: left;
1.913     droeschl 6988: }
1.933     droeschl 6989: .LC_breadcrumb_tools_tools {
                   6990:     padding: 0;
                   6991:     margin: 0;
1.913     droeschl 6992:     float: right;
                   6993: }
                   6994: 
1.1240    raeburn  6995: .LC_placement_prog {
                   6996:     padding-right: 20px;
                   6997:     font-weight: bold;
                   6998:     font-size: 90%;
                   6999: }
                   7000: 
1.359     albertel 7001: table#LC_title_bar td {
                   7002:   background: $tabbg;
                   7003: }
1.795     www      7004: 
1.911     bisitz   7005: table#LC_menubuttons img {
1.803     bisitz   7006:   border: none;
1.346     albertel 7007: }
1.795     www      7008: 
1.842     droeschl 7009: .LC_breadcrumbs_component {
1.911     bisitz   7010:   float: right;
                   7011:   margin: 0 1em;
1.357     albertel 7012: }
1.842     droeschl 7013: .LC_breadcrumbs_component img {
1.911     bisitz   7014:   vertical-align: middle;
1.777     tempelho 7015: }
1.795     www      7016: 
1.1243    raeburn  7017: .LC_breadcrumbs_hoverable {
                   7018:   background: $sidebg;
                   7019: }
                   7020: 
1.383     albertel 7021: td.LC_table_cell_checkbox {
                   7022:   text-align: center;
                   7023: }
1.795     www      7024: 
                   7025: .LC_fontsize_small {
1.911     bisitz   7026:   font-size: 70%;
1.705     tempelho 7027: }
                   7028: 
1.844     bisitz   7029: #LC_breadcrumbs {
1.911     bisitz   7030:   clear:both;
                   7031:   background: $sidebg;
                   7032:   border-bottom: 1px solid $lg_border_color;
                   7033:   line-height: 2.5em;
1.933     droeschl 7034:   overflow: hidden;
1.911     bisitz   7035:   margin: 0;
                   7036:   padding: 0;
1.995     raeburn  7037:   text-align: left;
1.819     tempelho 7038: }
1.862     bisitz   7039: 
1.1098    bisitz   7040: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7041:   clear:both;
                   7042:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7043:   border: 1px solid $sidebg;
1.1098    bisitz   7044:   margin: 0 0 10px 0;
1.966     bisitz   7045:   padding: 3px;
1.995     raeburn  7046:   text-align: left;
1.822     bisitz   7047: }
                   7048: 
1.795     www      7049: .LC_fontsize_medium {
1.911     bisitz   7050:   font-size: 85%;
1.705     tempelho 7051: }
                   7052: 
1.795     www      7053: .LC_fontsize_large {
1.911     bisitz   7054:   font-size: 120%;
1.705     tempelho 7055: }
                   7056: 
1.346     albertel 7057: .LC_menubuttons_inline_text {
                   7058:   color: $font;
1.698     harmsja  7059:   font-size: 90%;
1.701     harmsja  7060:   padding-left:3px;
1.346     albertel 7061: }
                   7062: 
1.934     droeschl 7063: .LC_menubuttons_inline_text img{
                   7064:   vertical-align: middle;
                   7065: }
                   7066: 
1.1051    www      7067: li.LC_menubuttons_inline_text img {
1.951     onken    7068:   cursor:pointer;
1.1002    droeschl 7069:   text-decoration: none;
1.951     onken    7070: }
                   7071: 
1.526     www      7072: .LC_menubuttons_link {
                   7073:   text-decoration: none;
                   7074: }
1.795     www      7075: 
1.522     albertel 7076: .LC_menubuttons_category {
1.521     www      7077:   color: $font;
1.526     www      7078:   background: $pgbg;
1.521     www      7079:   font-size: larger;
                   7080:   font-weight: bold;
                   7081: }
                   7082: 
1.346     albertel 7083: td.LC_menubuttons_text {
1.911     bisitz   7084:   color: $font;
1.346     albertel 7085: }
1.706     harmsja  7086: 
1.346     albertel 7087: .LC_current_location {
                   7088:   background: $tabbg;
                   7089: }
1.795     www      7090: 
1.1286    raeburn  7091: td.LC_zero_height {
                   7092:   line-height: 0; 
                   7093:   cellpadding: 0;
                   7094: }
                   7095: 
1.938     bisitz   7096: table.LC_data_table {
1.347     albertel 7097:   border: 1px solid #000000;
1.402     albertel 7098:   border-collapse: separate;
1.426     albertel 7099:   border-spacing: 1px;
1.610     albertel 7100:   background: $pgbg;
1.347     albertel 7101: }
1.795     www      7102: 
1.422     albertel 7103: .LC_data_table_dense {
                   7104:   font-size: small;
                   7105: }
1.795     www      7106: 
1.507     raeburn  7107: table.LC_nested_outer {
                   7108:   border: 1px solid #000000;
1.589     raeburn  7109:   border-collapse: collapse;
1.803     bisitz   7110:   border-spacing: 0;
1.507     raeburn  7111:   width: 100%;
                   7112: }
1.795     www      7113: 
1.879     raeburn  7114: table.LC_innerpickbox,
1.507     raeburn  7115: table.LC_nested {
1.803     bisitz   7116:   border: none;
1.589     raeburn  7117:   border-collapse: collapse;
1.803     bisitz   7118:   border-spacing: 0;
1.507     raeburn  7119:   width: 100%;
                   7120: }
1.795     www      7121: 
1.911     bisitz   7122: table.LC_data_table tr th,
                   7123: table.LC_calendar tr th,
1.879     raeburn  7124: table.LC_prior_tries tr th,
                   7125: table.LC_innerpickbox tr th {
1.349     albertel 7126:   font-weight: bold;
                   7127:   background-color: $data_table_head;
1.801     tempelho 7128:   color:$fontmenu;
1.701     harmsja  7129:   font-size:90%;
1.347     albertel 7130: }
1.795     www      7131: 
1.879     raeburn  7132: table.LC_innerpickbox tr th,
                   7133: table.LC_innerpickbox tr td {
                   7134:   vertical-align: top;
                   7135: }
                   7136: 
1.711     raeburn  7137: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7138:   background-color: #CCCCCC;
1.711     raeburn  7139:   font-weight: bold;
                   7140:   text-align: left;
                   7141: }
1.795     www      7142: 
1.912     bisitz   7143: table.LC_data_table tr.LC_odd_row > td {
                   7144:   background-color: $data_table_light;
                   7145:   padding: 2px;
                   7146:   vertical-align: top;
                   7147: }
                   7148: 
1.809     bisitz   7149: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7150:   background-color: $data_table_light;
1.912     bisitz   7151:   vertical-align: top;
                   7152: }
                   7153: 
                   7154: table.LC_data_table tr.LC_even_row > td {
                   7155:   background-color: $data_table_dark;
1.425     albertel 7156:   padding: 2px;
1.900     bisitz   7157:   vertical-align: top;
1.347     albertel 7158: }
1.795     www      7159: 
1.809     bisitz   7160: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7161:   background-color: $data_table_dark;
1.900     bisitz   7162:   vertical-align: top;
1.347     albertel 7163: }
1.795     www      7164: 
1.425     albertel 7165: table.LC_data_table tr.LC_data_table_highlight td {
                   7166:   background-color: $data_table_darker;
                   7167: }
1.795     www      7168: 
1.639     raeburn  7169: table.LC_data_table tr td.LC_leftcol_header {
                   7170:   background-color: $data_table_head;
                   7171:   font-weight: bold;
                   7172: }
1.795     www      7173: 
1.451     albertel 7174: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7175: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7176:   font-weight: bold;
                   7177:   font-style: italic;
                   7178:   text-align: center;
                   7179:   padding: 8px;
1.347     albertel 7180: }
1.795     www      7181: 
1.1114    raeburn  7182: table.LC_data_table tr.LC_empty_row td,
                   7183: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7184:   background-color: $sidebg;
                   7185: }
                   7186: 
                   7187: table.LC_nested tr.LC_empty_row td {
                   7188:   background-color: #FFFFFF;
                   7189: }
                   7190: 
1.890     droeschl 7191: table.LC_caption {
                   7192: }
                   7193: 
1.507     raeburn  7194: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7195:   padding: 4ex
                   7196: }
1.795     www      7197: 
1.507     raeburn  7198: table.LC_nested_outer tr th {
                   7199:   font-weight: bold;
1.801     tempelho 7200:   color:$fontmenu;
1.507     raeburn  7201:   background-color: $data_table_head;
1.701     harmsja  7202:   font-size: small;
1.507     raeburn  7203:   border-bottom: 1px solid #000000;
                   7204: }
1.795     www      7205: 
1.507     raeburn  7206: table.LC_nested_outer tr td.LC_subheader {
                   7207:   background-color: $data_table_head;
                   7208:   font-weight: bold;
                   7209:   font-size: small;
                   7210:   border-bottom: 1px solid #000000;
                   7211:   text-align: right;
1.451     albertel 7212: }
1.795     www      7213: 
1.507     raeburn  7214: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7215:   background-color: #CCCCCC;
1.451     albertel 7216:   font-weight: bold;
                   7217:   font-size: small;
1.507     raeburn  7218:   text-align: center;
                   7219: }
1.795     www      7220: 
1.589     raeburn  7221: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7222: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7223:   text-align: left;
1.451     albertel 7224: }
1.795     www      7225: 
1.507     raeburn  7226: table.LC_nested td {
1.735     bisitz   7227:   background-color: #FFFFFF;
1.451     albertel 7228:   font-size: small;
1.507     raeburn  7229: }
1.795     www      7230: 
1.507     raeburn  7231: table.LC_nested_outer tr th.LC_right_item,
                   7232: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7233: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7234: table.LC_nested tr td.LC_right_item {
1.451     albertel 7235:   text-align: right;
                   7236: }
                   7237: 
1.507     raeburn  7238: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7239:   background-color: #EEEEEE;
1.451     albertel 7240: }
                   7241: 
1.473     raeburn  7242: table.LC_createuser {
                   7243: }
                   7244: 
                   7245: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7246:   font-size: small;
1.473     raeburn  7247: }
                   7248: 
                   7249: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7250:   background-color: #CCCCCC;
1.473     raeburn  7251:   font-weight: bold;
                   7252:   text-align: center;
                   7253: }
                   7254: 
1.349     albertel 7255: table.LC_calendar {
                   7256:   border: 1px solid #000000;
                   7257:   border-collapse: collapse;
1.917     raeburn  7258:   width: 98%;
1.349     albertel 7259: }
1.795     www      7260: 
1.349     albertel 7261: table.LC_calendar_pickdate {
                   7262:   font-size: xx-small;
                   7263: }
1.795     www      7264: 
1.349     albertel 7265: table.LC_calendar tr td {
                   7266:   border: 1px solid #000000;
                   7267:   vertical-align: top;
1.917     raeburn  7268:   width: 14%;
1.349     albertel 7269: }
1.795     www      7270: 
1.349     albertel 7271: table.LC_calendar tr td.LC_calendar_day_empty {
                   7272:   background-color: $data_table_dark;
                   7273: }
1.795     www      7274: 
1.779     bisitz   7275: table.LC_calendar tr td.LC_calendar_day_current {
                   7276:   background-color: $data_table_highlight;
1.777     tempelho 7277: }
1.795     www      7278: 
1.938     bisitz   7279: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7280:   background-color: $mail_new;
                   7281: }
1.795     www      7282: 
1.938     bisitz   7283: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7284:   background-color: $mail_new_hover;
                   7285: }
1.795     www      7286: 
1.938     bisitz   7287: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7288:   background-color: $mail_read;
                   7289: }
1.795     www      7290: 
1.938     bisitz   7291: /*
                   7292: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7293:   background-color: $mail_read_hover;
                   7294: }
1.938     bisitz   7295: */
1.795     www      7296: 
1.938     bisitz   7297: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7298:   background-color: $mail_replied;
                   7299: }
1.795     www      7300: 
1.938     bisitz   7301: /*
                   7302: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7303:   background-color: $mail_replied_hover;
                   7304: }
1.938     bisitz   7305: */
1.795     www      7306: 
1.938     bisitz   7307: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7308:   background-color: $mail_other;
                   7309: }
1.795     www      7310: 
1.938     bisitz   7311: /*
                   7312: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7313:   background-color: $mail_other_hover;
                   7314: }
1.938     bisitz   7315: */
1.494     raeburn  7316: 
1.777     tempelho 7317: table.LC_data_table tr > td.LC_browser_file,
                   7318: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7319:   background: #AAEE77;
1.389     albertel 7320: }
1.795     www      7321: 
1.777     tempelho 7322: table.LC_data_table tr > td.LC_browser_file_locked,
                   7323: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7324:   background: #FFAA99;
1.387     albertel 7325: }
1.795     www      7326: 
1.777     tempelho 7327: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7328:   background: #888888;
1.779     bisitz   7329: }
1.795     www      7330: 
1.777     tempelho 7331: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7332: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7333:   background: #F8F866;
1.777     tempelho 7334: }
1.795     www      7335: 
1.696     bisitz   7336: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7337:   background: #E0E8FF;
1.387     albertel 7338: }
1.696     bisitz   7339: 
1.707     bisitz   7340: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7341:   /* background: #77FF77; */
1.707     bisitz   7342: }
1.795     www      7343: 
1.707     bisitz   7344: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7345:   border-right: 8px solid #FFFF77;
1.707     bisitz   7346: }
1.795     www      7347: 
1.707     bisitz   7348: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7349:   border-right: 8px solid #FFAA77;
1.707     bisitz   7350: }
1.795     www      7351: 
1.707     bisitz   7352: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7353:   border-right: 8px solid #FF7777;
1.707     bisitz   7354: }
1.795     www      7355: 
1.707     bisitz   7356: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7357:   border-right: 8px solid #AAFF77;
1.707     bisitz   7358: }
1.795     www      7359: 
1.707     bisitz   7360: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7361:   border-right: 8px solid #11CC55;
1.707     bisitz   7362: }
                   7363: 
1.388     albertel 7364: span.LC_current_location {
1.701     harmsja  7365:   font-size:larger;
1.388     albertel 7366:   background: $pgbg;
                   7367: }
1.387     albertel 7368: 
1.1029    www      7369: span.LC_current_nav_location {
                   7370:   font-weight:bold;
                   7371:   background: $sidebg;
                   7372: }
                   7373: 
1.395     albertel 7374: span.LC_parm_menu_item {
                   7375:   font-size: larger;
                   7376: }
1.795     www      7377: 
1.395     albertel 7378: span.LC_parm_scope_all {
                   7379:   color: red;
                   7380: }
1.795     www      7381: 
1.395     albertel 7382: span.LC_parm_scope_folder {
                   7383:   color: green;
                   7384: }
1.795     www      7385: 
1.395     albertel 7386: span.LC_parm_scope_resource {
                   7387:   color: orange;
                   7388: }
1.795     www      7389: 
1.395     albertel 7390: span.LC_parm_part {
                   7391:   color: blue;
                   7392: }
1.795     www      7393: 
1.911     bisitz   7394: span.LC_parm_folder,
                   7395: span.LC_parm_symb {
1.395     albertel 7396:   font-size: x-small;
                   7397:   font-family: $mono;
                   7398:   color: #AAAAAA;
                   7399: }
                   7400: 
1.977     bisitz   7401: ul.LC_parm_parmlist li {
                   7402:   display: inline-block;
                   7403:   padding: 0.3em 0.8em;
                   7404:   vertical-align: top;
                   7405:   width: 150px;
                   7406:   border-top:1px solid $lg_border_color;
                   7407: }
                   7408: 
1.795     www      7409: td.LC_parm_overview_level_menu,
                   7410: td.LC_parm_overview_map_menu,
                   7411: td.LC_parm_overview_parm_selectors,
                   7412: td.LC_parm_overview_restrictions  {
1.396     albertel 7413:   border: 1px solid black;
                   7414:   border-collapse: collapse;
                   7415: }
1.795     www      7416: 
1.1285    raeburn  7417: span.LC_parm_recursive,
                   7418: td.LC_parm_recursive {
                   7419:   font-weight: bold;
                   7420:   font-size: smaller;
                   7421: }
                   7422: 
1.396     albertel 7423: table.LC_parm_overview_restrictions td {
                   7424:   border-width: 1px 4px 1px 4px;
                   7425:   border-style: solid;
                   7426:   border-color: $pgbg;
                   7427:   text-align: center;
                   7428: }
1.795     www      7429: 
1.396     albertel 7430: table.LC_parm_overview_restrictions th {
                   7431:   background: $tabbg;
                   7432:   border-width: 1px 4px 1px 4px;
                   7433:   border-style: solid;
                   7434:   border-color: $pgbg;
                   7435: }
1.795     www      7436: 
1.398     albertel 7437: table#LC_helpmenu {
1.803     bisitz   7438:   border: none;
1.398     albertel 7439:   height: 55px;
1.803     bisitz   7440:   border-spacing: 0;
1.398     albertel 7441: }
                   7442: 
                   7443: table#LC_helpmenu fieldset legend {
                   7444:   font-size: larger;
                   7445: }
1.795     www      7446: 
1.397     albertel 7447: table#LC_helpmenu_links {
                   7448:   width: 100%;
                   7449:   border: 1px solid black;
                   7450:   background: $pgbg;
1.803     bisitz   7451:   padding: 0;
1.397     albertel 7452:   border-spacing: 1px;
                   7453: }
1.795     www      7454: 
1.397     albertel 7455: table#LC_helpmenu_links tr td {
                   7456:   padding: 1px;
                   7457:   background: $tabbg;
1.399     albertel 7458:   text-align: center;
                   7459:   font-weight: bold;
1.397     albertel 7460: }
1.396     albertel 7461: 
1.795     www      7462: table#LC_helpmenu_links a:link,
                   7463: table#LC_helpmenu_links a:visited,
1.397     albertel 7464: table#LC_helpmenu_links a:active {
                   7465:   text-decoration: none;
                   7466:   color: $font;
                   7467: }
1.795     www      7468: 
1.397     albertel 7469: table#LC_helpmenu_links a:hover {
                   7470:   text-decoration: underline;
                   7471:   color: $vlink;
                   7472: }
1.396     albertel 7473: 
1.417     albertel 7474: .LC_chrt_popup_exists {
                   7475:   border: 1px solid #339933;
                   7476:   margin: -1px;
                   7477: }
1.795     www      7478: 
1.417     albertel 7479: .LC_chrt_popup_up {
                   7480:   border: 1px solid yellow;
                   7481:   margin: -1px;
                   7482: }
1.795     www      7483: 
1.417     albertel 7484: .LC_chrt_popup {
                   7485:   border: 1px solid #8888FF;
                   7486:   background: #CCCCFF;
                   7487: }
1.795     www      7488: 
1.421     albertel 7489: table.LC_pick_box {
                   7490:   border-collapse: separate;
                   7491:   background: white;
                   7492:   border: 1px solid black;
                   7493:   border-spacing: 1px;
                   7494: }
1.795     www      7495: 
1.421     albertel 7496: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7497:   background: $sidebg;
1.421     albertel 7498:   font-weight: bold;
1.900     bisitz   7499:   text-align: left;
1.740     bisitz   7500:   vertical-align: top;
1.421     albertel 7501:   width: 184px;
                   7502:   padding: 8px;
                   7503: }
1.795     www      7504: 
1.579     raeburn  7505: table.LC_pick_box td.LC_pick_box_value {
                   7506:   text-align: left;
                   7507:   padding: 8px;
                   7508: }
1.795     www      7509: 
1.579     raeburn  7510: table.LC_pick_box td.LC_pick_box_select {
                   7511:   text-align: left;
                   7512:   padding: 8px;
                   7513: }
1.795     www      7514: 
1.424     albertel 7515: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7516:   padding: 0;
1.421     albertel 7517:   height: 1px;
                   7518:   background: black;
                   7519: }
1.795     www      7520: 
1.421     albertel 7521: table.LC_pick_box td.LC_pick_box_submit {
                   7522:   text-align: right;
                   7523: }
1.795     www      7524: 
1.579     raeburn  7525: table.LC_pick_box td.LC_evenrow_value {
                   7526:   text-align: left;
                   7527:   padding: 8px;
                   7528:   background-color: $data_table_light;
                   7529: }
1.795     www      7530: 
1.579     raeburn  7531: table.LC_pick_box td.LC_oddrow_value {
                   7532:   text-align: left;
                   7533:   padding: 8px;
                   7534:   background-color: $data_table_light;
                   7535: }
1.795     www      7536: 
1.579     raeburn  7537: span.LC_helpform_receipt_cat {
                   7538:   font-weight: bold;
                   7539: }
1.795     www      7540: 
1.424     albertel 7541: table.LC_group_priv_box {
                   7542:   background: white;
                   7543:   border: 1px solid black;
                   7544:   border-spacing: 1px;
                   7545: }
1.795     www      7546: 
1.424     albertel 7547: table.LC_group_priv_box td.LC_pick_box_title {
                   7548:   background: $tabbg;
                   7549:   font-weight: bold;
                   7550:   text-align: right;
                   7551:   width: 184px;
                   7552: }
1.795     www      7553: 
1.424     albertel 7554: table.LC_group_priv_box td.LC_groups_fixed {
                   7555:   background: $data_table_light;
                   7556:   text-align: center;
                   7557: }
1.795     www      7558: 
1.424     albertel 7559: table.LC_group_priv_box td.LC_groups_optional {
                   7560:   background: $data_table_dark;
                   7561:   text-align: center;
                   7562: }
1.795     www      7563: 
1.424     albertel 7564: table.LC_group_priv_box td.LC_groups_functionality {
                   7565:   background: $data_table_darker;
                   7566:   text-align: center;
                   7567:   font-weight: bold;
                   7568: }
1.795     www      7569: 
1.424     albertel 7570: table.LC_group_priv td {
                   7571:   text-align: left;
1.803     bisitz   7572:   padding: 0;
1.424     albertel 7573: }
                   7574: 
                   7575: .LC_navbuttons {
                   7576:   margin: 2ex 0ex 2ex 0ex;
                   7577: }
1.795     www      7578: 
1.423     albertel 7579: .LC_topic_bar {
                   7580:   font-weight: bold;
                   7581:   background: $tabbg;
1.918     wenzelju 7582:   margin: 1em 0em 1em 2em;
1.805     bisitz   7583:   padding: 3px;
1.918     wenzelju 7584:   font-size: 1.2em;
1.423     albertel 7585: }
1.795     www      7586: 
1.423     albertel 7587: .LC_topic_bar span {
1.918     wenzelju 7588:   left: 0.5em;
                   7589:   position: absolute;
1.423     albertel 7590:   vertical-align: middle;
1.918     wenzelju 7591:   font-size: 1.2em;
1.423     albertel 7592: }
1.795     www      7593: 
1.423     albertel 7594: table.LC_course_group_status {
                   7595:   margin: 20px;
                   7596: }
1.795     www      7597: 
1.423     albertel 7598: table.LC_status_selector td {
                   7599:   vertical-align: top;
                   7600:   text-align: center;
1.424     albertel 7601:   padding: 4px;
                   7602: }
1.795     www      7603: 
1.599     albertel 7604: div.LC_feedback_link {
1.616     albertel 7605:   clear: both;
1.829     kalberla 7606:   background: $sidebg;
1.779     bisitz   7607:   width: 100%;
1.829     kalberla 7608:   padding-bottom: 10px;
                   7609:   border: 1px $tabbg solid;
1.833     kalberla 7610:   height: 22px;
                   7611:   line-height: 22px;
                   7612:   padding-top: 5px;
                   7613: }
                   7614: 
                   7615: div.LC_feedback_link img {
                   7616:   height: 22px;
1.867     kalberla 7617:   vertical-align:middle;
1.829     kalberla 7618: }
                   7619: 
1.911     bisitz   7620: div.LC_feedback_link a {
1.829     kalberla 7621:   text-decoration: none;
1.489     raeburn  7622: }
1.795     www      7623: 
1.867     kalberla 7624: div.LC_comblock {
1.911     bisitz   7625:   display:inline;
1.867     kalberla 7626:   color:$font;
                   7627:   font-size:90%;
                   7628: }
                   7629: 
                   7630: div.LC_feedback_link div.LC_comblock {
                   7631:   padding-left:5px;
                   7632: }
                   7633: 
                   7634: div.LC_feedback_link div.LC_comblock a {
                   7635:   color:$font;
                   7636: }
                   7637: 
1.489     raeburn  7638: span.LC_feedback_link {
1.858     bisitz   7639:   /* background: $feedback_link_bg; */
1.599     albertel 7640:   font-size: larger;
                   7641: }
1.795     www      7642: 
1.599     albertel 7643: span.LC_message_link {
1.858     bisitz   7644:   /* background: $feedback_link_bg; */
1.599     albertel 7645:   font-size: larger;
                   7646:   position: absolute;
                   7647:   right: 1em;
1.489     raeburn  7648: }
1.421     albertel 7649: 
1.515     albertel 7650: table.LC_prior_tries {
1.524     albertel 7651:   border: 1px solid #000000;
                   7652:   border-collapse: separate;
                   7653:   border-spacing: 1px;
1.515     albertel 7654: }
1.523     albertel 7655: 
1.515     albertel 7656: table.LC_prior_tries td {
1.524     albertel 7657:   padding: 2px;
1.515     albertel 7658: }
1.523     albertel 7659: 
                   7660: .LC_answer_correct {
1.795     www      7661:   background: lightgreen;
                   7662:   color: darkgreen;
                   7663:   padding: 6px;
1.523     albertel 7664: }
1.795     www      7665: 
1.523     albertel 7666: .LC_answer_charged_try {
1.797     www      7667:   background: #FFAAAA;
1.795     www      7668:   color: darkred;
                   7669:   padding: 6px;
1.523     albertel 7670: }
1.795     www      7671: 
1.779     bisitz   7672: .LC_answer_not_charged_try,
1.523     albertel 7673: .LC_answer_no_grade,
                   7674: .LC_answer_late {
1.795     www      7675:   background: lightyellow;
1.523     albertel 7676:   color: black;
1.795     www      7677:   padding: 6px;
1.523     albertel 7678: }
1.795     www      7679: 
1.523     albertel 7680: .LC_answer_previous {
1.795     www      7681:   background: lightblue;
                   7682:   color: darkblue;
                   7683:   padding: 6px;
1.523     albertel 7684: }
1.795     www      7685: 
1.779     bisitz   7686: .LC_answer_no_message {
1.777     tempelho 7687:   background: #FFFFFF;
                   7688:   color: black;
1.795     www      7689:   padding: 6px;
1.779     bisitz   7690: }
1.795     www      7691: 
1.1334    raeburn  7692: .LC_answer_unknown,
                   7693: .LC_answer_warning {
1.779     bisitz   7694:   background: orange;
                   7695:   color: black;
1.795     www      7696:   padding: 6px;
1.777     tempelho 7697: }
1.795     www      7698: 
1.529     albertel 7699: span.LC_prior_numerical,
                   7700: span.LC_prior_string,
                   7701: span.LC_prior_custom,
                   7702: span.LC_prior_reaction,
                   7703: span.LC_prior_math {
1.925     bisitz   7704:   font-family: $mono;
1.523     albertel 7705:   white-space: pre;
                   7706: }
                   7707: 
1.525     albertel 7708: span.LC_prior_string {
1.925     bisitz   7709:   font-family: $mono;
1.525     albertel 7710:   white-space: pre;
                   7711: }
                   7712: 
1.523     albertel 7713: table.LC_prior_option {
                   7714:   width: 100%;
                   7715:   border-collapse: collapse;
                   7716: }
1.795     www      7717: 
1.911     bisitz   7718: table.LC_prior_rank,
1.795     www      7719: table.LC_prior_match {
1.528     albertel 7720:   border-collapse: collapse;
                   7721: }
1.795     www      7722: 
1.528     albertel 7723: table.LC_prior_option tr td,
                   7724: table.LC_prior_rank tr td,
                   7725: table.LC_prior_match tr td {
1.524     albertel 7726:   border: 1px solid #000000;
1.515     albertel 7727: }
                   7728: 
1.855     bisitz   7729: .LC_nobreak {
1.544     albertel 7730:   white-space: nowrap;
1.519     raeburn  7731: }
                   7732: 
1.576     raeburn  7733: span.LC_cusr_emph {
                   7734:   font-style: italic;
                   7735: }
                   7736: 
1.633     raeburn  7737: span.LC_cusr_subheading {
                   7738:   font-weight: normal;
                   7739:   font-size: 85%;
                   7740: }
                   7741: 
1.861     bisitz   7742: div.LC_docs_entry_move {
1.859     bisitz   7743:   border: 1px solid #BBBBBB;
1.545     albertel 7744:   background: #DDDDDD;
1.861     bisitz   7745:   width: 22px;
1.859     bisitz   7746:   padding: 1px;
                   7747:   margin: 0;
1.545     albertel 7748: }
                   7749: 
1.861     bisitz   7750: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7751: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7752:   font-size: x-small;
                   7753: }
1.795     www      7754: 
1.861     bisitz   7755: .LC_docs_entry_parameter {
                   7756:   white-space: nowrap;
                   7757: }
                   7758: 
1.544     albertel 7759: .LC_docs_copy {
1.545     albertel 7760:   color: #000099;
1.544     albertel 7761: }
1.795     www      7762: 
1.544     albertel 7763: .LC_docs_cut {
1.545     albertel 7764:   color: #550044;
1.544     albertel 7765: }
1.795     www      7766: 
1.544     albertel 7767: .LC_docs_rename {
1.545     albertel 7768:   color: #009900;
1.544     albertel 7769: }
1.795     www      7770: 
1.544     albertel 7771: .LC_docs_remove {
1.545     albertel 7772:   color: #990000;
                   7773: }
                   7774: 
1.1284    raeburn  7775: .LC_docs_alias {
                   7776:   color: #440055;  
                   7777: }
                   7778: 
1.1286    raeburn  7779: .LC_domprefs_email,
1.1284    raeburn  7780: .LC_docs_alias_name,
1.547     albertel 7781: .LC_docs_reinit_warn,
                   7782: .LC_docs_ext_edit {
                   7783:   font-size: x-small;
                   7784: }
                   7785: 
1.545     albertel 7786: table.LC_docs_adddocs td,
                   7787: table.LC_docs_adddocs th {
                   7788:   border: 1px solid #BBBBBB;
                   7789:   padding: 4px;
                   7790:   background: #DDDDDD;
1.543     albertel 7791: }
                   7792: 
1.584     albertel 7793: table.LC_sty_begin {
                   7794:   background: #BBFFBB;
                   7795: }
1.795     www      7796: 
1.584     albertel 7797: table.LC_sty_end {
                   7798:   background: #FFBBBB;
                   7799: }
                   7800: 
1.589     raeburn  7801: table.LC_double_column {
1.803     bisitz   7802:   border-width: 0;
1.589     raeburn  7803:   border-collapse: collapse;
                   7804:   width: 100%;
                   7805:   padding: 2px;
                   7806: }
                   7807: 
                   7808: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7809:   top: 2px;
1.589     raeburn  7810:   left: 2px;
                   7811:   width: 47%;
                   7812:   vertical-align: top;
                   7813: }
                   7814: 
                   7815: table.LC_double_column tr td.LC_right_col {
                   7816:   top: 2px;
1.779     bisitz   7817:   right: 2px;
1.589     raeburn  7818:   width: 47%;
                   7819:   vertical-align: top;
                   7820: }
                   7821: 
1.591     raeburn  7822: div.LC_left_float {
                   7823:   float: left;
                   7824:   padding-right: 5%;
1.597     albertel 7825:   padding-bottom: 4px;
1.591     raeburn  7826: }
                   7827: 
                   7828: div.LC_clear_float_header {
1.597     albertel 7829:   padding-bottom: 2px;
1.591     raeburn  7830: }
                   7831: 
                   7832: div.LC_clear_float_footer {
1.597     albertel 7833:   padding-top: 10px;
1.591     raeburn  7834:   clear: both;
                   7835: }
                   7836: 
1.597     albertel 7837: div.LC_grade_show_user {
1.941     bisitz   7838: /*  border-left: 5px solid $sidebg; */
                   7839:   border-top: 5px solid #000000;
                   7840:   margin: 50px 0 0 0;
1.936     bisitz   7841:   padding: 15px 0 5px 10px;
1.597     albertel 7842: }
1.795     www      7843: 
1.936     bisitz   7844: div.LC_grade_show_user_odd_row {
1.941     bisitz   7845: /*  border-left: 5px solid #000000; */
                   7846: }
                   7847: 
                   7848: div.LC_grade_show_user div.LC_Box {
                   7849:   margin-right: 50px;
1.597     albertel 7850: }
                   7851: 
                   7852: div.LC_grade_submissions,
                   7853: div.LC_grade_message_center,
1.936     bisitz   7854: div.LC_grade_info_links {
1.597     albertel 7855:   margin: 5px;
                   7856:   width: 99%;
                   7857:   background: #FFFFFF;
                   7858: }
1.795     www      7859: 
1.597     albertel 7860: div.LC_grade_submissions_header,
1.936     bisitz   7861: div.LC_grade_message_center_header {
1.705     tempelho 7862:   font-weight: bold;
                   7863:   font-size: large;
1.597     albertel 7864: }
1.795     www      7865: 
1.597     albertel 7866: div.LC_grade_submissions_body,
1.936     bisitz   7867: div.LC_grade_message_center_body {
1.597     albertel 7868:   border: 1px solid black;
                   7869:   width: 99%;
                   7870:   background: #FFFFFF;
                   7871: }
1.795     www      7872: 
1.613     albertel 7873: table.LC_scantron_action {
                   7874:   width: 100%;
                   7875: }
1.795     www      7876: 
1.613     albertel 7877: table.LC_scantron_action tr th {
1.698     harmsja  7878:   font-weight:bold;
                   7879:   font-style:normal;
1.613     albertel 7880: }
1.795     www      7881: 
1.779     bisitz   7882: .LC_edit_problem_header,
1.614     albertel 7883: div.LC_edit_problem_footer {
1.705     tempelho 7884:   font-weight: normal;
                   7885:   font-size:  medium;
1.602     albertel 7886:   margin: 2px;
1.1060    bisitz   7887:   background-color: $sidebg;
1.600     albertel 7888: }
1.795     www      7889: 
1.600     albertel 7890: div.LC_edit_problem_header,
1.602     albertel 7891: div.LC_edit_problem_header div,
1.614     albertel 7892: div.LC_edit_problem_footer,
                   7893: div.LC_edit_problem_footer div,
1.602     albertel 7894: div.LC_edit_problem_editxml_header,
                   7895: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7896:   z-index: 100;
1.600     albertel 7897: }
1.795     www      7898: 
1.600     albertel 7899: div.LC_edit_problem_header_title {
1.705     tempelho 7900:   font-weight: bold;
                   7901:   font-size: larger;
1.602     albertel 7902:   background: $tabbg;
                   7903:   padding: 3px;
1.1060    bisitz   7904:   margin: 0 0 5px 0;
1.602     albertel 7905: }
1.795     www      7906: 
1.602     albertel 7907: table.LC_edit_problem_header_title {
                   7908:   width: 100%;
1.600     albertel 7909:   background: $tabbg;
1.602     albertel 7910: }
                   7911: 
1.1205    golterma 7912: div.LC_edit_actionbar {
                   7913:     background-color: $sidebg;
1.1218    droeschl 7914:     margin: 0;
                   7915:     padding: 0;
                   7916:     line-height: 200%;
1.602     albertel 7917: }
1.795     www      7918: 
1.1218    droeschl 7919: div.LC_edit_actionbar div{
                   7920:     padding: 0;
                   7921:     margin: 0;
                   7922:     display: inline-block;
1.600     albertel 7923: }
1.795     www      7924: 
1.1124    bisitz   7925: .LC_edit_opt {
                   7926:   padding-left: 1em;
                   7927:   white-space: nowrap;
                   7928: }
                   7929: 
1.1152    golterma 7930: .LC_edit_problem_latexhelper{
                   7931:     text-align: right;
                   7932: }
                   7933: 
                   7934: #LC_edit_problem_colorful div{
                   7935:     margin-left: 40px;
                   7936: }
                   7937: 
1.1205    golterma 7938: #LC_edit_problem_codemirror div{
                   7939:     margin-left: 0px;
                   7940: }
                   7941: 
1.911     bisitz   7942: img.stift {
1.803     bisitz   7943:   border-width: 0;
                   7944:   vertical-align: middle;
1.677     riegler  7945: }
1.680     riegler  7946: 
1.923     bisitz   7947: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7948:   vertical-align: top;
1.777     tempelho 7949: }
1.795     www      7950: 
1.716     raeburn  7951: div.LC_createcourse {
1.911     bisitz   7952:   margin: 10px 10px 10px 10px;
1.716     raeburn  7953: }
                   7954: 
1.917     raeburn  7955: .LC_dccid {
1.1130    raeburn  7956:   float: right;
1.917     raeburn  7957:   margin: 0.2em 0 0 0;
                   7958:   padding: 0;
                   7959:   font-size: 90%;
                   7960:   display:none;
                   7961: }
                   7962: 
1.897     wenzelju 7963: ol.LC_primary_menu a:hover,
1.721     harmsja  7964: ol#LC_MenuBreadcrumbs a:hover,
                   7965: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7966: ul#LC_secondary_menu a:hover,
1.721     harmsja  7967: .LC_FormSectionClearButton input:hover
1.795     www      7968: ul.LC_TabContent   li:hover a {
1.952     onken    7969:   color:$button_hover;
1.911     bisitz   7970:   text-decoration:none;
1.693     droeschl 7971: }
                   7972: 
1.779     bisitz   7973: h1 {
1.911     bisitz   7974:   padding: 0;
                   7975:   line-height:130%;
1.693     droeschl 7976: }
1.698     harmsja  7977: 
1.911     bisitz   7978: h2,
                   7979: h3,
                   7980: h4,
                   7981: h5,
                   7982: h6 {
                   7983:   margin: 5px 0 5px 0;
                   7984:   padding: 0;
                   7985:   line-height:130%;
1.693     droeschl 7986: }
1.795     www      7987: 
                   7988: .LC_hcell {
1.911     bisitz   7989:   padding:3px 15px 3px 15px;
                   7990:   margin: 0;
                   7991:   background-color:$tabbg;
                   7992:   color:$fontmenu;
                   7993:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7994: }
1.795     www      7995: 
1.840     bisitz   7996: .LC_Box > .LC_hcell {
1.911     bisitz   7997:   margin: 0 -10px 10px -10px;
1.835     bisitz   7998: }
                   7999: 
1.721     harmsja  8000: .LC_noBorder {
1.911     bisitz   8001:   border: 0;
1.698     harmsja  8002: }
1.693     droeschl 8003: 
1.721     harmsja  8004: .LC_FormSectionClearButton input {
1.911     bisitz   8005:   background-color:transparent;
                   8006:   border: none;
                   8007:   cursor:pointer;
                   8008:   text-decoration:underline;
1.693     droeschl 8009: }
1.763     bisitz   8010: 
                   8011: .LC_help_open_topic {
1.911     bisitz   8012:   color: #FFFFFF;
                   8013:   background-color: #EEEEFF;
                   8014:   margin: 1px;
                   8015:   padding: 4px;
                   8016:   border: 1px solid #000033;
                   8017:   white-space: nowrap;
                   8018:   /* vertical-align: middle; */
1.759     neumanie 8019: }
1.693     droeschl 8020: 
1.911     bisitz   8021: dl,
                   8022: ul,
                   8023: div,
                   8024: fieldset {
                   8025:   margin: 10px 10px 10px 0;
                   8026:   /* overflow: hidden; */
1.693     droeschl 8027: }
1.795     www      8028: 
1.1211    raeburn  8029: article.geogebraweb div {
                   8030:     margin: 0;
                   8031: }
                   8032: 
1.838     bisitz   8033: fieldset > legend {
1.911     bisitz   8034:   font-weight: bold;
                   8035:   padding: 0 5px 0 5px;
1.838     bisitz   8036: }
                   8037: 
1.813     bisitz   8038: #LC_nav_bar {
1.911     bisitz   8039:   float: left;
1.995     raeburn  8040:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8041:   margin: 0 0 2px 0;
1.807     droeschl 8042: }
                   8043: 
1.916     droeschl 8044: #LC_realm {
                   8045:   margin: 0.2em 0 0 0;
                   8046:   padding: 0;
                   8047:   font-weight: bold;
                   8048:   text-align: center;
1.995     raeburn  8049:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8050: }
                   8051: 
1.911     bisitz   8052: #LC_nav_bar em {
                   8053:   font-weight: bold;
                   8054:   font-style: normal;
1.807     droeschl 8055: }
                   8056: 
1.897     wenzelju 8057: ol.LC_primary_menu {
1.934     droeschl 8058:   margin: 0;
1.1076    raeburn  8059:   padding: 0;
1.807     droeschl 8060: }
                   8061: 
1.852     droeschl 8062: ol#LC_PathBreadcrumbs {
1.911     bisitz   8063:   margin: 0;
1.693     droeschl 8064: }
                   8065: 
1.897     wenzelju 8066: ol.LC_primary_menu li {
1.1076    raeburn  8067:   color: RGB(80, 80, 80);
                   8068:   vertical-align: middle;
                   8069:   text-align: left;
                   8070:   list-style: none;
1.1205    golterma 8071:   position: relative;
1.1076    raeburn  8072:   float: left;
1.1205    golterma 8073:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8074:   line-height: 1.5em;
1.1076    raeburn  8075: }
                   8076: 
1.1205    golterma 8077: ol.LC_primary_menu li a,
                   8078: ol.LC_primary_menu li p {
1.1076    raeburn  8079:   display: block;
                   8080:   margin: 0;
                   8081:   padding: 0 5px 0 10px;
                   8082:   text-decoration: none;
                   8083: }
                   8084: 
1.1205    golterma 8085: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8086:   display: inline-block;
                   8087:   width: 95%;
                   8088:   text-align: left;
                   8089: }
                   8090: 
                   8091: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8092:   display: inline-block;	
                   8093:   width: 5%;
                   8094:   float: right;
                   8095:   text-align: right;
                   8096:   font-size: 70%;
                   8097: }
                   8098: 
                   8099: ol.LC_primary_menu ul {
1.1076    raeburn  8100:   display: none;
1.1205    golterma 8101:   width: 15em;
1.1076    raeburn  8102:   background-color: $data_table_light;
1.1205    golterma 8103:   position: absolute;
                   8104:   top: 100%;
1.1076    raeburn  8105: }
                   8106: 
1.1205    golterma 8107: ol.LC_primary_menu ul ul {
                   8108:   left: 100%;
                   8109:   top: 0;
                   8110: }
                   8111: 
                   8112: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8113:   display: block;
                   8114:   position: absolute;
                   8115:   margin: 0;
                   8116:   padding: 0;
1.1078    raeburn  8117:   z-index: 2;
1.1076    raeburn  8118: }
                   8119: 
                   8120: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8121: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8122:   font-size: 90%;
1.911     bisitz   8123:   vertical-align: top;
1.1076    raeburn  8124:   float: none;
1.1079    raeburn  8125:   border-left: 1px solid black;
                   8126:   border-right: 1px solid black;
1.1205    golterma 8127: /* A dark bottom border to visualize different menu options; 
                   8128: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8129:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8130: }
                   8131: 
1.1205    golterma 8132: ol.LC_primary_menu li li p:hover {
                   8133:   color:$button_hover;
                   8134:   text-decoration:none;
                   8135:   background-color:$data_table_dark;
1.1076    raeburn  8136: }
                   8137: 
                   8138: ol.LC_primary_menu li li a:hover {
                   8139:    color:$button_hover;
                   8140:    background-color:$data_table_dark;
1.693     droeschl 8141: }
                   8142: 
1.1205    golterma 8143: /* Font-size equal to the size of the predecessors*/
                   8144: ol.LC_primary_menu li:hover li li {
                   8145:   font-size: 100%;
                   8146: }
                   8147: 
1.897     wenzelju 8148: ol.LC_primary_menu li img {
1.911     bisitz   8149:   vertical-align: bottom;
1.934     droeschl 8150:   height: 1.1em;
1.1077    raeburn  8151:   margin: 0.2em 0 0 0;
1.693     droeschl 8152: }
                   8153: 
1.897     wenzelju 8154: ol.LC_primary_menu a {
1.911     bisitz   8155:   color: RGB(80, 80, 80);
                   8156:   text-decoration: none;
1.693     droeschl 8157: }
1.795     www      8158: 
1.949     droeschl 8159: ol.LC_primary_menu a.LC_new_message {
                   8160:   font-weight:bold;
                   8161:   color: darkred;
                   8162: }
                   8163: 
1.975     raeburn  8164: ol.LC_docs_parameters {
                   8165:   margin-left: 0;
                   8166:   padding: 0;
                   8167:   list-style: none;
                   8168: }
                   8169: 
                   8170: ol.LC_docs_parameters li {
                   8171:   margin: 0;
                   8172:   padding-right: 20px;
                   8173:   display: inline;
                   8174: }
                   8175: 
1.976     raeburn  8176: ol.LC_docs_parameters li:before {
                   8177:   content: "\\002022 \\0020";
                   8178: }
                   8179: 
                   8180: li.LC_docs_parameters_title {
                   8181:   font-weight: bold;
                   8182: }
                   8183: 
                   8184: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8185:   content: "";
                   8186: }
                   8187: 
1.897     wenzelju 8188: ul#LC_secondary_menu {
1.1107    raeburn  8189:   clear: right;
1.911     bisitz   8190:   color: $fontmenu;
                   8191:   background: $tabbg;
                   8192:   list-style: none;
                   8193:   padding: 0;
                   8194:   margin: 0;
                   8195:   width: 100%;
1.995     raeburn  8196:   text-align: left;
1.1107    raeburn  8197:   float: left;
1.808     droeschl 8198: }
                   8199: 
1.897     wenzelju 8200: ul#LC_secondary_menu li {
1.911     bisitz   8201:   font-weight: bold;
                   8202:   line-height: 1.8em;
1.1107    raeburn  8203:   border-right: 1px solid black;
                   8204:   float: left;
                   8205: }
                   8206: 
                   8207: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8208:   background-color: $data_table_light;
                   8209: }
                   8210: 
                   8211: ul#LC_secondary_menu li a {
1.911     bisitz   8212:   padding: 0 0.8em;
1.1107    raeburn  8213: }
                   8214: 
                   8215: ul#LC_secondary_menu li ul {
                   8216:   display: none;
                   8217: }
                   8218: 
                   8219: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8220:   display: block;
                   8221:   position: absolute;
                   8222:   margin: 0;
                   8223:   padding: 0;
                   8224:   list-style:none;
                   8225:   float: none;
                   8226:   background-color: $data_table_light;
                   8227:   z-index: 2;
                   8228:   margin-left: -1px;
                   8229: }
                   8230: 
                   8231: ul#LC_secondary_menu li ul li {
                   8232:   font-size: 90%;
                   8233:   vertical-align: top;
                   8234:   border-left: 1px solid black;
1.911     bisitz   8235:   border-right: 1px solid black;
1.1119    raeburn  8236:   background-color: $data_table_light;
1.1107    raeburn  8237:   list-style:none;
                   8238:   float: none;
                   8239: }
                   8240: 
                   8241: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8242:   background-color: $data_table_dark;
1.807     droeschl 8243: }
                   8244: 
1.847     tempelho 8245: ul.LC_TabContent {
1.911     bisitz   8246:   display:block;
                   8247:   background: $sidebg;
                   8248:   border-bottom: solid 1px $lg_border_color;
                   8249:   list-style:none;
1.1020    raeburn  8250:   margin: -1px -10px 0 -10px;
1.911     bisitz   8251:   padding: 0;
1.693     droeschl 8252: }
                   8253: 
1.795     www      8254: ul.LC_TabContent li,
                   8255: ul.LC_TabContentBigger li {
1.911     bisitz   8256:   float:left;
1.741     harmsja  8257: }
1.795     www      8258: 
1.897     wenzelju 8259: ul#LC_secondary_menu li a {
1.911     bisitz   8260:   color: $fontmenu;
                   8261:   text-decoration: none;
1.693     droeschl 8262: }
1.795     www      8263: 
1.721     harmsja  8264: ul.LC_TabContent {
1.952     onken    8265:   min-height:20px;
1.721     harmsja  8266: }
1.795     www      8267: 
                   8268: ul.LC_TabContent li {
1.911     bisitz   8269:   vertical-align:middle;
1.959     onken    8270:   padding: 0 16px 0 10px;
1.911     bisitz   8271:   background-color:$tabbg;
                   8272:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8273:   border-left: solid 1px $font;
1.721     harmsja  8274: }
1.795     www      8275: 
1.847     tempelho 8276: ul.LC_TabContent .right {
1.911     bisitz   8277:   float:right;
1.847     tempelho 8278: }
                   8279: 
1.911     bisitz   8280: ul.LC_TabContent li a,
                   8281: ul.LC_TabContent li {
                   8282:   color:rgb(47,47,47);
                   8283:   text-decoration:none;
                   8284:   font-size:95%;
                   8285:   font-weight:bold;
1.952     onken    8286:   min-height:20px;
                   8287: }
                   8288: 
1.959     onken    8289: ul.LC_TabContent li a:hover,
                   8290: ul.LC_TabContent li a:focus {
1.952     onken    8291:   color: $button_hover;
1.959     onken    8292:   background:none;
                   8293:   outline:none;
1.952     onken    8294: }
                   8295: 
                   8296: ul.LC_TabContent li:hover {
                   8297:   color: $button_hover;
                   8298:   cursor:pointer;
1.721     harmsja  8299: }
1.795     www      8300: 
1.911     bisitz   8301: ul.LC_TabContent li.active {
1.952     onken    8302:   color: $font;
1.911     bisitz   8303:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8304:   border-bottom:solid 1px #FFFFFF;
                   8305:   cursor: default;
1.744     ehlerst  8306: }
1.795     www      8307: 
1.959     onken    8308: ul.LC_TabContent li.active a {
                   8309:   color:$font;
                   8310:   background:#FFFFFF;
                   8311:   outline: none;
                   8312: }
1.1047    raeburn  8313: 
                   8314: ul.LC_TabContent li.goback {
                   8315:   float: left;
                   8316:   border-left: none;
                   8317: }
                   8318: 
1.870     tempelho 8319: #maincoursedoc {
1.911     bisitz   8320:   clear:both;
1.870     tempelho 8321: }
                   8322: 
                   8323: ul.LC_TabContentBigger {
1.911     bisitz   8324:   display:block;
                   8325:   list-style:none;
                   8326:   padding: 0;
1.870     tempelho 8327: }
                   8328: 
1.795     www      8329: ul.LC_TabContentBigger li {
1.911     bisitz   8330:   vertical-align:bottom;
                   8331:   height: 30px;
                   8332:   font-size:110%;
                   8333:   font-weight:bold;
                   8334:   color: #737373;
1.841     tempelho 8335: }
                   8336: 
1.957     onken    8337: ul.LC_TabContentBigger li.active {
                   8338:   position: relative;
                   8339:   top: 1px;
                   8340: }
                   8341: 
1.870     tempelho 8342: ul.LC_TabContentBigger li a {
1.911     bisitz   8343:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8344:   height: 30px;
                   8345:   line-height: 30px;
                   8346:   text-align: center;
                   8347:   display: block;
                   8348:   text-decoration: none;
1.958     onken    8349:   outline: none;  
1.741     harmsja  8350: }
1.795     www      8351: 
1.870     tempelho 8352: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8353:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8354:   color:$font;
1.744     ehlerst  8355: }
1.795     www      8356: 
1.870     tempelho 8357: ul.LC_TabContentBigger li b {
1.911     bisitz   8358:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8359:   display: block;
                   8360:   float: left;
                   8361:   padding: 0 30px;
1.957     onken    8362:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8363: }
                   8364: 
1.956     onken    8365: ul.LC_TabContentBigger li:hover b {
                   8366:   color:$button_hover;
                   8367: }
                   8368: 
1.870     tempelho 8369: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8370:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8371:   color:$font;
1.957     onken    8372:   border: 0;
1.741     harmsja  8373: }
1.693     droeschl 8374: 
1.870     tempelho 8375: 
1.862     bisitz   8376: ul.LC_CourseBreadcrumbs {
                   8377:   background: $sidebg;
1.1020    raeburn  8378:   height: 2em;
1.862     bisitz   8379:   padding-left: 10px;
1.1020    raeburn  8380:   margin: 0;
1.862     bisitz   8381:   list-style-position: inside;
                   8382: }
                   8383: 
1.911     bisitz   8384: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8385: ol#LC_PathBreadcrumbs {
1.911     bisitz   8386:   padding-left: 10px;
                   8387:   margin: 0;
1.933     droeschl 8388:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8389: }
                   8390: 
1.911     bisitz   8391: ol#LC_MenuBreadcrumbs li,
                   8392: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8393: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8394:   display: inline;
1.933     droeschl 8395:   white-space: normal;  
1.693     droeschl 8396: }
                   8397: 
1.823     bisitz   8398: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8399: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8400:   text-decoration: none;
                   8401:   font-size:90%;
1.693     droeschl 8402: }
1.795     www      8403: 
1.969     droeschl 8404: ol#LC_MenuBreadcrumbs h1 {
                   8405:   display: inline;
                   8406:   font-size: 90%;
                   8407:   line-height: 2.5em;
                   8408:   margin: 0;
                   8409:   padding: 0;
                   8410: }
                   8411: 
1.795     www      8412: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8413:   text-decoration:none;
                   8414:   font-size:100%;
                   8415:   font-weight:bold;
1.693     droeschl 8416: }
1.795     www      8417: 
1.840     bisitz   8418: .LC_Box {
1.911     bisitz   8419:   border: solid 1px $lg_border_color;
                   8420:   padding: 0 10px 10px 10px;
1.746     neumanie 8421: }
1.795     www      8422: 
1.1020    raeburn  8423: .LC_DocsBox {
                   8424:   border: solid 1px $lg_border_color;
                   8425:   padding: 0 0 10px 10px;
                   8426: }
                   8427: 
1.795     www      8428: .LC_AboutMe_Image {
1.911     bisitz   8429:   float:left;
                   8430:   margin-right:10px;
1.747     neumanie 8431: }
1.795     www      8432: 
                   8433: .LC_Clear_AboutMe_Image {
1.911     bisitz   8434:   clear:left;
1.747     neumanie 8435: }
1.795     www      8436: 
1.721     harmsja  8437: dl.LC_ListStyleClean dt {
1.911     bisitz   8438:   padding-right: 5px;
                   8439:   display: table-header-group;
1.693     droeschl 8440: }
                   8441: 
1.721     harmsja  8442: dl.LC_ListStyleClean dd {
1.911     bisitz   8443:   display: table-row;
1.693     droeschl 8444: }
                   8445: 
1.721     harmsja  8446: .LC_ListStyleClean,
                   8447: .LC_ListStyleSimple,
                   8448: .LC_ListStyleNormal,
1.795     www      8449: .LC_ListStyleSpecial {
1.911     bisitz   8450:   /* display:block; */
                   8451:   list-style-position: inside;
                   8452:   list-style-type: none;
                   8453:   overflow: hidden;
                   8454:   padding: 0;
1.693     droeschl 8455: }
                   8456: 
1.721     harmsja  8457: .LC_ListStyleSimple li,
                   8458: .LC_ListStyleSimple dd,
                   8459: .LC_ListStyleNormal li,
                   8460: .LC_ListStyleNormal dd,
                   8461: .LC_ListStyleSpecial li,
1.795     www      8462: .LC_ListStyleSpecial dd {
1.911     bisitz   8463:   margin: 0;
                   8464:   padding: 5px 5px 5px 10px;
                   8465:   clear: both;
1.693     droeschl 8466: }
                   8467: 
1.721     harmsja  8468: .LC_ListStyleClean li,
                   8469: .LC_ListStyleClean dd {
1.911     bisitz   8470:   padding-top: 0;
                   8471:   padding-bottom: 0;
1.693     droeschl 8472: }
                   8473: 
1.721     harmsja  8474: .LC_ListStyleSimple dd,
1.795     www      8475: .LC_ListStyleSimple li {
1.911     bisitz   8476:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8477: }
                   8478: 
1.721     harmsja  8479: .LC_ListStyleSpecial li,
                   8480: .LC_ListStyleSpecial dd {
1.911     bisitz   8481:   list-style-type: none;
                   8482:   background-color: RGB(220, 220, 220);
                   8483:   margin-bottom: 4px;
1.693     droeschl 8484: }
                   8485: 
1.721     harmsja  8486: table.LC_SimpleTable {
1.911     bisitz   8487:   margin:5px;
                   8488:   border:solid 1px $lg_border_color;
1.795     www      8489: }
1.693     droeschl 8490: 
1.721     harmsja  8491: table.LC_SimpleTable tr {
1.911     bisitz   8492:   padding: 0;
                   8493:   border:solid 1px $lg_border_color;
1.693     droeschl 8494: }
1.795     www      8495: 
                   8496: table.LC_SimpleTable thead {
1.911     bisitz   8497:   background:rgb(220,220,220);
1.693     droeschl 8498: }
                   8499: 
1.721     harmsja  8500: div.LC_columnSection {
1.911     bisitz   8501:   display: block;
                   8502:   clear: both;
                   8503:   overflow: hidden;
                   8504:   margin: 0;
1.693     droeschl 8505: }
                   8506: 
1.721     harmsja  8507: div.LC_columnSection>* {
1.911     bisitz   8508:   float: left;
                   8509:   margin: 10px 20px 10px 0;
                   8510:   overflow:hidden;
1.693     droeschl 8511: }
1.721     harmsja  8512: 
1.795     www      8513: table em {
1.911     bisitz   8514:   font-weight: bold;
                   8515:   font-style: normal;
1.748     schulted 8516: }
1.795     www      8517: 
1.779     bisitz   8518: table.LC_tableBrowseRes,
1.795     www      8519: table.LC_tableOfContent {
1.911     bisitz   8520:   border:none;
                   8521:   border-spacing: 1px;
                   8522:   padding: 3px;
                   8523:   background-color: #FFFFFF;
                   8524:   font-size: 90%;
1.753     droeschl 8525: }
1.789     droeschl 8526: 
1.911     bisitz   8527: table.LC_tableOfContent {
                   8528:   border-collapse: collapse;
1.789     droeschl 8529: }
                   8530: 
1.771     droeschl 8531: table.LC_tableBrowseRes a,
1.768     schulted 8532: table.LC_tableOfContent a {
1.911     bisitz   8533:   background-color: transparent;
                   8534:   text-decoration: none;
1.753     droeschl 8535: }
                   8536: 
1.795     www      8537: table.LC_tableOfContent img {
1.911     bisitz   8538:   border: none;
                   8539:   height: 1.3em;
                   8540:   vertical-align: text-bottom;
                   8541:   margin-right: 0.3em;
1.753     droeschl 8542: }
1.757     schulted 8543: 
1.795     www      8544: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8545:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8546: }
                   8547: 
1.795     www      8548: a#LC_content_toolbar_everything {
1.911     bisitz   8549:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8550: }
                   8551: 
1.795     www      8552: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8553:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8554: }
                   8555: 
1.795     www      8556: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8557:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8558: }
                   8559: 
1.795     www      8560: a#LC_content_toolbar_changefolder {
1.911     bisitz   8561:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8562: }
                   8563: 
1.795     www      8564: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8565:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8566: }
                   8567: 
1.1043    raeburn  8568: a#LC_content_toolbar_edittoplevel {
                   8569:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8570: }
                   8571: 
1.1384    raeburn  8572: a#LC_content_toolbar_printout {
                   8573:   background-image:url(/res/adm/pages/printout.gif);
                   8574: }
                   8575: 
1.795     www      8576: ul#LC_toolbar li a:hover {
1.911     bisitz   8577:   background-position: bottom center;
1.757     schulted 8578: }
                   8579: 
1.795     www      8580: ul#LC_toolbar {
1.911     bisitz   8581:   padding: 0;
                   8582:   margin: 2px;
                   8583:   list-style:none;
                   8584:   position:relative;
                   8585:   background-color:white;
1.1082    raeburn  8586:   overflow: auto;
1.757     schulted 8587: }
                   8588: 
1.795     www      8589: ul#LC_toolbar li {
1.911     bisitz   8590:   border:1px solid white;
                   8591:   padding: 0;
                   8592:   margin: 0;
                   8593:   float: left;
                   8594:   display:inline;
                   8595:   vertical-align:middle;
1.1082    raeburn  8596:   white-space: nowrap;
1.911     bisitz   8597: }
1.757     schulted 8598: 
1.783     amueller 8599: 
1.795     www      8600: a.LC_toolbarItem {
1.911     bisitz   8601:   display:block;
                   8602:   padding: 0;
                   8603:   margin: 0;
                   8604:   height: 32px;
                   8605:   width: 32px;
                   8606:   color:white;
                   8607:   border: none;
                   8608:   background-repeat:no-repeat;
                   8609:   background-color:transparent;
1.757     schulted 8610: }
                   8611: 
1.915     droeschl 8612: ul.LC_funclist {
                   8613:     margin: 0;
                   8614:     padding: 0.5em 1em 0.5em 0;
                   8615: }
                   8616: 
1.933     droeschl 8617: ul.LC_funclist > li:first-child {
                   8618:     font-weight:bold; 
                   8619:     margin-left:0.8em;
                   8620: }
                   8621: 
1.915     droeschl 8622: ul.LC_funclist + ul.LC_funclist {
                   8623:     /* 
                   8624:        left border as a seperator if we have more than
                   8625:        one list 
                   8626:     */
                   8627:     border-left: 1px solid $sidebg;
                   8628:     /* 
                   8629:        this hides the left border behind the border of the 
                   8630:        outer box if element is wrapped to the next 'line' 
                   8631:     */
                   8632:     margin-left: -1px;
                   8633: }
                   8634: 
1.843     bisitz   8635: ul.LC_funclist li {
1.915     droeschl 8636:   display: inline;
1.782     bisitz   8637:   white-space: nowrap;
1.915     droeschl 8638:   margin: 0 0 0 25px;
                   8639:   line-height: 150%;
1.782     bisitz   8640: }
                   8641: 
1.974     wenzelju 8642: .LC_hidden {
                   8643:   display: none;
                   8644: }
                   8645: 
1.1030    www      8646: .LCmodal-overlay {
                   8647: 		position:fixed;
                   8648: 		top:0;
                   8649: 		right:0;
                   8650: 		bottom:0;
                   8651: 		left:0;
                   8652: 		height:100%;
                   8653: 		width:100%;
                   8654: 		margin:0;
                   8655: 		padding:0;
                   8656: 		background:#999;
                   8657: 		opacity:.75;
                   8658: 		filter: alpha(opacity=75);
                   8659: 		-moz-opacity: 0.75;
                   8660: 		z-index:101;
                   8661: }
                   8662: 
                   8663: * html .LCmodal-overlay {   
                   8664: 		position: absolute;
                   8665: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8666: }
                   8667: 
                   8668: .LCmodal-window {
                   8669: 		position:fixed;
                   8670: 		top:50%;
                   8671: 		left:50%;
                   8672: 		margin:0;
                   8673: 		padding:0;
                   8674: 		z-index:102;
                   8675: 	}
                   8676: 
                   8677: * html .LCmodal-window {
                   8678: 		position:absolute;
                   8679: }
                   8680: 
                   8681: .LCclose-window {
                   8682: 		position:absolute;
                   8683: 		width:32px;
                   8684: 		height:32px;
                   8685: 		right:8px;
                   8686: 		top:8px;
                   8687: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8688: 		text-indent:-99999px;
                   8689: 		overflow:hidden;
                   8690: 		cursor:pointer;
                   8691: }
                   8692: 
1.1369    raeburn  8693: .LCisDisabled {
                   8694:   cursor: not-allowed;
                   8695:   opacity: 0.5;
                   8696: }
                   8697: 
                   8698: a[aria-disabled="true"] {
                   8699:   color: currentColor;
                   8700:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8701:   pointer-events: none;
                   8702:   text-decoration: none;
                   8703: }
                   8704: 
1.1335    raeburn  8705: pre.LC_wordwrap {
                   8706:   white-space: pre-wrap;
                   8707:   white-space: -moz-pre-wrap;
                   8708:   white-space: -pre-wrap;
                   8709:   white-space: -o-pre-wrap;
                   8710:   word-wrap: break-word;
                   8711: }
                   8712: 
1.1100    raeburn  8713: /*
1.1231    damieng  8714:   styles used for response display
                   8715: */
                   8716: div.LC_radiofoil, div.LC_rankfoil {
                   8717:   margin: .5em 0em .5em 0em;
                   8718: }
                   8719: table.LC_itemgroup {
                   8720:   margin-top: 1em;
                   8721: }
                   8722: 
                   8723: /*
1.1100    raeburn  8724:   styles used by TTH when "Default set of options to pass to tth/m
                   8725:   when converting TeX" in course settings has been set
                   8726: 
                   8727:   option passed: -t
                   8728: 
                   8729: */
                   8730: 
                   8731: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8732: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8733: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8734: td div.norm {line-height:normal;}
                   8735: 
                   8736: /*
                   8737:   option passed -y3
                   8738: */
                   8739: 
                   8740: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8741: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8742: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8743: 
1.1230    damieng  8744: /*
                   8745:   sections with roles, for content only
                   8746: */
                   8747: section[class^="role-"] {
                   8748:   padding-left: 10px;
                   8749:   padding-right: 5px;
                   8750:   margin-top: 8px;
                   8751:   margin-bottom: 8px;
                   8752:   border: 1px solid #2A4;
                   8753:   border-radius: 5px;
                   8754:   box-shadow: 0px 1px 1px #BBB;
                   8755: }
                   8756: section[class^="role-"]>h1 {
                   8757:   position: relative;
                   8758:   margin: 0px;
                   8759:   padding-top: 10px;
                   8760:   padding-left: 40px;
                   8761: }
                   8762: section[class^="role-"]>h1:before {
                   8763:   position: absolute;
                   8764:   left: -5px;
                   8765:   top: 5px;
                   8766: }
                   8767: section.role-activity>h1:before {
                   8768:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8769: }
                   8770: section.role-advice>h1:before {
                   8771:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8772: }
                   8773: section.role-bibliography>h1:before {
                   8774:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8775: }
                   8776: section.role-citation>h1:before {
                   8777:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8778: }
                   8779: section.role-conclusion>h1:before {
                   8780:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8781: }
                   8782: section.role-definition>h1:before {
                   8783:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8784: }
                   8785: section.role-demonstration>h1:before {
                   8786:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8787: }
                   8788: section.role-example>h1:before {
                   8789:   content:url('/adm/daxe/images/section_icons/example.png');
                   8790: }
                   8791: section.role-explanation>h1:before {
                   8792:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8793: }
                   8794: section.role-introduction>h1:before {
                   8795:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8796: }
                   8797: section.role-method>h1:before {
                   8798:   content:url('/adm/daxe/images/section_icons/method.png');
                   8799: }
                   8800: section.role-more_information>h1:before {
                   8801:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8802: }
                   8803: section.role-objectives>h1:before {
                   8804:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8805: }
                   8806: section.role-prerequisites>h1:before {
                   8807:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8808: }
                   8809: section.role-remark>h1:before {
                   8810:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8811: }
                   8812: section.role-reminder>h1:before {
                   8813:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8814: }
                   8815: section.role-summary>h1:before {
                   8816:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8817: }
                   8818: section.role-syntax>h1:before {
                   8819:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8820: }
                   8821: section.role-warning>h1:before {
                   8822:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8823: }
                   8824: 
1.1269    raeburn  8825: #LC_minitab_header {
                   8826:   float:left;
                   8827:   width:100%;
                   8828:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8829:   font-size:93%;
                   8830:   line-height:normal;
                   8831:   margin: 0.5em 0 0.5em 0;
                   8832: }
                   8833: #LC_minitab_header ul {
                   8834:   margin:0;
                   8835:   padding:10px 10px 0;
                   8836:   list-style:none;
                   8837: }
                   8838: #LC_minitab_header li {
                   8839:   float:left;
                   8840:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8841:   margin:0;
                   8842:   padding:0 0 0 9px;
                   8843: }
                   8844: #LC_minitab_header a {
                   8845:   display:block;
                   8846:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8847:   padding:5px 15px 4px 6px;
                   8848: }
                   8849: #LC_minitab_header #LC_current_minitab {
                   8850:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8851: }
                   8852: #LC_minitab_header #LC_current_minitab a {
                   8853:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8854:   padding-bottom:5px;
                   8855: }
                   8856: 
                   8857: 
1.343     albertel 8858: END
                   8859: }
                   8860: 
1.306     albertel 8861: =pod
                   8862: 
                   8863: =item * &headtag()
                   8864: 
                   8865: Returns a uniform footer for LON-CAPA web pages.
                   8866: 
1.307     albertel 8867: Inputs: $title - optional title for the head
                   8868:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8869:         $args - optional arguments
1.319     albertel 8870:             force_register - if is true call registerurl so the remote is 
                   8871:                              informed
1.415     albertel 8872:             redirect       -> array ref of
                   8873:                                    1- seconds before redirect occurs
                   8874:                                    2- url to redirect to
                   8875:                                    3- whether the side effect should occur
1.315     albertel 8876:                            (side effect of setting 
                   8877:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  8878:                                redirected to)
                   8879:                                    4- whether the redirect target should be
                   8880:                                       the opener of the current (pop-up)
                   8881:                                       window (side effect of setting
                   8882:                                       $env{'internal.head.to_opener'} to
                   8883:                                       1, if true.
1.352     albertel 8884:             domain         -> force to color decorate a page for a specific
                   8885:                                domain
                   8886:             function       -> force usage of a specific rolish color scheme
                   8887:             bgcolor        -> override the default page bgcolor
1.460     albertel 8888:             no_auto_mt_title
                   8889:                            -> prevent &mt()ing the title arg
1.464     albertel 8890: 
1.306     albertel 8891: =cut
                   8892: 
                   8893: sub headtag {
1.313     albertel 8894:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8895:     
1.363     albertel 8896:     my $function = $args->{'function'} || &get_users_function();
                   8897:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8898:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8899:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8900:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8901: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8902: 		   #time(),
1.418     albertel 8903: 		   $env{'environment.color.timestamp'},
1.363     albertel 8904: 		   $function,$domain,$bgcolor);
                   8905: 
1.369     www      8906:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8907: 
1.308     albertel 8908:     my $result =
                   8909: 	'<head>'.
1.1160    raeburn  8910: 	&font_settings($args);
1.319     albertel 8911: 
1.1188    raeburn  8912:     my $inhibitprint;
                   8913:     if ($args->{'print_suppress'}) {
                   8914:         $inhibitprint = &print_suppression();
                   8915:     }
1.1064    raeburn  8916: 
1.461     albertel 8917:     if (!$args->{'frameset'}) {
                   8918: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8919:     }
1.962     droeschl 8920:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8921:         $result .= Apache::lonxml::display_title();
1.319     albertel 8922:     }
1.436     albertel 8923:     if (!$args->{'no_nav_bar'} 
                   8924: 	&& !$args->{'only_body'}
                   8925: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8926: 	$result .= &help_menu_js($httphost);
1.1032    www      8927:         $result.=&modal_window();
1.1038    www      8928:         $result.=&togglebox_script();
1.1034    www      8929:         $result.=&wishlist_window();
1.1041    www      8930:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8931:     } else {
                   8932:         if ($args->{'add_modal'}) {
                   8933:            $result.=&modal_window();
                   8934:         }
                   8935:         if ($args->{'add_wishlist'}) {
                   8936:            $result.=&wishlist_window();
                   8937:         }
1.1038    www      8938:         if ($args->{'add_togglebox'}) {
                   8939:            $result.=&togglebox_script();
                   8940:         }
1.1041    www      8941:         if ($args->{'add_progressbar'}) {
                   8942:            $result.=&LCprogressbarUpdate_script();
                   8943:         }
1.436     albertel 8944:     }
1.314     albertel 8945:     if (ref($args->{'redirect'})) {
1.1386    raeburn  8946: 	my ($time,$url,$inhibit_continue,$to_opener) = @{$args->{'redirect'}};
1.315     albertel 8947: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8948: 	if (!$inhibit_continue) {
                   8949: 	    $env{'internal.head.redirect'} = $url;
                   8950: 	}
1.1386    raeburn  8951: 	$result.=<<"ADDMETA";
1.313     albertel 8952: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  8953: ADDMETA
                   8954:         if ($to_opener) {
                   8955:             $env{'internal.head.to_opener'} = 1;
                   8956:             my $dest = &js_escape($url);
                   8957:             my $timeout = int($time * 1000);
                   8958:             $result .=<<"ENDJS";
                   8959: <script type="text/javascript">
                   8960: // <![CDATA[
                   8961: function LC_To_Opener() {
                   8962:     var dest = '$dest';
                   8963:     if (dest != '') {
                   8964:         if (window.opener != null && !window.opener.closed) {
                   8965:             window.opener.location.href=dest;
                   8966:             window.close();
                   8967:         } else {
                   8968:             window.location.href=dest;
                   8969:         }
                   8970:     }
                   8971: }
                   8972: \$(document).ready(function () {
                   8973:     setTimeout('LC_To_Opener()',$timeout);
                   8974: });
                   8975: // ]]>
                   8976: </script>
                   8977: ENDJS
                   8978:         } else {
                   8979:             $result.=<<"ADDMETA";
1.344     albertel 8980: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8981: ADDMETA
1.1386    raeburn  8982:         }
1.1210    raeburn  8983:     } else {
                   8984:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8985:             my $requrl = $env{'request.uri'};
                   8986:             if ($requrl eq '') {
                   8987:                 $requrl = $ENV{'REQUEST_URI'};
                   8988:                 $requrl =~ s/\?.+$//;
                   8989:             }
                   8990:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8991:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8992:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8993:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8994:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8995:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8996:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8997:                     my ($offload,$offloadoth);
1.1210    raeburn  8998:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8999:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9000:                             $offload = 1;
1.1353    raeburn  9001:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9002:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9003:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9004:                                     $offloadoth = 1;
                   9005:                                     $dom_in_use = $env{'user.domain'};
                   9006:                                 }
                   9007:                             }
1.1340    raeburn  9008:                         }
                   9009:                     }
                   9010:                     unless ($offload) {
                   9011:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9012:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9013:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9014:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9015:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9016:                                         $offload = 1;
1.1352    raeburn  9017:                                         $offloadoth = 1;
1.1340    raeburn  9018:                                         $dom_in_use = $env{'user.domain'};
                   9019:                                     }
1.1210    raeburn  9020:                                 }
1.1340    raeburn  9021:                             }
                   9022:                         }
                   9023:                     }
                   9024:                     if ($offload) {
1.1358    raeburn  9025:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9026:                         if (($newserver eq '') && ($offloadoth)) {
                   9027:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9028:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9029:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9030:                             }
                   9031:                         }
1.1340    raeburn  9032:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9033:                             my $numsec = 5;
                   9034:                             my $timeout = $numsec * 1000;
                   9035:                             my ($newurl,$locknum,%locks,$msg);
                   9036:                             if ($env{'request.role.adv'}) {
                   9037:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9038:                             }
                   9039:                             my $disable_submit = 0;
                   9040:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9041:                                 $disable_submit = 1;
                   9042:                             }
                   9043:                             if ($locknum) {
                   9044:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9045:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9046:                                        join(", ",sort(values(%locks)))."\n";
                   9047:                                 if (&show_course()) {
                   9048:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9049:                                 } else {
                   9050:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9051:                                 }
1.1340    raeburn  9052:                             } else {
                   9053:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9054:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9055:                                 }
                   9056:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9057:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9058:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9059:                                     $newurl .= '&role='.$env{'request.role'};
                   9060:                                 }
                   9061:                                 if ($env{'request.symb'}) {
                   9062:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9063:                                     if ($shownsymb =~ m{^/enc/}) {
                   9064:                                         my $reqdmajor = 2;
                   9065:                                         my $reqdminor = 11;
                   9066:                                         my $reqdsubminor = 3;
                   9067:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9068:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9069:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9070:                                         if (($major eq '' && $minor eq '') ||
                   9071:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9072:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9073:                                              ($reqdsubminor > $subminor))))) {
                   9074:                                             undef($shownsymb);
                   9075:                                         }
1.1210    raeburn  9076:                                     }
1.1340    raeburn  9077:                                     if ($shownsymb) {
                   9078:                                         &js_escape(\$shownsymb);
                   9079:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9080:                                     }
1.1340    raeburn  9081:                                 } else {
                   9082:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9083:                                     &js_escape(\$shownurl);
                   9084:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9085:                                 }
1.1340    raeburn  9086:                             }
                   9087:                             &js_escape(\$msg);
                   9088:                             $result.=<<OFFLOAD
1.1210    raeburn  9089: <meta http-equiv="pragma" content="no-cache" />
                   9090: <script type="text/javascript">
1.1215    raeburn  9091: // <![CDATA[
1.1210    raeburn  9092: function LC_Offload_Now() {
                   9093:     var dest = "$newurl";
                   9094:     if (dest != '') {
                   9095:         window.location.href="$newurl";
                   9096:     }
                   9097: }
1.1214    raeburn  9098: \$(document).ready(function () {
                   9099:     window.alert('$msg');
                   9100:     if ($disable_submit) {
1.1210    raeburn  9101:         \$(".LC_hwk_submit").prop("disabled", true);
                   9102:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9103:     }
                   9104:     setTimeout('LC_Offload_Now()', $timeout);
                   9105: });
1.1215    raeburn  9106: // ]]>
1.1210    raeburn  9107: </script>
                   9108: OFFLOAD
                   9109:                         }
                   9110:                     }
                   9111:                 }
                   9112:             }
                   9113:         }
1.313     albertel 9114:     }
1.306     albertel 9115:     if (!defined($title)) {
                   9116: 	$title = 'The LearningOnline Network with CAPA';
                   9117:     }
1.460     albertel 9118:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9119:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9120: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9121:     if (!$args->{'frameset'}) {
                   9122:         $result .= ' /';
                   9123:     }
                   9124:     $result .= '>' 
1.1064    raeburn  9125:         .$inhibitprint
1.414     albertel 9126: 	.$head_extra;
1.1242    raeburn  9127:     my $clientmobile;
                   9128:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9129:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9130:     } else {
                   9131:         $clientmobile = $env{'browser.mobile'};
                   9132:     }
                   9133:     if ($clientmobile) {
1.1137    raeburn  9134:         $result .= '
                   9135: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9136: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9137:     }
1.1278    raeburn  9138:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9139:     return $result.'</head>';
1.306     albertel 9140: }
                   9141: 
                   9142: =pod
                   9143: 
1.340     albertel 9144: =item * &font_settings()
                   9145: 
                   9146: Returns neccessary <meta> to set the proper encoding
                   9147: 
1.1160    raeburn  9148: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9149: 
                   9150: =cut
                   9151: 
                   9152: sub font_settings {
1.1160    raeburn  9153:     my ($args) = @_;
1.340     albertel 9154:     my $headerstring='';
1.1160    raeburn  9155:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9156:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9157:         $headerstring.=
                   9158:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9159:         if (!$args->{'frameset'}) {
                   9160: 	    $headerstring.= ' /';
                   9161:         }
                   9162: 	$headerstring .= '>'."\n";
1.340     albertel 9163:     }
                   9164:     return $headerstring;
                   9165: }
                   9166: 
1.341     albertel 9167: =pod
                   9168: 
1.1064    raeburn  9169: =item * &print_suppression()
                   9170: 
                   9171: In course context returns css which causes the body to be blank when media="print",
                   9172: if printout generation is unavailable for the current resource.
                   9173: 
                   9174: This could be because:
                   9175: 
                   9176: (a) printstartdate is in the future
                   9177: 
                   9178: (b) printenddate is in the past
                   9179: 
                   9180: (c) there is an active exam block with "printout"
                   9181: functionality blocked
                   9182: 
                   9183: Users with pav, pfo or evb privileges are exempt.
                   9184: 
                   9185: Inputs: none
                   9186: 
                   9187: =cut
                   9188: 
                   9189: 
                   9190: sub print_suppression {
                   9191:     my $noprint;
                   9192:     if ($env{'request.course.id'}) {
                   9193:         my $scope = $env{'request.course.id'};
                   9194:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9195:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9196:             return;
                   9197:         }
                   9198:         if ($env{'request.course.sec'} ne '') {
                   9199:             $scope .= "/$env{'request.course.sec'}";
                   9200:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9201:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9202:                 return;
1.1064    raeburn  9203:             }
                   9204:         }
                   9205:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9206:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9207:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9208:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9209:         if ($blocked) {
                   9210:             my $checkrole = "cm./$cdom/$cnum";
                   9211:             if ($env{'request.course.sec'} ne '') {
                   9212:                 $checkrole .= "/$env{'request.course.sec'}";
                   9213:             }
                   9214:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9215:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9216:                 $noprint = 1;
                   9217:             }
                   9218:         }
                   9219:         unless ($noprint) {
                   9220:             my $symb = &Apache::lonnet::symbread();
                   9221:             if ($symb ne '') {
                   9222:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9223:                 if (ref($navmap)) {
                   9224:                     my $res = $navmap->getBySymb($symb);
                   9225:                     if (ref($res)) {
                   9226:                         if (!$res->resprintable()) {
                   9227:                             $noprint = 1;
                   9228:                         }
                   9229:                     }
                   9230:                 }
                   9231:             }
                   9232:         }
                   9233:         if ($noprint) {
                   9234:             return <<"ENDSTYLE";
                   9235: <style type="text/css" media="print">
                   9236:     body { display:none }
                   9237: </style>
                   9238: ENDSTYLE
                   9239:         }
                   9240:     }
                   9241:     return;
                   9242: }
                   9243: 
                   9244: =pod
                   9245: 
1.341     albertel 9246: =item * &xml_begin()
                   9247: 
                   9248: Returns the needed doctype and <html>
                   9249: 
                   9250: Inputs: none
                   9251: 
                   9252: =cut
                   9253: 
                   9254: sub xml_begin {
1.1168    raeburn  9255:     my ($is_frameset) = @_;
1.341     albertel 9256:     my $output='';
                   9257: 
                   9258:     if ($env{'browser.mathml'}) {
                   9259: 	$output='<?xml version="1.0"?>'
                   9260:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9261: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9262:             
                   9263: #	    .'<!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">] >'
                   9264: 	    .'<!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">'
                   9265:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9266: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9267:     } elsif ($is_frameset) {
                   9268:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9269:                 '<html>'."\n";
1.341     albertel 9270:     } else {
1.1168    raeburn  9271: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9272:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9273:     }
                   9274:     return $output;
                   9275: }
1.340     albertel 9276: 
                   9277: =pod
                   9278: 
1.306     albertel 9279: =item * &start_page()
                   9280: 
                   9281: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9282: 
1.648     raeburn  9283: Inputs:
                   9284: 
                   9285: =over 4
                   9286: 
                   9287: $title - optional title for the page
                   9288: 
                   9289: $head_extra - optional extra HTML to incude inside the <head>
                   9290: 
                   9291: $args - additional optional args supported are:
                   9292: 
                   9293: =over 8
                   9294: 
                   9295:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9296:                                     arg on
1.814     bisitz   9297:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9298:              add_entries    -> additional attributes to add to the  <body>
                   9299:              domain         -> force to color decorate a page for a 
1.317     albertel 9300:                                     specific domain
1.648     raeburn  9301:              function       -> force usage of a specific rolish color
1.317     albertel 9302:                                     scheme
1.648     raeburn  9303:              redirect       -> see &headtag()
                   9304:              bgcolor        -> override the default page bg color
                   9305:              js_ready       -> return a string ready for being used in 
1.317     albertel 9306:                                     a javascript writeln
1.648     raeburn  9307:              html_encode    -> return a string ready for being used in 
1.320     albertel 9308:                                     a html attribute
1.648     raeburn  9309:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9310:                                     $forcereg arg
1.648     raeburn  9311:              frameset       -> if true will start with a <frameset>
1.330     albertel 9312:                                     rather than <body>
1.648     raeburn  9313:              skip_phases    -> hash ref of 
1.338     albertel 9314:                                     head -> skip the <html><head> generation
                   9315:                                     body -> skip all <body> generation
1.648     raeburn  9316:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9317:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9318:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9319:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9320:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9321:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9322:                                specific group
                   9323:              use_absolute   -> for request for external resource or syllabus, this
                   9324:                                will contain https://<hostname> if server uses
                   9325:                                https (as per hosts.tab), but request is for http
                   9326:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9327:              links_disabled -> Links in primary and secondary menus are disabled
                   9328:                                (Can enable them once page has loaded - see lonroles.pm
                   9329:                                for an example).
1.1380    raeburn  9330:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9331: 
1.648     raeburn  9332: =back
1.460     albertel 9333: 
1.648     raeburn  9334: =back
1.562     albertel 9335: 
1.306     albertel 9336: =cut
                   9337: 
                   9338: sub start_page {
1.309     albertel 9339:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9340:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9341: 
1.315     albertel 9342:     $env{'internal.start_page'}++;
1.1359    raeburn  9343:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9344: 
1.338     albertel 9345:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9346:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9347:     }
1.1316    raeburn  9348: 
                   9349:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9350:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9351:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9352:                 $args->{'no_primary_menu'} = 1;
                   9353:             }
                   9354:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9355:                 $args->{'no_inline_menu'} = 1;
                   9356:             }
                   9357:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9358:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9359:             }
                   9360:         } else {
                   9361:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9362:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9363:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9364:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9365:                     $args->{'no_primary_menu'} = 1;
                   9366:                 }
                   9367:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9368:                     $args->{'no_inline_menu'} = 1;
                   9369:                 }
                   9370:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9371:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9372:                 }
                   9373:             }
                   9374:         }
1.1316    raeburn  9375:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9376:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9377:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9378:     } elsif ($env{'request.course.id'}) {
                   9379:         my $expiretime=600;
                   9380:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9381:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9382:         }
                   9383:         my ($deeplinkmenu,$menuref);
                   9384:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9385:         if ($menucoll) {
                   9386:             if (ref($menuref) eq 'HASH') {
                   9387:                 %menu = %{$menuref};
                   9388:             }
                   9389:             if ($menu{'top'} eq 'n') {
                   9390:                 $args->{'no_primary_menu'} = 1;
                   9391:             }
                   9392:             if ($menu{'inline'} eq 'n') {
                   9393:                 unless (&Apache::lonnet::allowed('opa')) {
                   9394:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9395:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9396:                     my $crstype = &course_type();
                   9397:                     my $now = time;
                   9398:                     my $ccrole;
                   9399:                     if ($crstype eq 'Community') {
                   9400:                         $ccrole = 'co';
                   9401:                     } else {
                   9402:                         $ccrole = 'cc';
                   9403:                     }
                   9404:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9405:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9406:                         if ((($start) && ($start<0)) ||
                   9407:                             (($end) && ($end<$now))  ||
                   9408:                             (($start) && ($now<$start))) {
                   9409:                             $args->{'no_inline_menu'} = 1;
                   9410:                         }
                   9411:                     } else {
                   9412:                         $args->{'no_inline_menu'} = 1;
                   9413:                     }
                   9414:                 }
                   9415:             }
                   9416:         }
1.1316    raeburn  9417:     }
1.1359    raeburn  9418: 
1.1385    raeburn  9419:     my $showncrumbs;
1.338     albertel 9420:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9421: 	if ($args->{'frameset'}) {
                   9422: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9423: 						$args->{'add_entries'});
                   9424: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9425:         } else {
                   9426:             $result .=
                   9427:                 &bodytag($title, 
                   9428:                          $args->{'function'},       $args->{'add_entries'},
                   9429:                          $args->{'only_body'},      $args->{'domain'},
                   9430:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9431:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9432:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9433:                          \%menu,\$showncrumbs);
1.831     bisitz   9434:         }
1.330     albertel 9435:     }
1.338     albertel 9436: 
1.315     albertel 9437:     if ($args->{'js_ready'}) {
1.713     kaisler  9438: 		$result = &js_ready($result);
1.315     albertel 9439:     }
1.320     albertel 9440:     if ($args->{'html_encode'}) {
1.713     kaisler  9441: 		$result = &html_encode($result);
                   9442:     }
                   9443: 
1.813     bisitz   9444:     # Preparation for new and consistent functionlist at top of screen
                   9445:     # if ($args->{'functionlist'}) {
                   9446:     #            $result .= &build_functionlist();
                   9447:     #}
                   9448: 
1.964     droeschl 9449:     # Don't add anything more if only_body wanted or in const space
                   9450:     return $result if    $args->{'only_body'} 
                   9451:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9452: 
                   9453:     #Breadcrumbs
1.758     kaisler  9454:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9455:         unless ($showncrumbs) {
1.758     kaisler  9456: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9457: 		#if any br links exists, add them to the breadcrumbs
                   9458: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9459: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9460: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9461: 			}
                   9462: 		}
1.1096    raeburn  9463:                 # if @advtools array contains items add then to the breadcrumbs
                   9464:                 if (@advtools > 0) {
                   9465:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9466:                 }
1.1272    raeburn  9467:                 my $menulink;
                   9468:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9469:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9470:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9471:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9472:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9473:                      (!$env{'request.role.adv'}))) {
                   9474:                     $menulink = 0;
                   9475:                 } else {
                   9476:                     undef($menulink);
                   9477:                 }
1.1385    raeburn  9478:                 my $linkprotout;
                   9479:                 if ($env{'request.deeplink.login'}) {
                   9480:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9481:                     if ($linkprotout) {
                   9482:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9483:                     }
                   9484:                 }
1.758     kaisler  9485: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9486: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9487: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9488:                 } else {
1.1272    raeburn  9489: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9490: 		}
1.1385    raeburn  9491:         }
1.320     albertel 9492:     }
1.315     albertel 9493:     return $result;
1.306     albertel 9494: }
                   9495: 
                   9496: sub end_page {
1.315     albertel 9497:     my ($args) = @_;
                   9498:     $env{'internal.end_page'}++;
1.330     albertel 9499:     my $result;
1.335     albertel 9500:     if ($args->{'discussion'}) {
                   9501: 	my ($target,$parser);
                   9502: 	if (ref($args->{'discussion'})) {
                   9503: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9504: 				$args->{'discussion'}{'parser'});
                   9505: 	}
                   9506: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9507:     }
1.330     albertel 9508:     if ($args->{'frameset'}) {
                   9509: 	$result .= '</frameset>';
                   9510:     } else {
1.635     raeburn  9511: 	$result .= &endbodytag($args);
1.330     albertel 9512:     }
1.1080    raeburn  9513:     unless ($args->{'notbody'}) {
                   9514:         $result .= "\n</html>";
                   9515:     }
1.330     albertel 9516: 
1.315     albertel 9517:     if ($args->{'js_ready'}) {
1.317     albertel 9518: 	$result = &js_ready($result);
1.315     albertel 9519:     }
1.335     albertel 9520: 
1.320     albertel 9521:     if ($args->{'html_encode'}) {
                   9522: 	$result = &html_encode($result);
                   9523:     }
1.335     albertel 9524: 
1.315     albertel 9525:     return $result;
                   9526: }
                   9527: 
1.1359    raeburn  9528: sub menucoll_in_effect {
                   9529:     my ($menucoll,$deeplinkmenu,%menu);
                   9530:     if ($env{'request.course.id'}) {
                   9531:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9532:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9533:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9534:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9535:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9536:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9537:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9538:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9539:                     if (ref($navmap)) {
                   9540:                         $deeplink = $navmap->get_mapparam(undef,
                   9541:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9542:                                                           '0.deeplink');
1.1370    raeburn  9543:                     } else {
                   9544:                         $check_login_symb = 1;
1.1362    raeburn  9545:                     }
                   9546:                 } else {
1.1370    raeburn  9547:                     my $symb = &Apache::lonnet::symbread();
                   9548:                     if ($symb) {
                   9549:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9550:                     } else {
                   9551:                         $check_login_symb = 1;
                   9552:                     }
1.1362    raeburn  9553:                 }
                   9554:             } else {
1.1370    raeburn  9555:                 $check_login_symb = 1;
                   9556:             }
                   9557:             if ($check_login_symb) {
1.1362    raeburn  9558:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9559:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9560:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9561:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9562:                     if (ref($navmap)) {
                   9563:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9564:                     }
                   9565:                 } else {
                   9566:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9567:                 }
                   9568:             }
1.1359    raeburn  9569:             if ($deeplink ne '') {
1.1378    raeburn  9570:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9571:                 if ($display =~ /^\d+$/) {
                   9572:                     $deeplinkmenu = 1;
                   9573:                     $menucoll = $display;
                   9574:                 }
                   9575:             }
                   9576:         }
                   9577:         if ($menucoll) {
                   9578:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9579:         }
                   9580:     }
                   9581:     return ($menucoll,$deeplinkmenu,\%menu);
                   9582: }
                   9583: 
1.1362    raeburn  9584: sub deeplink_login_symb {
                   9585:     my ($cnum,$cdom) = @_;
                   9586:     my $login_symb;
                   9587:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9588:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9589:     }
                   9590:     return $login_symb;
                   9591: }
                   9592: 
                   9593: sub symb_from_tinyurl {
                   9594:     my ($url,$cnum,$cdom) = @_;
                   9595:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9596:         my $key = $1;
                   9597:         my ($tinyurl,$login);
                   9598:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9599:         if (defined($cached)) {
                   9600:             $tinyurl = $result;
                   9601:         } else {
                   9602:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9603:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9604:             if ($currtiny{$key} ne '') {
                   9605:                 $tinyurl = $currtiny{$key};
                   9606:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9607:             }
1.1364    raeburn  9608:         }
                   9609:         if ($tinyurl ne '') {
                   9610:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9611:             if (wantarray) {
                   9612:                 return ($cnumreq,$symb);
                   9613:             } elsif ($cnumreq eq $cnum) {
                   9614:                 return $symb;
1.1362    raeburn  9615:             }
                   9616:         }
                   9617:     }
1.1364    raeburn  9618:     if (wantarray) {
                   9619:         return ();
                   9620:     } else {
                   9621:         return;
                   9622:     }
1.1362    raeburn  9623: }
                   9624: 
1.1034    www      9625: sub wishlist_window {
                   9626:     return(<<'ENDWISHLIST');
1.1046    raeburn  9627: <script type="text/javascript">
1.1034    www      9628: // <![CDATA[
                   9629: // <!-- BEGIN LON-CAPA Internal
                   9630: function set_wishlistlink(title, path) {
                   9631:     if (!title) {
                   9632:         title = document.title;
                   9633:         title = title.replace(/^LON-CAPA /,'');
                   9634:     }
1.1175    raeburn  9635:     title = encodeURIComponent(title);
1.1203    raeburn  9636:     title = title.replace("'","\\\'");
1.1034    www      9637:     if (!path) {
                   9638:         path = location.pathname;
                   9639:     }
1.1175    raeburn  9640:     path = encodeURIComponent(path);
1.1203    raeburn  9641:     path = path.replace("'","\\\'");
1.1034    www      9642:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9643:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9644: }
                   9645: // END LON-CAPA Internal -->
                   9646: // ]]>
                   9647: </script>
                   9648: ENDWISHLIST
                   9649: }
                   9650: 
1.1030    www      9651: sub modal_window {
                   9652:     return(<<'ENDMODAL');
1.1046    raeburn  9653: <script type="text/javascript">
1.1030    www      9654: // <![CDATA[
                   9655: // <!-- BEGIN LON-CAPA Internal
                   9656: var modalWindow = {
                   9657: 	parent:"body",
                   9658: 	windowId:null,
                   9659: 	content:null,
                   9660: 	width:null,
                   9661: 	height:null,
                   9662: 	close:function()
                   9663: 	{
                   9664: 	        $(".LCmodal-window").remove();
                   9665: 	        $(".LCmodal-overlay").remove();
                   9666: 	},
                   9667: 	open:function()
                   9668: 	{
                   9669: 		var modal = "";
                   9670: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9671: 		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;\">";
                   9672: 		modal += this.content;
                   9673: 		modal += "</div>";	
                   9674: 
                   9675: 		$(this.parent).append(modal);
                   9676: 
                   9677: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9678: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9679: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9680: 	}
                   9681: };
1.1140    raeburn  9682: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9683: 	{
1.1266    raeburn  9684:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9685: 		modalWindow.windowId = "myModal";
                   9686: 		modalWindow.width = width;
                   9687: 		modalWindow.height = height;
1.1196    raeburn  9688: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9689: 		modalWindow.open();
1.1208    raeburn  9690: 	};
1.1030    www      9691: // END LON-CAPA Internal -->
                   9692: // ]]>
                   9693: </script>
                   9694: ENDMODAL
                   9695: }
                   9696: 
                   9697: sub modal_link {
1.1140    raeburn  9698:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9699:     unless ($width) { $width=480; }
                   9700:     unless ($height) { $height=400; }
1.1031    www      9701:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9702:     unless ($transparency) { $transparency='true'; }
                   9703: 
1.1074    raeburn  9704:     my $target_attr;
                   9705:     if (defined($target)) {
                   9706:         $target_attr = 'target="'.$target.'"';
                   9707:     }
                   9708:     return <<"ENDLINK";
1.1336    raeburn  9709: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9710: ENDLINK
1.1030    www      9711: }
                   9712: 
1.1032    www      9713: sub modal_adhoc_script {
1.1365    raeburn  9714:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9715:     my $mathjax;
                   9716:     if ($possmathjax) {
                   9717:         $mathjax = <<'ENDJAX';
                   9718:                if (typeof MathJax == 'object') {
                   9719:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9720:                }
                   9721: ENDJAX
                   9722:     }
1.1032    www      9723:     return (<<ENDADHOC);
1.1046    raeburn  9724: <script type="text/javascript">
1.1032    www      9725: // <![CDATA[
                   9726:         var $funcname = function()
                   9727:         {
                   9728:                 modalWindow.windowId = "myModal";
                   9729:                 modalWindow.width = $width;
                   9730:                 modalWindow.height = $height;
                   9731:                 modalWindow.content = '$content';
                   9732:                 modalWindow.open();
1.1365    raeburn  9733:                 $mathjax
1.1032    www      9734:         };  
                   9735: // ]]>
                   9736: </script>
                   9737: ENDADHOC
                   9738: }
                   9739: 
1.1041    www      9740: sub modal_adhoc_inner {
1.1365    raeburn  9741:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9742:     my $innerwidth=$width-20;
                   9743:     $content=&js_ready(
1.1140    raeburn  9744:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9745:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9746:                  $content.
1.1041    www      9747:                  &end_scrollbox().
1.1140    raeburn  9748:                  &end_page()
1.1041    www      9749:              );
1.1365    raeburn  9750:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9751: }
                   9752: 
                   9753: sub modal_adhoc_window {
1.1365    raeburn  9754:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9755:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9756:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9757: }
                   9758: 
                   9759: sub modal_adhoc_launch {
                   9760:     my ($funcname,$width,$height,$content)=@_;
                   9761:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9762: <script type="text/javascript">
                   9763: // <![CDATA[
                   9764: $funcname();
                   9765: // ]]>
                   9766: </script>
                   9767: ENDLAUNCH
                   9768: }
                   9769: 
                   9770: sub modal_adhoc_close {
                   9771:     return (<<ENDCLOSE);
                   9772: <script type="text/javascript">
                   9773: // <![CDATA[
                   9774: modalWindow.close();
                   9775: // ]]>
                   9776: </script>
                   9777: ENDCLOSE
                   9778: }
                   9779: 
1.1038    www      9780: sub togglebox_script {
                   9781:    return(<<ENDTOGGLE);
                   9782: <script type="text/javascript"> 
                   9783: // <![CDATA[
                   9784: function LCtoggleDisplay(id,hidetext,showtext) {
                   9785:    link = document.getElementById(id + "link").childNodes[0];
                   9786:    with (document.getElementById(id).style) {
                   9787:       if (display == "none" ) {
                   9788:           display = "inline";
                   9789:           link.nodeValue = hidetext;
                   9790:         } else {
                   9791:           display = "none";
                   9792:           link.nodeValue = showtext;
                   9793:        }
                   9794:    }
                   9795: }
                   9796: // ]]>
                   9797: </script>
                   9798: ENDTOGGLE
                   9799: }
                   9800: 
1.1039    www      9801: sub start_togglebox {
                   9802:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9803:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9804:     unless ($showtext) { $showtext=&mt('show'); }
                   9805:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9806:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9807:     return &start_data_table().
                   9808:            &start_data_table_header_row().
                   9809:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9810:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9811:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9812:            &end_data_table_header_row().
                   9813:            '<tr id="'.$id.'" style="display:none""><td>';
                   9814: }
                   9815: 
                   9816: sub end_togglebox {
                   9817:     return '</td></tr>'.&end_data_table();
                   9818: }
                   9819: 
1.1041    www      9820: sub LCprogressbar_script {
1.1302    raeburn  9821:    my ($id,$number_to_do)=@_;
                   9822:    if ($number_to_do) {
                   9823:        return(<<ENDPROGRESS);
1.1041    www      9824: <script type="text/javascript">
                   9825: // <![CDATA[
1.1045    www      9826: \$('#progressbar$id').progressbar({
1.1041    www      9827:   value: 0,
                   9828:   change: function(event, ui) {
                   9829:     var newVal = \$(this).progressbar('option', 'value');
                   9830:     \$('.pblabel', this).text(LCprogressTxt);
                   9831:   }
                   9832: });
                   9833: // ]]>
                   9834: </script>
                   9835: ENDPROGRESS
1.1302    raeburn  9836:    } else {
                   9837:        return(<<ENDPROGRESS);
                   9838: <script type="text/javascript">
                   9839: // <![CDATA[
                   9840: \$('#progressbar$id').progressbar({
                   9841:   value: false,
                   9842:   create: function(event, ui) {
                   9843:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9844:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9845:   }
                   9846: });
                   9847: // ]]>
                   9848: </script>
                   9849: ENDPROGRESS
                   9850:    }
1.1041    www      9851: }
                   9852: 
                   9853: sub LCprogressbarUpdate_script {
                   9854:    return(<<ENDPROGRESSUPDATE);
                   9855: <style type="text/css">
                   9856: .ui-progressbar { position:relative; }
1.1302    raeburn  9857: .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      9858: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9859: </style>
                   9860: <script type="text/javascript">
                   9861: // <![CDATA[
1.1045    www      9862: var LCprogressTxt='---';
                   9863: 
1.1302    raeburn  9864: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9865:    LCprogressTxt=progresstext;
1.1302    raeburn  9866:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9867:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9868:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9869:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9870:    } else {
                   9871:        \$('#progressbar'+id).progressbar('value',percent);
                   9872:    }
1.1041    www      9873: }
                   9874: // ]]>
                   9875: </script>
                   9876: ENDPROGRESSUPDATE
                   9877: }
                   9878: 
1.1042    www      9879: my $LClastpercent;
1.1045    www      9880: my $LCidcnt;
                   9881: my $LCcurrentid;
1.1042    www      9882: 
1.1041    www      9883: sub LCprogressbar {
1.1302    raeburn  9884:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9885:     $LClastpercent=0;
1.1045    www      9886:     $LCidcnt++;
                   9887:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9888:     my ($starting,$content);
                   9889:     if ($number_to_do) {
                   9890:         $starting=&mt('Starting');
                   9891:         $content=(<<ENDPROGBAR);
                   9892: $preamble
1.1045    www      9893:   <div id="progressbar$LCcurrentid">
1.1041    www      9894:     <span class="pblabel">$starting</span>
                   9895:   </div>
                   9896: ENDPROGBAR
1.1302    raeburn  9897:     } else {
                   9898:         $starting=&mt('Loading...');
                   9899:         $LClastpercent='false';
                   9900:         $content=(<<ENDPROGBAR);
                   9901: $preamble
                   9902:   <div id="progressbar$LCcurrentid">
                   9903:       <div class="progress-label">$starting</div>
                   9904:   </div>
                   9905: ENDPROGBAR
                   9906:     }
                   9907:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9908: }
                   9909: 
                   9910: sub LCprogressbarUpdate {
1.1302    raeburn  9911:     my ($r,$val,$text,$number_to_do)=@_;
                   9912:     if ($number_to_do) {
                   9913:         unless ($val) { 
                   9914:             if ($LClastpercent) {
                   9915:                 $val=$LClastpercent;
                   9916:             } else {
                   9917:                 $val=0;
                   9918:             }
                   9919:         }
                   9920:         if ($val<0) { $val=0; }
                   9921:         if ($val>100) { $val=0; }
                   9922:         $LClastpercent=$val;
                   9923:         unless ($text) { $text=$val.'%'; }
                   9924:     } else {
                   9925:         $val = 'false';
1.1042    www      9926:     }
1.1041    www      9927:     $text=&js_ready($text);
1.1044    www      9928:     &r_print($r,<<ENDUPDATE);
1.1041    www      9929: <script type="text/javascript">
                   9930: // <![CDATA[
1.1302    raeburn  9931: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9932: // ]]>
                   9933: </script>
                   9934: ENDUPDATE
1.1035    www      9935: }
                   9936: 
1.1042    www      9937: sub LCprogressbarClose {
                   9938:     my ($r)=@_;
                   9939:     $LClastpercent=0;
1.1044    www      9940:     &r_print($r,<<ENDCLOSE);
1.1042    www      9941: <script type="text/javascript">
                   9942: // <![CDATA[
1.1045    www      9943: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9944: // ]]>
                   9945: </script>
                   9946: ENDCLOSE
1.1044    www      9947: }
                   9948: 
                   9949: sub r_print {
                   9950:     my ($r,$to_print)=@_;
                   9951:     if ($r) {
                   9952:       $r->print($to_print);
                   9953:       $r->rflush();
                   9954:     } else {
                   9955:       print($to_print);
                   9956:     }
1.1042    www      9957: }
                   9958: 
1.320     albertel 9959: sub html_encode {
                   9960:     my ($result) = @_;
                   9961: 
1.322     albertel 9962:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9963:     
                   9964:     return $result;
                   9965: }
1.1044    www      9966: 
1.317     albertel 9967: sub js_ready {
                   9968:     my ($result) = @_;
                   9969: 
1.323     albertel 9970:     $result =~ s/[\n\r]/ /xmsg;
                   9971:     $result =~ s/\\/\\\\/xmsg;
                   9972:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9973:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9974:     
                   9975:     return $result;
                   9976: }
                   9977: 
1.315     albertel 9978: sub validate_page {
                   9979:     if (  exists($env{'internal.start_page'})
1.316     albertel 9980: 	  &&     $env{'internal.start_page'} > 1) {
                   9981: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9982: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9983: 				 $ENV{'request.filename'});
1.315     albertel 9984:     }
                   9985:     if (  exists($env{'internal.end_page'})
1.316     albertel 9986: 	  &&     $env{'internal.end_page'} > 1) {
                   9987: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9988: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9989: 				 $env{'request.filename'});
1.315     albertel 9990:     }
                   9991:     if (     exists($env{'internal.start_page'})
                   9992: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9993: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9994: 				 $env{'request.filename'});
1.315     albertel 9995:     }
                   9996:     if (   ! exists($env{'internal.start_page'})
                   9997: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9998: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9999: 				 $env{'request.filename'});
1.315     albertel 10000:     }
1.306     albertel 10001: }
1.315     albertel 10002: 
1.996     www      10003: 
                   10004: sub start_scrollbox {
1.1140    raeburn  10005:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10006:     unless ($outerwidth) { $outerwidth='520px'; }
                   10007:     unless ($width) { $width='500px'; }
                   10008:     unless ($height) { $height='200px'; }
1.1075    raeburn  10009:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10010:     if ($id ne '') {
1.1140    raeburn  10011:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10012:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10013:     }
1.1075    raeburn  10014:     if ($bgcolor ne '') {
                   10015:         $tdcol = "background-color: $bgcolor;";
                   10016:     }
1.1137    raeburn  10017:     my $nicescroll_js;
                   10018:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10019:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10020:     }
                   10021:     return <<"END";
                   10022: $nicescroll_js
                   10023: 
                   10024: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10025: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10026: END
                   10027: }
                   10028: 
                   10029: sub end_scrollbox {
                   10030:     return '</div></td></tr></table>';
                   10031: }
                   10032: 
                   10033: sub nicescroll_javascript {
                   10034:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10035:     my %options;
                   10036:     if (ref($cursor) eq 'HASH') {
                   10037:         %options = %{$cursor};
                   10038:     }
                   10039:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10040:         $options{'railalign'} = 'left';
                   10041:     }
                   10042:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10043:         my $function  = &get_users_function();
                   10044:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10045:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10046:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10047:         }
1.1140    raeburn  10048:     }
                   10049:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10050:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10051:             $options{'cursoropacity'}='1.0';
                   10052:         }
1.1140    raeburn  10053:     } else {
                   10054:         $options{'cursoropacity'}='1.0';
                   10055:     }
                   10056:     if ($options{'cursorfixedheight'} eq 'none') {
                   10057:         delete($options{'cursorfixedheight'});
                   10058:     } else {
                   10059:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10060:     }
                   10061:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10062:         delete($options{'railoffset'});
                   10063:     }
                   10064:     my @niceoptions;
                   10065:     while (my($key,$value) = each(%options)) {
                   10066:         if ($value =~ /^\{.+\}$/) {
                   10067:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10068:         } else {
1.1140    raeburn  10069:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10070:         }
1.1140    raeburn  10071:     }
                   10072:     my $nicescroll_js = '
1.1137    raeburn  10073: $(document).ready(
1.1140    raeburn  10074:       function() {
                   10075:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10076:       }
1.1137    raeburn  10077: );
                   10078: ';
1.1140    raeburn  10079:     if ($framecheck) {
                   10080:         $nicescroll_js .= '
                   10081: function expand_div(caller) {
                   10082:     if (top === self) {
                   10083:         document.getElementById("'.$id.'").style.width = "auto";
                   10084:         document.getElementById("'.$id.'").style.height = "auto";
                   10085:     } else {
                   10086:         try {
                   10087:             if (parent.frames) {
                   10088:                 if (parent.frames.length > 1) {
                   10089:                     var framesrc = parent.frames[1].location.href;
                   10090:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10091:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10092:                         document.getElementById("'.$id.'").style.width = "auto";
                   10093:                         document.getElementById("'.$id.'").style.height = "auto";
                   10094:                     }
                   10095:                 }
                   10096:             }
                   10097:         } catch (e) {
                   10098:             return;
                   10099:         }
1.1137    raeburn  10100:     }
1.1140    raeburn  10101:     return;
1.996     www      10102: }
1.1140    raeburn  10103: ';
                   10104:     }
                   10105:     if ($needjsready) {
                   10106:         $nicescroll_js = '
                   10107: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10108:     } else {
                   10109:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10110:     }
                   10111:     return $nicescroll_js;
1.996     www      10112: }
                   10113: 
1.318     albertel 10114: sub simple_error_page {
1.1150    bisitz   10115:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10116:     my %displayargs;
1.1151    raeburn  10117:     if (ref($args) eq 'HASH') {
                   10118:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10119:         if ($args->{'only_body'}) {
                   10120:             $displayargs{'only_body'} = 1;
                   10121:         }
                   10122:         if ($args->{'no_nav_bar'}) {
                   10123:             $displayargs{'no_nav_bar'} = 1;
                   10124:         }
1.1151    raeburn  10125:     } else {
                   10126:         $msg = &mt($msg);
                   10127:     }
1.1150    bisitz   10128: 
1.318     albertel 10129:     my $page =
1.1304    raeburn  10130: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10131: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10132: 	&Apache::loncommon::end_page();
                   10133:     if (ref($r)) {
                   10134: 	$r->print($page);
1.327     albertel 10135: 	return;
1.318     albertel 10136:     }
                   10137:     return $page;
                   10138: }
1.347     albertel 10139: 
                   10140: {
1.610     albertel 10141:     my @row_count;
1.961     onken    10142: 
                   10143:     sub start_data_table_count {
                   10144:         unshift(@row_count, 0);
                   10145:         return;
                   10146:     }
                   10147: 
                   10148:     sub end_data_table_count {
                   10149:         shift(@row_count);
                   10150:         return;
                   10151:     }
                   10152: 
1.347     albertel 10153:     sub start_data_table {
1.1018    raeburn  10154: 	my ($add_class,$id) = @_;
1.422     albertel 10155: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10156:         my $table_id;
                   10157:         if (defined($id)) {
                   10158:             $table_id = ' id="'.$id.'"';
                   10159:         }
1.961     onken    10160: 	&start_data_table_count();
1.1018    raeburn  10161: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10162:     }
                   10163: 
                   10164:     sub end_data_table {
1.961     onken    10165: 	&end_data_table_count();
1.389     albertel 10166: 	return '</table>'."\n";;
1.347     albertel 10167:     }
                   10168: 
                   10169:     sub start_data_table_row {
1.974     wenzelju 10170: 	my ($add_class, $id) = @_;
1.610     albertel 10171: 	$row_count[0]++;
                   10172: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10173: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10174:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10175:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10176:     }
1.471     banghart 10177:     
                   10178:     sub continue_data_table_row {
1.974     wenzelju 10179: 	my ($add_class, $id) = @_;
1.610     albertel 10180: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10181: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10182:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10183:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10184:     }
1.347     albertel 10185: 
                   10186:     sub end_data_table_row {
1.389     albertel 10187: 	return '</tr>'."\n";;
1.347     albertel 10188:     }
1.367     www      10189: 
1.421     albertel 10190:     sub start_data_table_empty_row {
1.707     bisitz   10191: #	$row_count[0]++;
1.421     albertel 10192: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10193:     }
                   10194: 
                   10195:     sub end_data_table_empty_row {
                   10196: 	return '</tr>'."\n";;
                   10197:     }
                   10198: 
1.367     www      10199:     sub start_data_table_header_row {
1.389     albertel 10200: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10201:     }
                   10202: 
                   10203:     sub end_data_table_header_row {
1.389     albertel 10204: 	return '</tr>'."\n";;
1.367     www      10205:     }
1.890     droeschl 10206: 
                   10207:     sub data_table_caption {
                   10208:         my $caption = shift;
                   10209:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10210:     }
1.347     albertel 10211: }
                   10212: 
1.548     albertel 10213: =pod
                   10214: 
                   10215: =item * &inhibit_menu_check($arg)
                   10216: 
                   10217: Checks for a inhibitmenu state and generates output to preserve it
                   10218: 
                   10219: Inputs:         $arg - can be any of
                   10220:                      - undef - in which case the return value is a string 
                   10221:                                to add  into arguments list of a uri
                   10222:                      - 'input' - in which case the return value is a HTML
                   10223:                                  <form> <input> field of type hidden to
                   10224:                                  preserve the value
                   10225:                      - a url - in which case the return value is the url with
                   10226:                                the neccesary cgi args added to preserve the
                   10227:                                inhibitmenu state
                   10228:                      - a ref to a url - no return value, but the string is
                   10229:                                         updated to include the neccessary cgi
                   10230:                                         args to preserve the inhibitmenu state
                   10231: 
                   10232: =cut
                   10233: 
                   10234: sub inhibit_menu_check {
                   10235:     my ($arg) = @_;
                   10236:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10237:     if ($arg eq 'input') {
                   10238: 	if ($env{'form.inhibitmenu'}) {
                   10239: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10240: 	} else {
                   10241: 	    return
                   10242: 	}
                   10243:     }
                   10244:     if ($env{'form.inhibitmenu'}) {
                   10245: 	if (ref($arg)) {
                   10246: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10247: 	} elsif ($arg eq '') {
                   10248: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10249: 	} else {
                   10250: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10251: 	}
                   10252:     }
                   10253:     if (!ref($arg)) {
                   10254: 	return $arg;
                   10255:     }
                   10256: }
                   10257: 
1.251     albertel 10258: ###############################################
1.182     matthew  10259: 
                   10260: =pod
                   10261: 
1.549     albertel 10262: =back
                   10263: 
                   10264: =head1 User Information Routines
                   10265: 
                   10266: =over 4
                   10267: 
1.405     albertel 10268: =item * &get_users_function()
1.182     matthew  10269: 
                   10270: Used by &bodytag to determine the current users primary role.
                   10271: Returns either 'student','coordinator','admin', or 'author'.
                   10272: 
                   10273: =cut
                   10274: 
                   10275: ###############################################
                   10276: sub get_users_function {
1.815     tempelho 10277:     my $function = 'norole';
1.818     tempelho 10278:     if ($env{'request.role'}=~/^(st)/) {
                   10279:         $function='student';
                   10280:     }
1.907     raeburn  10281:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10282:         $function='coordinator';
                   10283:     }
1.258     albertel 10284:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10285:         $function='admin';
                   10286:     }
1.826     bisitz   10287:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10288:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10289:         $function='author';
                   10290:     }
                   10291:     return $function;
1.54      www      10292: }
1.99      www      10293: 
                   10294: ###############################################
                   10295: 
1.233     raeburn  10296: =pod
                   10297: 
1.821     raeburn  10298: =item * &show_course()
                   10299: 
                   10300: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10301: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10302: 
                   10303: Inputs:
                   10304: None
                   10305: 
                   10306: Outputs:
                   10307: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10308: 
                   10309: =cut
                   10310: 
                   10311: ###############################################
                   10312: sub show_course {
                   10313:     my $course = !$env{'user.adv'};
                   10314:     if (!$env{'user.adv'}) {
                   10315:         foreach my $env (keys(%env)) {
                   10316:             next if ($env !~ m/^user\.priv\./);
                   10317:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10318:                 $course = 0;
                   10319:                 last;
                   10320:             }
                   10321:         }
                   10322:     }
                   10323:     return $course;
                   10324: }
                   10325: 
                   10326: ###############################################
                   10327: 
                   10328: =pod
                   10329: 
1.542     raeburn  10330: =item * &check_user_status()
1.274     raeburn  10331: 
                   10332: Determines current status of supplied role for a
                   10333: specific user. Roles can be active, previous or future.
                   10334: 
                   10335: Inputs: 
                   10336: user's domain, user's username, course's domain,
1.375     raeburn  10337: course's number, optional section ID.
1.274     raeburn  10338: 
                   10339: Outputs:
                   10340: role status: active, previous or future. 
                   10341: 
                   10342: =cut
                   10343: 
                   10344: sub check_user_status {
1.412     raeburn  10345:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10346:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10347:     my @uroles = keys(%userinfo);
1.274     raeburn  10348:     my $srchstr;
                   10349:     my $active_chk = 'none';
1.412     raeburn  10350:     my $now = time;
1.274     raeburn  10351:     if (@uroles > 0) {
1.908     raeburn  10352:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10353:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10354:         } else {
1.412     raeburn  10355:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10356:         }
                   10357:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10358:             my $role_end = 0;
                   10359:             my $role_start = 0;
                   10360:             $active_chk = 'active';
1.412     raeburn  10361:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10362:                 $role_end = $1;
                   10363:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10364:                     $role_start = $1;
1.274     raeburn  10365:                 }
                   10366:             }
                   10367:             if ($role_start > 0) {
1.412     raeburn  10368:                 if ($now < $role_start) {
1.274     raeburn  10369:                     $active_chk = 'future';
                   10370:                 }
                   10371:             }
                   10372:             if ($role_end > 0) {
1.412     raeburn  10373:                 if ($now > $role_end) {
1.274     raeburn  10374:                     $active_chk = 'previous';
                   10375:                 }
                   10376:             }
                   10377:         }
                   10378:     }
                   10379:     return $active_chk;
                   10380: }
                   10381: 
                   10382: ###############################################
                   10383: 
                   10384: =pod
                   10385: 
1.405     albertel 10386: =item * &get_sections()
1.233     raeburn  10387: 
                   10388: Determines all the sections for a course including
                   10389: sections with students and sections containing other roles.
1.419     raeburn  10390: Incoming parameters: 
                   10391: 
                   10392: 1. domain
                   10393: 2. course number 
                   10394: 3. reference to array containing roles for which sections should 
                   10395: be gathered (optional).
                   10396: 4. reference to array containing status types for which sections 
                   10397: should be gathered (optional).
                   10398: 
                   10399: If the third argument is undefined, sections are gathered for any role. 
                   10400: If the fourth argument is undefined, sections are gathered for any status.
                   10401: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10402:  
1.374     raeburn  10403: Returns section hash (keys are section IDs, values are
                   10404: number of users in each section), subject to the
1.419     raeburn  10405: optional roles filter, optional status filter 
1.233     raeburn  10406: 
                   10407: =cut
                   10408: 
                   10409: ###############################################
                   10410: sub get_sections {
1.419     raeburn  10411:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10412:     if (!defined($cdom) || !defined($cnum)) {
                   10413:         my $cid =  $env{'request.course.id'};
                   10414: 
                   10415: 	return if (!defined($cid));
                   10416: 
                   10417:         $cdom = $env{'course.'.$cid.'.domain'};
                   10418:         $cnum = $env{'course.'.$cid.'.num'};
                   10419:     }
                   10420: 
                   10421:     my %sectioncount;
1.419     raeburn  10422:     my $now = time;
1.240     albertel 10423: 
1.1118    raeburn  10424:     my $check_students = 1;
                   10425:     my $only_students = 0;
                   10426:     if (ref($possible_roles) eq 'ARRAY') {
                   10427:         if (grep(/^st$/,@{$possible_roles})) {
                   10428:             if (@{$possible_roles} == 1) {
                   10429:                 $only_students = 1;
                   10430:             }
                   10431:         } else {
                   10432:             $check_students = 0;
                   10433:         }
                   10434:     }
                   10435: 
                   10436:     if ($check_students) { 
1.276     albertel 10437: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10438: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10439: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10440:         my $start_index = &Apache::loncoursedata::CL_START();
                   10441:         my $end_index = &Apache::loncoursedata::CL_END();
                   10442:         my $status;
1.366     albertel 10443: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10444: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10445: 				                     $data->[$status_index],
                   10446:                                                      $data->[$start_index],
                   10447:                                                      $data->[$end_index]);
                   10448:             if ($stu_status eq 'Active') {
                   10449:                 $status = 'active';
                   10450:             } elsif ($end < $now) {
                   10451:                 $status = 'previous';
                   10452:             } elsif ($start > $now) {
                   10453:                 $status = 'future';
                   10454:             } 
                   10455: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10456:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10457:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10458: 		    $sectioncount{$section}++;
                   10459:                 }
1.240     albertel 10460: 	    }
                   10461: 	}
                   10462:     }
1.1118    raeburn  10463:     if ($only_students) {
                   10464:         return %sectioncount;
                   10465:     }
1.240     albertel 10466:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10467:     foreach my $user (sort(keys(%courseroles))) {
                   10468: 	if ($user !~ /^(\w{2})/) { next; }
                   10469: 	my ($role) = ($user =~ /^(\w{2})/);
                   10470: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10471: 	my ($section,$status);
1.240     albertel 10472: 	if ($role eq 'cr' &&
                   10473: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10474: 	    $section=$1;
                   10475: 	}
                   10476: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10477: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10478:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10479:         if ($end == -1 && $start == -1) {
                   10480:             next; #deleted role
                   10481:         }
                   10482:         if (!defined($possible_status)) { 
                   10483:             $sectioncount{$section}++;
                   10484:         } else {
                   10485:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10486:                 $status = 'active';
                   10487:             } elsif ($end < $now) {
                   10488:                 $status = 'future';
                   10489:             } elsif ($start > $now) {
                   10490:                 $status = 'previous';
                   10491:             }
                   10492:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10493:                 $sectioncount{$section}++;
                   10494:             }
                   10495:         }
1.233     raeburn  10496:     }
1.366     albertel 10497:     return %sectioncount;
1.233     raeburn  10498: }
                   10499: 
1.274     raeburn  10500: ###############################################
1.294     raeburn  10501: 
                   10502: =pod
1.405     albertel 10503: 
                   10504: =item * &get_course_users()
                   10505: 
1.275     raeburn  10506: Retrieves usernames:domains for users in the specified course
                   10507: with specific role(s), and access status. 
                   10508: 
                   10509: Incoming parameters:
1.277     albertel 10510: 1. course domain
                   10511: 2. course number
                   10512: 3. access status: users must have - either active, 
1.275     raeburn  10513: previous, future, or all.
1.277     albertel 10514: 4. reference to array of permissible roles
1.288     raeburn  10515: 5. reference to array of section restrictions (optional)
                   10516: 6. reference to results object (hash of hashes).
                   10517: 7. reference to optional userdata hash
1.609     raeburn  10518: 8. reference to optional statushash
1.630     raeburn  10519: 9. flag if privileged users (except those set to unhide in
                   10520:    course settings) should be excluded    
1.609     raeburn  10521: Keys of top level results hash are roles.
1.275     raeburn  10522: Keys of inner hashes are username:domain, with 
                   10523: values set to access type.
1.288     raeburn  10524: Optional userdata hash returns an array with arguments in the 
                   10525: same order as loncoursedata::get_classlist() for student data.
                   10526: 
1.609     raeburn  10527: Optional statushash returns
                   10528: 
1.288     raeburn  10529: Entries for end, start, section and status are blank because
                   10530: of the possibility of multiple values for non-student roles.
                   10531: 
1.275     raeburn  10532: =cut
1.405     albertel 10533: 
1.275     raeburn  10534: ###############################################
1.405     albertel 10535: 
1.275     raeburn  10536: sub get_course_users {
1.630     raeburn  10537:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10538:     my %idx = ();
1.419     raeburn  10539:     my %seclists;
1.288     raeburn  10540: 
                   10541:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10542:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10543:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10544:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10545:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10546:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10547:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10548:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10549: 
1.290     albertel 10550:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10551:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10552:         my $now = time;
1.277     albertel 10553:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10554:             my $match = 0;
1.412     raeburn  10555:             my $secmatch = 0;
1.419     raeburn  10556:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10557:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10558:             if ($section eq '') {
                   10559:                 $section = 'none';
                   10560:             }
1.291     albertel 10561:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10562:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10563:                     $secmatch = 1;
                   10564:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10565:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10566:                         $secmatch = 1;
                   10567:                     }
                   10568:                 } else {  
1.419     raeburn  10569: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10570: 		        $secmatch = 1;
                   10571:                     }
1.290     albertel 10572: 		}
1.412     raeburn  10573:                 if (!$secmatch) {
                   10574:                     next;
                   10575:                 }
1.419     raeburn  10576:             }
1.275     raeburn  10577:             if (defined($$types{'active'})) {
1.288     raeburn  10578:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10579:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10580:                     $match = 1;
1.275     raeburn  10581:                 }
                   10582:             }
                   10583:             if (defined($$types{'previous'})) {
1.609     raeburn  10584:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10585:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10586:                     $match = 1;
1.275     raeburn  10587:                 }
                   10588:             }
                   10589:             if (defined($$types{'future'})) {
1.609     raeburn  10590:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10591:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10592:                     $match = 1;
1.275     raeburn  10593:                 }
                   10594:             }
1.609     raeburn  10595:             if ($match) {
                   10596:                 push(@{$seclists{$student}},$section);
                   10597:                 if (ref($userdata) eq 'HASH') {
                   10598:                     $$userdata{$student} = $$classlist{$student};
                   10599:                 }
                   10600:                 if (ref($statushash) eq 'HASH') {
                   10601:                     $statushash->{$student}{'st'}{$section} = $status;
                   10602:                 }
1.288     raeburn  10603:             }
1.275     raeburn  10604:         }
                   10605:     }
1.412     raeburn  10606:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10607:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10608:         my $now = time;
1.609     raeburn  10609:         my %displaystatus = ( previous => 'Expired',
                   10610:                               active   => 'Active',
                   10611:                               future   => 'Future',
                   10612:                             );
1.1121    raeburn  10613:         my (%nothide,@possdoms);
1.630     raeburn  10614:         if ($hidepriv) {
                   10615:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10616:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10617:                 if ($user !~ /:/) {
                   10618:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10619:                 } else {
                   10620:                     $nothide{$user} = 1;
                   10621:                 }
                   10622:             }
1.1121    raeburn  10623:             my @possdoms = ($cdom);
                   10624:             if ($coursehash{'checkforpriv'}) {
                   10625:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10626:             }
1.630     raeburn  10627:         }
1.439     raeburn  10628:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10629:             my $match = 0;
1.412     raeburn  10630:             my $secmatch = 0;
1.439     raeburn  10631:             my $status;
1.412     raeburn  10632:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10633:             $user =~ s/:$//;
1.439     raeburn  10634:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10635:             if ($end == -1 || $start == -1) {
                   10636:                 next;
                   10637:             }
                   10638:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10639:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10640:                 my ($uname,$udom) = split(/:/,$user);
                   10641:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10642:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10643:                         $secmatch = 1;
                   10644:                     } elsif ($usec eq '') {
1.420     albertel 10645:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10646:                             $secmatch = 1;
                   10647:                         }
                   10648:                     } else {
                   10649:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10650:                             $secmatch = 1;
                   10651:                         }
                   10652:                     }
                   10653:                     if (!$secmatch) {
                   10654:                         next;
                   10655:                     }
1.288     raeburn  10656:                 }
1.419     raeburn  10657:                 if ($usec eq '') {
                   10658:                     $usec = 'none';
                   10659:                 }
1.275     raeburn  10660:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10661:                     if ($hidepriv) {
1.1121    raeburn  10662:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10663:                             (!$nothide{$uname.':'.$udom})) {
                   10664:                             next;
                   10665:                         }
                   10666:                     }
1.503     raeburn  10667:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10668:                         $status = 'previous';
                   10669:                     } elsif ($start > $now) {
                   10670:                         $status = 'future';
                   10671:                     } else {
                   10672:                         $status = 'active';
                   10673:                     }
1.277     albertel 10674:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10675:                         if ($status eq $type) {
1.420     albertel 10676:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10677:                                 push(@{$$users{$role}{$user}},$type);
                   10678:                             }
1.288     raeburn  10679:                             $match = 1;
                   10680:                         }
                   10681:                     }
1.419     raeburn  10682:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10683:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10684: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10685:                         }
1.420     albertel 10686:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10687:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10688:                         }
1.609     raeburn  10689:                         if (ref($statushash) eq 'HASH') {
                   10690:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10691:                         }
1.275     raeburn  10692:                     }
                   10693:                 }
                   10694:             }
                   10695:         }
1.290     albertel 10696:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10697:             if ((defined($cdom)) && (defined($cnum))) {
                   10698:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10699:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10700:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10701:                     next if ($owner eq '');
                   10702:                     my ($ownername,$ownerdom);
                   10703:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10704:                         $ownername = $1;
                   10705:                         $ownerdom = $2;
                   10706:                     } else {
                   10707:                         $ownername = $owner;
                   10708:                         $ownerdom = $cdom;
                   10709:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10710:                     }
                   10711:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10712:                     if (defined($userdata) && 
1.609     raeburn  10713: 			!exists($$userdata{$owner})) {
                   10714: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10715:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10716:                             push(@{$seclists{$owner}},'none');
                   10717:                         }
                   10718:                         if (ref($statushash) eq 'HASH') {
                   10719:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10720:                         }
1.290     albertel 10721: 		    }
1.279     raeburn  10722:                 }
                   10723:             }
                   10724:         }
1.419     raeburn  10725:         foreach my $user (keys(%seclists)) {
                   10726:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10727:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10728:         }
1.275     raeburn  10729:     }
                   10730:     return;
                   10731: }
                   10732: 
1.288     raeburn  10733: sub get_user_info {
                   10734:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10735:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10736: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10737:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10738:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10739:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10740:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10741:     return;
                   10742: }
1.275     raeburn  10743: 
1.472     raeburn  10744: ###############################################
                   10745: 
                   10746: =pod
                   10747: 
                   10748: =item * &get_user_quota()
                   10749: 
1.1134    raeburn  10750: Retrieves quota assigned for storage of user files.
                   10751: Default is to report quota for portfolio files.
1.472     raeburn  10752: 
                   10753: Incoming parameters:
                   10754: 1. user's username
                   10755: 2. user's domain
1.1134    raeburn  10756: 3. quota name - portfolio, author, or course
1.1136    raeburn  10757:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10758: 4. crstype - official, unofficial, textbook, placement or community, 
                   10759:    if quota name is course
1.472     raeburn  10760: 
                   10761: Returns:
1.1163    raeburn  10762: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10763: 2. (Optional) Type of setting: custom or default
                   10764:    (individually assigned or default for user's 
                   10765:    institutional status).
                   10766: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10767:    or student - types as defined in localenroll::inst_usertypes 
                   10768:    for user's domain, which determines default quota for user.
                   10769: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10770: 
                   10771: If a value has been stored in the user's environment, 
1.536     raeburn  10772: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10773: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10774: 
                   10775: =cut
                   10776: 
                   10777: ###############################################
                   10778: 
                   10779: 
                   10780: sub get_user_quota {
1.1136    raeburn  10781:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10782:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10783:     if (!defined($udom)) {
                   10784:         $udom = $env{'user.domain'};
                   10785:     }
                   10786:     if (!defined($uname)) {
                   10787:         $uname = $env{'user.name'};
                   10788:     }
                   10789:     if (($udom eq '' || $uname eq '') ||
                   10790:         ($udom eq 'public') && ($uname eq 'public')) {
                   10791:         $quota = 0;
1.536     raeburn  10792:         $quotatype = 'default';
                   10793:         $defquota = 0; 
1.472     raeburn  10794:     } else {
1.536     raeburn  10795:         my $inststatus;
1.1134    raeburn  10796:         if ($quotaname eq 'course') {
                   10797:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10798:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10799:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10800:             } else {
                   10801:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10802:                 $quota = $cenv{'internal.uploadquota'};
                   10803:             }
1.536     raeburn  10804:         } else {
1.1134    raeburn  10805:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10806:                 if ($quotaname eq 'author') {
                   10807:                     $quota = $env{'environment.authorquota'};
                   10808:                 } else {
                   10809:                     $quota = $env{'environment.portfolioquota'};
                   10810:                 }
                   10811:                 $inststatus = $env{'environment.inststatus'};
                   10812:             } else {
                   10813:                 my %userenv = 
                   10814:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10815:                                          'authorquota','inststatus'],$udom,$uname);
                   10816:                 my ($tmp) = keys(%userenv);
                   10817:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10818:                     if ($quotaname eq 'author') {
                   10819:                         $quota = $userenv{'authorquota'};
                   10820:                     } else {
                   10821:                         $quota = $userenv{'portfolioquota'};
                   10822:                     }
                   10823:                     $inststatus = $userenv{'inststatus'};
                   10824:                 } else {
                   10825:                     undef(%userenv);
                   10826:                 }
                   10827:             }
                   10828:         }
                   10829:         if ($quota eq '' || wantarray) {
                   10830:             if ($quotaname eq 'course') {
                   10831:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10832:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10833:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10834:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10835:                     $defquota = $domdefs{$crstype.'quota'};
                   10836:                 }
                   10837:                 if ($defquota eq '') {
                   10838:                     $defquota = 500;
                   10839:                 }
1.1134    raeburn  10840:             } else {
                   10841:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10842:             }
                   10843:             if ($quota eq '') {
                   10844:                 $quota = $defquota;
                   10845:                 $quotatype = 'default';
                   10846:             } else {
                   10847:                 $quotatype = 'custom';
                   10848:             }
1.472     raeburn  10849:         }
                   10850:     }
1.536     raeburn  10851:     if (wantarray) {
                   10852:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10853:     } else {
                   10854:         return $quota;
                   10855:     }
1.472     raeburn  10856: }
                   10857: 
                   10858: ###############################################
                   10859: 
                   10860: =pod
                   10861: 
                   10862: =item * &default_quota()
                   10863: 
1.536     raeburn  10864: Retrieves default quota assigned for storage of user portfolio files,
                   10865: given an (optional) user's institutional status.
1.472     raeburn  10866: 
                   10867: Incoming parameters:
1.1142    raeburn  10868: 
1.472     raeburn  10869: 1. domain
1.536     raeburn  10870: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10871:    status types (e.g., faculty, staff, student etc.)
                   10872:    which apply to the user for whom the default is being retrieved.
                   10873:    If the institutional status string in undefined, the domain
1.1134    raeburn  10874:    default quota will be returned.
                   10875: 3.  quota name - portfolio, author, or course
                   10876:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10877: 
                   10878: Returns:
1.1142    raeburn  10879: 
1.1163    raeburn  10880: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10881: 2. (Optional) institutional type which determined the value of the
                   10882:    default quota.
1.472     raeburn  10883: 
                   10884: If a value has been stored in the domain's configuration db,
                   10885: it will return that, otherwise it returns 20 (for backwards 
                   10886: compatibility with domains which have not set up a configuration
1.1163    raeburn  10887: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10888: 
1.536     raeburn  10889: If the user's status includes multiple types (e.g., staff and student),
                   10890: the largest default quota which applies to the user determines the
                   10891: default quota returned.
                   10892: 
1.472     raeburn  10893: =cut
                   10894: 
                   10895: ###############################################
                   10896: 
                   10897: 
                   10898: sub default_quota {
1.1134    raeburn  10899:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10900:     my ($defquota,$settingstatus);
                   10901:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10902:                                             ['quotas'],$udom);
1.1134    raeburn  10903:     my $key = 'defaultquota';
                   10904:     if ($quotaname eq 'author') {
                   10905:         $key = 'authorquota';
                   10906:     }
1.622     raeburn  10907:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10908:         if ($inststatus ne '') {
1.765     raeburn  10909:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10910:             foreach my $item (@statuses) {
1.1134    raeburn  10911:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10912:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10913:                         if ($defquota eq '') {
1.1134    raeburn  10914:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10915:                             $settingstatus = $item;
1.1134    raeburn  10916:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10917:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10918:                             $settingstatus = $item;
                   10919:                         }
                   10920:                     }
1.1134    raeburn  10921:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10922:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10923:                         if ($defquota eq '') {
                   10924:                             $defquota = $quotahash{'quotas'}{$item};
                   10925:                             $settingstatus = $item;
                   10926:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10927:                             $defquota = $quotahash{'quotas'}{$item};
                   10928:                             $settingstatus = $item;
                   10929:                         }
1.536     raeburn  10930:                     }
                   10931:                 }
                   10932:             }
                   10933:         }
                   10934:         if ($defquota eq '') {
1.1134    raeburn  10935:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10936:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10937:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10938:                 $defquota = $quotahash{'quotas'}{'default'};
                   10939:             }
1.536     raeburn  10940:             $settingstatus = 'default';
1.1139    raeburn  10941:             if ($defquota eq '') {
                   10942:                 if ($quotaname eq 'author') {
                   10943:                     $defquota = 500;
                   10944:                 }
                   10945:             }
1.536     raeburn  10946:         }
                   10947:     } else {
                   10948:         $settingstatus = 'default';
1.1134    raeburn  10949:         if ($quotaname eq 'author') {
                   10950:             $defquota = 500;
                   10951:         } else {
                   10952:             $defquota = 20;
                   10953:         }
1.536     raeburn  10954:     }
                   10955:     if (wantarray) {
                   10956:         return ($defquota,$settingstatus);
1.472     raeburn  10957:     } else {
1.536     raeburn  10958:         return $defquota;
1.472     raeburn  10959:     }
                   10960: }
                   10961: 
1.1135    raeburn  10962: ###############################################
                   10963: 
                   10964: =pod
                   10965: 
1.1136    raeburn  10966: =item * &excess_filesize_warning()
1.1135    raeburn  10967: 
                   10968: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10969: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10970: space to be exceeded.
1.1136    raeburn  10971: 
                   10972: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10973: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10974: 
1.1165    raeburn  10975: Inputs: 7 
1.1136    raeburn  10976: 1. username or coursenum
1.1135    raeburn  10977: 2. domain
1.1136    raeburn  10978: 3. context ('author' or 'course')
1.1135    raeburn  10979: 4. filename of file for which action is being requested
                   10980: 5. filesize (kB) of file
                   10981: 6. action being taken: copy or upload.
1.1237    raeburn  10982: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10983: 
                   10984: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10985:          otherwise return null.
                   10986: 
                   10987: =back
1.1135    raeburn  10988: 
                   10989: =cut
                   10990: 
1.1136    raeburn  10991: sub excess_filesize_warning {
1.1165    raeburn  10992:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10993:     my $current_disk_usage = 0;
1.1165    raeburn  10994:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10995:     if ($context eq 'author') {
                   10996:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10997:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10998:     } else {
                   10999:         foreach my $subdir ('docs','supplemental') {
                   11000:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11001:         }
                   11002:     }
1.1135    raeburn  11003:     $disk_quota = int($disk_quota * 1000);
                   11004:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11005:         return '<p class="LC_warning">'.
1.1135    raeburn  11006:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11007:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11008:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11009:                             $disk_quota,$current_disk_usage).
                   11010:                '</p>';
                   11011:     }
                   11012:     return;
                   11013: }
                   11014: 
                   11015: ###############################################
                   11016: 
                   11017: 
1.1136    raeburn  11018: 
                   11019: 
1.384     raeburn  11020: sub get_secgrprole_info {
                   11021:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11022:     my %sections_count = &get_sections($cdom,$cnum);
                   11023:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11024:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11025:     my @groups = sort(keys(%curr_groups));
                   11026:     my $allroles = [];
                   11027:     my $rolehash;
                   11028:     my $accesshash = {
                   11029:                      active => 'Currently has access',
                   11030:                      future => 'Will have future access',
                   11031:                      previous => 'Previously had access',
                   11032:                   };
                   11033:     if ($needroles) {
                   11034:         $rolehash = {'all' => 'all'};
1.385     albertel 11035:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11036: 	if (&Apache::lonnet::error(%user_roles)) {
                   11037: 	    undef(%user_roles);
                   11038: 	}
                   11039:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11040:             my ($role)=split(/\:/,$item,2);
                   11041:             if ($role eq 'cr') { next; }
                   11042:             if ($role =~ /^cr/) {
                   11043:                 $$rolehash{$role} = (split('/',$role))[3];
                   11044:             } else {
                   11045:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11046:             }
                   11047:         }
                   11048:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11049:             push(@{$allroles},$key);
                   11050:         }
                   11051:         push (@{$allroles},'st');
                   11052:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11053:     }
                   11054:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11055: }
                   11056: 
1.555     raeburn  11057: sub user_picker {
1.1279    raeburn  11058:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11059:     my $currdom = $dom;
1.1253    raeburn  11060:     my @alldoms = &Apache::lonnet::all_domains();
                   11061:     if (@alldoms == 1) {
                   11062:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11063:                                                ['directorysrch'],$alldoms[0]);
                   11064:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11065:         my $showdom = $domdesc;
                   11066:         if ($showdom eq '') {
                   11067:             $showdom = $dom;
                   11068:         }
                   11069:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11070:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11071:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11072:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11073:             }
                   11074:         }
                   11075:     }
1.555     raeburn  11076:     my %curr_selected = (
                   11077:                         srchin => 'dom',
1.580     raeburn  11078:                         srchby => 'lastname',
1.555     raeburn  11079:                       );
                   11080:     my $srchterm;
1.625     raeburn  11081:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11082:         if ($srch->{'srchby'} ne '') {
                   11083:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11084:         }
                   11085:         if ($srch->{'srchin'} ne '') {
                   11086:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11087:         }
                   11088:         if ($srch->{'srchtype'} ne '') {
                   11089:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11090:         }
                   11091:         if ($srch->{'srchdomain'} ne '') {
                   11092:             $currdom = $srch->{'srchdomain'};
                   11093:         }
                   11094:         $srchterm = $srch->{'srchterm'};
                   11095:     }
1.1222    damieng  11096:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11097:                     'usr'       => 'Search criteria',
1.563     raeburn  11098:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11099:                     'uname'     => 'username',
                   11100:                     'lastname'  => 'last name',
1.555     raeburn  11101:                     'lastfirst' => 'last name, first name',
1.558     albertel 11102:                     'crs'       => 'in this course',
1.576     raeburn  11103:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11104:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11105:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11106:                     'exact'     => 'is',
                   11107:                     'contains'  => 'contains',
1.569     raeburn  11108:                     'begins'    => 'begins with',
1.1222    damieng  11109:                                        );
                   11110:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11111:                     'youm'      => "You must include some text to search for.",
                   11112:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11113:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11114:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11115:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11116:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11117:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11118:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11119:                                        );
1.1222    damieng  11120:     &html_escape(\%html_lt);
                   11121:     &js_escape(\%js_lt);
1.1255    raeburn  11122:     my $domform;
1.1277    raeburn  11123:     my $allow_blank = 1;
1.1255    raeburn  11124:     if ($fixeddom) {
1.1277    raeburn  11125:         $allow_blank = 0;
                   11126:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11127:     } else {
1.1287    raeburn  11128:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11129:         my ($trusted,$untrusted);
1.1287    raeburn  11130:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11131:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11132:         } elsif ($context eq 'author') {
1.1288    raeburn  11133:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11134:         } elsif ($context eq 'domain') {
1.1288    raeburn  11135:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11136:         }
1.1288    raeburn  11137:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11138:     }
1.563     raeburn  11139:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11140: 
                   11141:     my @srchins = ('crs','dom','alc','instd');
                   11142: 
                   11143:     foreach my $option (@srchins) {
                   11144:         # FIXME 'alc' option unavailable until 
                   11145:         #       loncreateuser::print_user_query_page()
                   11146:         #       has been completed.
                   11147:         next if ($option eq 'alc');
1.880     raeburn  11148:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11149:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11150:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11151:         if ($curr_selected{'srchin'} eq $option) {
                   11152:             $srchinsel .= ' 
1.1222    damieng  11153:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11154:         } else {
                   11155:             $srchinsel .= '
1.1222    damieng  11156:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11157:         }
1.555     raeburn  11158:     }
1.563     raeburn  11159:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11160: 
                   11161:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11162:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11163:         if ($curr_selected{'srchby'} eq $option) {
                   11164:             $srchbysel .= '
1.1222    damieng  11165:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11166:         } else {
                   11167:             $srchbysel .= '
1.1222    damieng  11168:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11169:          }
                   11170:     }
                   11171:     $srchbysel .= "\n  </select>\n";
                   11172: 
                   11173:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11174:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11175:         if ($curr_selected{'srchtype'} eq $option) {
                   11176:             $srchtypesel .= '
1.1222    damieng  11177:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11178:         } else {
                   11179:             $srchtypesel .= '
1.1222    damieng  11180:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11181:         }
                   11182:     }
                   11183:     $srchtypesel .= "\n  </select>\n";
                   11184: 
1.558     albertel 11185:     my ($newuserscript,$new_user_create);
1.994     raeburn  11186:     my $context_dom = $env{'request.role.domain'};
                   11187:     if ($context eq 'requestcrs') {
                   11188:         if ($env{'form.coursedom'} ne '') { 
                   11189:             $context_dom = $env{'form.coursedom'};
                   11190:         }
                   11191:     }
1.556     raeburn  11192:     if ($forcenewuser) {
1.576     raeburn  11193:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11194:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11195:                 if ($cancreate) {
                   11196:                     $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>';
                   11197:                 } else {
1.799     bisitz   11198:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11199:                     my %usertypetext = (
                   11200:                         official   => 'institutional',
                   11201:                         unofficial => 'non-institutional',
                   11202:                     );
1.799     bisitz   11203:                     $new_user_create = '<p class="LC_warning">'
                   11204:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11205:                                       .' '
                   11206:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11207:                                           ,'<a href="'.$helplink.'">','</a>')
                   11208:                                       .'</p><br />';
1.627     raeburn  11209:                 }
1.576     raeburn  11210:             }
                   11211:         }
                   11212: 
1.556     raeburn  11213:         $newuserscript = <<"ENDSCRIPT";
                   11214: 
1.570     raeburn  11215: function setSearch(createnew,callingForm) {
1.556     raeburn  11216:     if (createnew == 1) {
1.570     raeburn  11217:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11218:             if (callingForm.srchby.options[i].value == 'uname') {
                   11219:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11220:             }
                   11221:         }
1.570     raeburn  11222:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11223:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11224: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11225:             }
                   11226:         }
1.570     raeburn  11227:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11228:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11229:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11230:             }
                   11231:         }
1.570     raeburn  11232:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11233:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11234:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11235:             }
                   11236:         }
                   11237:     }
                   11238: }
                   11239: ENDSCRIPT
1.558     albertel 11240: 
1.556     raeburn  11241:     }
                   11242: 
1.555     raeburn  11243:     my $output = <<"END_BLOCK";
1.556     raeburn  11244: <script type="text/javascript">
1.824     bisitz   11245: // <![CDATA[
1.570     raeburn  11246: function validateEntry(callingForm) {
1.558     albertel 11247: 
1.556     raeburn  11248:     var checkok = 1;
1.558     albertel 11249:     var srchin;
1.570     raeburn  11250:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11251: 	if ( callingForm.srchin[i].checked ) {
                   11252: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11253: 	}
                   11254:     }
                   11255: 
1.570     raeburn  11256:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11257:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11258:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11259:     var srchterm =  callingForm.srchterm.value;
                   11260:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11261:     var msg = "";
                   11262: 
                   11263:     if (srchterm == "") {
                   11264:         checkok = 0;
1.1222    damieng  11265:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11266:     }
                   11267: 
1.569     raeburn  11268:     if (srchtype== 'begins') {
                   11269:         if (srchterm.length < 2) {
                   11270:             checkok = 0;
1.1222    damieng  11271:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11272:         }
                   11273:     }
                   11274: 
1.556     raeburn  11275:     if (srchtype== 'contains') {
                   11276:         if (srchterm.length < 3) {
                   11277:             checkok = 0;
1.1222    damieng  11278:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11279:         }
                   11280:     }
                   11281:     if (srchin == 'instd') {
                   11282:         if (srchdomain == '') {
                   11283:             checkok = 0;
1.1222    damieng  11284:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11285:         }
                   11286:     }
                   11287:     if (srchin == 'dom') {
                   11288:         if (srchdomain == '') {
                   11289:             checkok = 0;
1.1222    damieng  11290:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11291:         }
                   11292:     }
                   11293:     if (srchby == 'lastfirst') {
                   11294:         if (srchterm.indexOf(",") == -1) {
                   11295:             checkok = 0;
1.1222    damieng  11296:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11297:         }
                   11298:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11299:             checkok = 0;
1.1222    damieng  11300:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11301:         }
                   11302:     }
                   11303:     if (checkok == 0) {
1.1222    damieng  11304:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11305:         return;
                   11306:     }
                   11307:     if (checkok == 1) {
1.570     raeburn  11308:         callingForm.submit();
1.556     raeburn  11309:     }
                   11310: }
                   11311: 
                   11312: $newuserscript
                   11313: 
1.824     bisitz   11314: // ]]>
1.556     raeburn  11315: </script>
1.558     albertel 11316: 
                   11317: $new_user_create
                   11318: 
1.555     raeburn  11319: END_BLOCK
1.558     albertel 11320: 
1.876     raeburn  11321:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11322:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11323:                $domform.
                   11324:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11325:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11326:                $srchbysel.
                   11327:                $srchtypesel. 
                   11328:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11329:                $srchinsel.
                   11330:                &Apache::lonhtmlcommon::row_closure(1). 
                   11331:                &Apache::lonhtmlcommon::end_pick_box().
                   11332:                '<br />';
1.1253    raeburn  11333:     return ($output,1);
1.555     raeburn  11334: }
                   11335: 
1.612     raeburn  11336: sub user_rule_check {
1.615     raeburn  11337:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11338:     my ($response,%inst_response);
1.612     raeburn  11339:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11340:         if (keys(%{$usershash}) > 1) {
                   11341:             my (%by_username,%by_id,%userdoms);
                   11342:             my $checkid; 
                   11343:             if (ref($checks) eq 'HASH') {
                   11344:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11345:                     $checkid = 1;
                   11346:                 }
                   11347:             }
                   11348:             foreach my $user (keys(%{$usershash})) {
                   11349:                 my ($uname,$udom) = split(/:/,$user);
                   11350:                 if ($checkid) {
                   11351:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11352:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11353:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11354:                             $userdoms{$udom} = 1;
1.1227    raeburn  11355:                             if (ref($inst_results) eq 'HASH') {
                   11356:                                 $inst_results->{$uname.':'.$udom} = {};
                   11357:                             }
1.1226    raeburn  11358:                         }
                   11359:                     }
                   11360:                 } else {
                   11361:                     $by_username{$udom}{$uname} = 1;
                   11362:                     $userdoms{$udom} = 1;
1.1227    raeburn  11363:                     if (ref($inst_results) eq 'HASH') {
                   11364:                         $inst_results->{$uname.':'.$udom} = {};
                   11365:                     }
1.1226    raeburn  11366:                 }
                   11367:             }
                   11368:             foreach my $udom (keys(%userdoms)) {
                   11369:                 if (!$got_rules->{$udom}) {
                   11370:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11371:                                                              ['usercreation'],$udom);
                   11372:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11373:                         foreach my $item ('username','id') {
                   11374:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11375:                                 $$curr_rules{$udom}{$item} =
                   11376:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11377:                             }
                   11378:                         }
                   11379:                     }
                   11380:                     $got_rules->{$udom} = 1;
                   11381:                 }
1.612     raeburn  11382:             }
1.1226    raeburn  11383:             if ($checkid) {
                   11384:                 foreach my $udom (keys(%by_id)) {
                   11385:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11386:                     if ($outcome eq 'ok') {
1.1227    raeburn  11387:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11388:                             my $uname = $by_id{$udom}{$id};
                   11389:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11390:                         }
1.1226    raeburn  11391:                         if (ref($results) eq 'HASH') {
                   11392:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11393:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11394:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11395:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11396:                                 }
1.1226    raeburn  11397:                             }
                   11398:                         }
                   11399:                     }
1.612     raeburn  11400:                 }
1.615     raeburn  11401:             } else {
1.1226    raeburn  11402:                 foreach my $udom (keys(%by_username)) {
                   11403:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11404:                     if ($outcome eq 'ok') {
1.1227    raeburn  11405:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11406:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11407:                         }
1.1226    raeburn  11408:                         if (ref($results) eq 'HASH') {
                   11409:                             foreach my $uname (keys(%{$results})) {
                   11410:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11411:                             }
                   11412:                         }
                   11413:                     }
                   11414:                 }
1.612     raeburn  11415:             }
1.1226    raeburn  11416:         } elsif (keys(%{$usershash}) == 1) {
                   11417:             my $user = (keys(%{$usershash}))[0];
                   11418:             my ($uname,$udom) = split(/:/,$user);
                   11419:             if (($udom ne '') && ($uname ne '')) {
                   11420:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11421:                     if (ref($checks) eq 'HASH') {
                   11422:                         if (defined($checks->{'username'})) {
                   11423:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11424:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11425:                         } elsif (defined($checks->{'id'})) {
                   11426:                             if ($usershash->{$user}->{'id'} ne '') {
                   11427:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11428:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11429:                                                                   $usershash->{$user}->{'id'});
                   11430:                             } else {
                   11431:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11432:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11433:                             }
1.585     raeburn  11434:                         }
1.1226    raeburn  11435:                     } else {
                   11436:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11437:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11438:                        return;
                   11439:                     }
                   11440:                     if (!$got_rules->{$udom}) {
                   11441:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11442:                                                                  ['usercreation'],$udom);
                   11443:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11444:                             foreach my $item ('username','id') {
                   11445:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11446:                                    $$curr_rules{$udom}{$item} = 
                   11447:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11448:                                 }
                   11449:                             }
                   11450:                         }
                   11451:                         $got_rules->{$udom} = 1;
1.585     raeburn  11452:                     }
                   11453:                 }
1.1226    raeburn  11454:             } else {
                   11455:                 return;
                   11456:             }
                   11457:         } else {
                   11458:             return;
                   11459:         }
                   11460:         foreach my $user (keys(%{$usershash})) {
                   11461:             my ($uname,$udom) = split(/:/,$user);
                   11462:             next if (($udom eq '') || ($uname eq ''));
                   11463:             my $id;
1.1227    raeburn  11464:             if (ref($inst_results) eq 'HASH') {
                   11465:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11466:                     $id = $inst_results->{$user}->{'id'};
                   11467:                 }
                   11468:             }
                   11469:             if ($id eq '') { 
                   11470:                 if (ref($usershash->{$user})) {
                   11471:                     $id = $usershash->{$user}->{'id'};
                   11472:                 }
1.585     raeburn  11473:             }
1.612     raeburn  11474:             foreach my $item (keys(%{$checks})) {
                   11475:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11476:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11477:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11478:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11479:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11480:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11481:                                 if ($rule_check{$rule}) {
                   11482:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11483:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11484:                                         if (ref($inst_results) eq 'HASH') {
                   11485:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11486:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11487:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11488:                                                 } elsif ($item eq 'id') {
                   11489:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11490:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11491:                                                     }
1.615     raeburn  11492:                                                 }
1.612     raeburn  11493:                                             }
                   11494:                                         }
1.615     raeburn  11495:                                     }
                   11496:                                     last;
1.585     raeburn  11497:                                 }
                   11498:                             }
                   11499:                         }
                   11500:                     }
                   11501:                 }
                   11502:             }
                   11503:         }
                   11504:     }
1.612     raeburn  11505:     return;
                   11506: }
                   11507: 
                   11508: sub user_rule_formats {
                   11509:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11510:     my %text = ( 
                   11511:                  'username' => 'Usernames',
                   11512:                  'id'       => 'IDs',
                   11513:                );
                   11514:     my $output;
                   11515:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11516:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11517:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11518:             $output = '<br />'.
                   11519:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11520:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11521:                       ' <ul>';
1.612     raeburn  11522:             foreach my $rule (@{$ruleorder}) {
                   11523:                 if (ref($curr_rules) eq 'ARRAY') {
                   11524:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11525:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11526:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11527:                                         $rules->{$rule}{'desc'}.'</li>';
                   11528:                         }
                   11529:                     }
                   11530:                 }
                   11531:             }
                   11532:             $output .= '</ul>';
                   11533:         }
                   11534:     }
                   11535:     return $output;
                   11536: }
                   11537: 
                   11538: sub instrule_disallow_msg {
1.615     raeburn  11539:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11540:     my $response;
                   11541:     my %text = (
                   11542:                   item   => 'username',
                   11543:                   items  => 'usernames',
                   11544:                   match  => 'matches',
                   11545:                   do     => 'does',
                   11546:                   action => 'a username',
                   11547:                   one    => 'one',
                   11548:                );
                   11549:     if ($count > 1) {
                   11550:         $text{'item'} = 'usernames';
                   11551:         $text{'match'} ='match';
                   11552:         $text{'do'} = 'do';
                   11553:         $text{'action'} = 'usernames',
                   11554:         $text{'one'} = 'ones';
                   11555:     }
                   11556:     if ($checkitem eq 'id') {
                   11557:         $text{'items'} = 'IDs';
                   11558:         $text{'item'} = 'ID';
                   11559:         $text{'action'} = 'an ID';
1.615     raeburn  11560:         if ($count > 1) {
                   11561:             $text{'item'} = 'IDs';
                   11562:             $text{'action'} = 'IDs';
                   11563:         }
1.612     raeburn  11564:     }
1.674     bisitz   11565:     $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  11566:     if ($mode eq 'upload') {
                   11567:         if ($checkitem eq 'username') {
                   11568:             $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'}.");
                   11569:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11570:             $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  11571:         }
1.669     raeburn  11572:     } elsif ($mode eq 'selfcreate') {
                   11573:         if ($checkitem eq 'id') {
                   11574:             $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.");
                   11575:         }
1.615     raeburn  11576:     } else {
                   11577:         if ($checkitem eq 'username') {
                   11578:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11579:         } elsif ($checkitem eq 'id') {
                   11580:             $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.");
                   11581:         }
1.612     raeburn  11582:     }
                   11583:     return $response;
1.585     raeburn  11584: }
                   11585: 
1.624     raeburn  11586: sub personal_data_fieldtitles {
                   11587:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11588:                         id => 'Student/Employee ID',
                   11589:                         permanentemail => 'E-mail address',
                   11590:                         lastname => 'Last Name',
                   11591:                         firstname => 'First Name',
                   11592:                         middlename => 'Middle Name',
                   11593:                         generation => 'Generation',
                   11594:                         gen => 'Generation',
1.765     raeburn  11595:                         inststatus => 'Affiliation',
1.624     raeburn  11596:                    );
                   11597:     return %fieldtitles;
                   11598: }
                   11599: 
1.642     raeburn  11600: sub sorted_inst_types {
                   11601:     my ($dom) = @_;
1.1185    raeburn  11602:     my ($usertypes,$order);
                   11603:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11604:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11605:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11606:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11607:     } else {
                   11608:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11609:     }
1.642     raeburn  11610:     my $othertitle = &mt('All users');
                   11611:     if ($env{'request.course.id'}) {
1.668     raeburn  11612:         $othertitle  = &mt('Any users');
1.642     raeburn  11613:     }
                   11614:     my @types;
                   11615:     if (ref($order) eq 'ARRAY') {
                   11616:         @types = @{$order};
                   11617:     }
                   11618:     if (@types == 0) {
                   11619:         if (ref($usertypes) eq 'HASH') {
                   11620:             @types = sort(keys(%{$usertypes}));
                   11621:         }
                   11622:     }
                   11623:     if (keys(%{$usertypes}) > 0) {
                   11624:         $othertitle = &mt('Other users');
                   11625:     }
                   11626:     return ($othertitle,$usertypes,\@types);
                   11627: }
                   11628: 
1.645     raeburn  11629: sub get_institutional_codes {
1.1361    raeburn  11630:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11631: # Get complete list of course sections to update
                   11632:     my @currsections = ();
                   11633:     my @currxlists = ();
1.1361    raeburn  11634:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11635:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11636:     my $crskey = $crs.':'.$coursecode;
                   11637:     @{$unclutteredsec{$crskey}} = ();
                   11638:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11639: 
                   11640:     if ($$settings{'internal.sectionnums'} ne '') {
                   11641:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11642:     }
                   11643: 
                   11644:     if ($$settings{'internal.crosslistings'} ne '') {
                   11645:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11646:     }
                   11647: 
                   11648:     if (@currxlists > 0) {
1.1361    raeburn  11649:         foreach my $xl (@currxlists) {
                   11650:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11651:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11652:                     push(@{$allcourses},$1);
1.645     raeburn  11653:                     $$LC_code{$1} = $2;
                   11654:                 }
                   11655:             }
                   11656:         }
                   11657:     }
1.1361    raeburn  11658: 
1.645     raeburn  11659:     if (@currsections > 0) {
1.1361    raeburn  11660:         foreach my $sec (@currsections) {
                   11661:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11662:                 my $instsec = $1;
1.645     raeburn  11663:                 my $lc_sec = $2;
1.1361    raeburn  11664:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11665:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11666:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11667:                 }
                   11668:             }
                   11669:         }
                   11670:     }
                   11671: 
                   11672:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11673:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11674:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11675:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11676:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11677:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11678:                     push(@{$allcourses},$sec);
1.1361    raeburn  11679:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11680:                 }
                   11681:             }
                   11682:         }
                   11683:     }
                   11684:     return;
                   11685: }
                   11686: 
1.971     raeburn  11687: sub get_standard_codeitems {
                   11688:     return ('Year','Semester','Department','Number','Section');
                   11689: }
                   11690: 
1.112     bowersj2 11691: =pod
                   11692: 
1.780     raeburn  11693: =head1 Slot Helpers
                   11694: 
                   11695: =over 4
                   11696: 
                   11697: =item * sorted_slots()
                   11698: 
1.1040    raeburn  11699: Sorts an array of slot names in order of an optional sort key,
                   11700: default sort is by slot start time (earliest first). 
1.780     raeburn  11701: 
                   11702: Inputs:
                   11703: 
                   11704: =over 4
                   11705: 
                   11706: slotsarr  - Reference to array of unsorted slot names.
                   11707: 
                   11708: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11709: 
1.1040    raeburn  11710: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11711: 
1.549     albertel 11712: =back
                   11713: 
1.780     raeburn  11714: Returns:
                   11715: 
                   11716: =over 4
                   11717: 
1.1040    raeburn  11718: sorted   - An array of slot names sorted by a specified sort key 
                   11719:            (default sort key is start time of the slot).
1.780     raeburn  11720: 
                   11721: =back
                   11722: 
                   11723: =cut
                   11724: 
                   11725: 
                   11726: sub sorted_slots {
1.1040    raeburn  11727:     my ($slotsarr,$slots,$sortkey) = @_;
                   11728:     if ($sortkey eq '') {
                   11729:         $sortkey = 'starttime';
                   11730:     }
1.780     raeburn  11731:     my @sorted;
                   11732:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11733:         @sorted =
                   11734:             sort {
                   11735:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11736:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11737:                      }
                   11738:                      if (ref($slots->{$a})) { return -1;}
                   11739:                      if (ref($slots->{$b})) { return 1;}
                   11740:                      return 0;
                   11741:                  } @{$slotsarr};
                   11742:     }
                   11743:     return @sorted;
                   11744: }
                   11745: 
1.1040    raeburn  11746: =pod
                   11747: 
                   11748: =item * get_future_slots()
                   11749: 
                   11750: Inputs:
                   11751: 
                   11752: =over 4
                   11753: 
                   11754: cnum - course number
                   11755: 
                   11756: cdom - course domain
                   11757: 
                   11758: now - current UNIX time
                   11759: 
                   11760: symb - optional symb
                   11761: 
                   11762: =back
                   11763: 
                   11764: Returns:
                   11765: 
                   11766: =over 4
                   11767: 
                   11768: sorted_reservable - ref to array of student_schedulable slots currently 
                   11769:                     reservable, ordered by end date of reservation period.
                   11770: 
                   11771: reservable_now - ref to hash of student_schedulable slots currently
                   11772:                  reservable.
                   11773: 
                   11774:     Keys in inner hash are:
                   11775:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11776:     (b) endreserve: end date of reservation period.
                   11777:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11778:         selected.
1.1040    raeburn  11779: 
                   11780: sorted_future - ref to array of student_schedulable slots reservable in
                   11781:                 the future, ordered by start date of reservation period.
                   11782: 
                   11783: future_reservable - ref to hash of student_schedulable slots reservable
                   11784:                     in the future.
                   11785: 
                   11786:     Keys in inner hash are:
                   11787:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11788:     (b) startreserve: start date of reservation period.
                   11789:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11790:         selected.
1.1040    raeburn  11791: 
                   11792: =back
                   11793: 
                   11794: =cut
                   11795: 
                   11796: sub get_future_slots {
                   11797:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11798:     my $map;
                   11799:     if ($symb) {
                   11800:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11801:     }
1.1040    raeburn  11802:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11803:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11804:     foreach my $slot (keys(%slots)) {
                   11805:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11806:         if ($symb) {
1.1229    raeburn  11807:             if ($slots{$slot}->{'symb'} ne '') {
                   11808:                 my $canuse;
                   11809:                 my %oksymbs;
                   11810:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11811:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11812:                 if ($oksymbs{$symb}) {
                   11813:                     $canuse = 1;
                   11814:                 } else {
                   11815:                     foreach my $item (@slotsymbs) {
                   11816:                         if ($item =~ /\.(page|sequence)$/) {
                   11817:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11818:                             if (($map ne '') && ($map eq $sloturl)) {
                   11819:                                 $canuse = 1;
                   11820:                                 last;
                   11821:                             }
                   11822:                         }
                   11823:                     }
                   11824:                 }
                   11825:                 next unless ($canuse);
                   11826:             }
1.1040    raeburn  11827:         }
                   11828:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11829:             ($slots{$slot}->{'endtime'} > $now)) {
                   11830:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11831:                 my $userallowed = 0;
                   11832:                 if ($slots{$slot}->{'allowedsections'}) {
                   11833:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11834:                     if (!defined($env{'request.role.sec'})
                   11835:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11836:                         $userallowed=1;
                   11837:                     } else {
                   11838:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11839:                             $userallowed=1;
                   11840:                         }
                   11841:                     }
                   11842:                     unless ($userallowed) {
                   11843:                         if (defined($env{'request.course.groups'})) {
                   11844:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11845:                             foreach my $group (@groups) {
                   11846:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11847:                                     $userallowed=1;
                   11848:                                     last;
                   11849:                                 }
                   11850:                             }
                   11851:                         }
                   11852:                     }
                   11853:                 }
                   11854:                 if ($slots{$slot}->{'allowedusers'}) {
                   11855:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11856:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11857:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11858:                         $userallowed = 1;
                   11859:                     }
                   11860:                 }
                   11861:                 next unless($userallowed);
                   11862:             }
                   11863:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11864:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11865:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11866:             my $uniqueperiod;
                   11867:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11868:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11869:             }
1.1040    raeburn  11870:             if (($startreserve < $now) &&
                   11871:                 (!$endreserve || $endreserve > $now)) {
                   11872:                 my $lastres = $endreserve;
                   11873:                 if (!$lastres) {
                   11874:                     $lastres = $slots{$slot}->{'starttime'};
                   11875:                 }
                   11876:                 $reservable_now{$slot} = {
                   11877:                                            symb       => $symb,
1.1250    raeburn  11878:                                            endreserve => $lastres,
                   11879:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11880:                                          };
                   11881:             } elsif (($startreserve > $now) &&
                   11882:                      (!$endreserve || $endreserve > $startreserve)) {
                   11883:                 $future_reservable{$slot} = {
                   11884:                                               symb         => $symb,
1.1250    raeburn  11885:                                               startreserve => $startreserve,
                   11886:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11887:                                             };
                   11888:             }
                   11889:         }
                   11890:     }
                   11891:     my @unsorted_reservable = keys(%reservable_now);
                   11892:     if (@unsorted_reservable > 0) {
                   11893:         @sorted_reservable = 
                   11894:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11895:     }
                   11896:     my @unsorted_future = keys(%future_reservable);
                   11897:     if (@unsorted_future > 0) {
                   11898:         @sorted_future =
                   11899:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11900:     }
                   11901:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11902: }
1.780     raeburn  11903: 
                   11904: =pod
                   11905: 
1.1057    foxr     11906: =back
                   11907: 
1.549     albertel 11908: =head1 HTTP Helpers
                   11909: 
                   11910: =over 4
                   11911: 
1.648     raeburn  11912: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11913: 
1.258     albertel 11914: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11915: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11916: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11917: 
                   11918: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11919: $possible_names is an ref to an array of form element names.  As an example:
                   11920: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11921: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11922: 
                   11923: =cut
1.1       albertel 11924: 
1.6       albertel 11925: sub get_unprocessed_cgi {
1.25      albertel 11926:   my ($query,$possible_names)= @_;
1.26      matthew  11927:   # $Apache::lonxml::debug=1;
1.356     albertel 11928:   foreach my $pair (split(/&/,$query)) {
                   11929:     my ($name, $value) = split(/=/,$pair);
1.369     www      11930:     $name = &unescape($name);
1.25      albertel 11931:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11932:       $value =~ tr/+/ /;
                   11933:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11934:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11935:     }
1.16      harris41 11936:   }
1.6       albertel 11937: }
                   11938: 
1.112     bowersj2 11939: =pod
                   11940: 
1.648     raeburn  11941: =item * &cacheheader() 
1.112     bowersj2 11942: 
                   11943: returns cache-controlling header code
                   11944: 
                   11945: =cut
                   11946: 
1.7       albertel 11947: sub cacheheader {
1.258     albertel 11948:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11949:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11950:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11951:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11952:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11953:     return $output;
1.7       albertel 11954: }
                   11955: 
1.112     bowersj2 11956: =pod
                   11957: 
1.648     raeburn  11958: =item * &no_cache($r) 
1.112     bowersj2 11959: 
                   11960: specifies header code to not have cache
                   11961: 
                   11962: =cut
                   11963: 
1.9       albertel 11964: sub no_cache {
1.216     albertel 11965:     my ($r) = @_;
                   11966:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11967: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11968:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11969:     $r->no_cache(1);
                   11970:     $r->header_out("Expires" => $date);
                   11971:     $r->header_out("Pragma" => "no-cache");
1.123     www      11972: }
                   11973: 
                   11974: sub content_type {
1.181     albertel 11975:     my ($r,$type,$charset) = @_;
1.299     foxr     11976:     if ($r) {
                   11977: 	#  Note that printout.pl calls this with undef for $r.
                   11978: 	&no_cache($r);
                   11979:     }
1.258     albertel 11980:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11981:     unless ($charset) {
                   11982: 	$charset=&Apache::lonlocal::current_encoding;
                   11983:     }
                   11984:     if ($charset) { $type.='; charset='.$charset; }
                   11985:     if ($r) {
                   11986: 	$r->content_type($type);
                   11987:     } else {
                   11988: 	print("Content-type: $type\n\n");
                   11989:     }
1.9       albertel 11990: }
1.25      albertel 11991: 
1.112     bowersj2 11992: =pod
                   11993: 
1.648     raeburn  11994: =item * &add_to_env($name,$value) 
1.112     bowersj2 11995: 
1.258     albertel 11996: adds $name to the %env hash with value
1.112     bowersj2 11997: $value, if $name already exists, the entry is converted to an array
                   11998: reference and $value is added to the array.
                   11999: 
                   12000: =cut
                   12001: 
1.25      albertel 12002: sub add_to_env {
                   12003:   my ($name,$value)=@_;
1.258     albertel 12004:   if (defined($env{$name})) {
                   12005:     if (ref($env{$name})) {
1.25      albertel 12006:       #already have multiple values
1.258     albertel 12007:       push(@{ $env{$name} },$value);
1.25      albertel 12008:     } else {
                   12009:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12010:       my $first=$env{$name};
                   12011:       undef($env{$name});
                   12012:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12013:     }
                   12014:   } else {
1.258     albertel 12015:     $env{$name}=$value;
1.25      albertel 12016:   }
1.31      albertel 12017: }
1.149     albertel 12018: 
                   12019: =pod
                   12020: 
1.648     raeburn  12021: =item * &get_env_multiple($name) 
1.149     albertel 12022: 
1.258     albertel 12023: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12024: values may be defined and end up as an array ref.
                   12025: 
                   12026: returns an array of values
                   12027: 
                   12028: =cut
                   12029: 
                   12030: sub get_env_multiple {
                   12031:     my ($name) = @_;
                   12032:     my @values;
1.258     albertel 12033:     if (defined($env{$name})) {
1.149     albertel 12034:         # exists is it an array
1.258     albertel 12035:         if (ref($env{$name})) {
                   12036:             @values=@{ $env{$name} };
1.149     albertel 12037:         } else {
1.258     albertel 12038:             $values[0]=$env{$name};
1.149     albertel 12039:         }
                   12040:     }
                   12041:     return(@values);
                   12042: }
                   12043: 
1.1249    damieng  12044: # Looks at given dependencies, and returns something depending on the context.
                   12045: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12046: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12047: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12048: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12049: # $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.
                   12050: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12051: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12052: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12053: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12054: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12055: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12056: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12057: # @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)
                   12058: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12059: sub ask_for_embedded_content {
1.1249    damieng  12060:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12061:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12062:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12063:         %currsubfile,%unused,$rem);
1.1071    raeburn  12064:     my $counter = 0;
                   12065:     my $numnew = 0;
1.987     raeburn  12066:     my $numremref = 0;
                   12067:     my $numinvalid = 0;
                   12068:     my $numpathchg = 0;
                   12069:     my $numexisting = 0;
1.1071    raeburn  12070:     my $numunused = 0;
                   12071:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12072:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12073:     my $heading = &mt('Upload embedded files');
                   12074:     my $buttontext = &mt('Upload');
                   12075: 
1.1249    damieng  12076:     # fills these variables based on the context:
                   12077:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12078:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12079:     if ($env{'request.course.id'}) {
1.1123    raeburn  12080:         if ($actionurl eq '/adm/dependencies') {
                   12081:             $navmap = Apache::lonnavmaps::navmap->new();
                   12082:         }
                   12083:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12084:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12085:     }
1.1123    raeburn  12086:     if (($actionurl eq '/adm/portfolio') || 
                   12087:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12088:         my $current_path='/';
                   12089:         if ($env{'form.currentpath'}) {
                   12090:             $current_path = $env{'form.currentpath'};
                   12091:         }
                   12092:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12093:             $udom = $cdom;
                   12094:             $uname = $cnum;
1.984     raeburn  12095:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12096:         } else {
                   12097:             $udom = $env{'user.domain'};
                   12098:             $uname = $env{'user.name'};
                   12099:             $url = '/userfiles/portfolio';
                   12100:         }
1.987     raeburn  12101:         $toplevel = $url.'/';
1.984     raeburn  12102:         $url .= $current_path;
                   12103:         $getpropath = 1;
1.987     raeburn  12104:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12105:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12106:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12107:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12108:         $toplevel = $url;
1.984     raeburn  12109:         if ($rest ne '') {
1.987     raeburn  12110:             $url .= $rest;
                   12111:         }
                   12112:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12113:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12114:             $url = $args->{'docs_url'};
                   12115:             $toplevel = $url;
1.1084    raeburn  12116:             if ($args->{'context'} eq 'paste') {
                   12117:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12118:                 ($path) = 
                   12119:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12120:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12121:                 $fileloc =~ s{^/}{};
                   12122:             }
1.1071    raeburn  12123:         }
1.1084    raeburn  12124:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12125:         if ($env{'request.course.id'} ne '') {
                   12126:             if (ref($args) eq 'HASH') {
                   12127:                 $url = $args->{'docs_url'};
                   12128:                 $title = $args->{'docs_title'};
1.1126    raeburn  12129:                 $toplevel = $url; 
                   12130:                 unless ($toplevel =~ m{^/}) {
                   12131:                     $toplevel = "/$url";
                   12132:                 }
1.1085    raeburn  12133:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12134:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12135:                     $path = $1;
                   12136:                 } else {
                   12137:                     ($path) =
                   12138:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12139:                 }
1.1195    raeburn  12140:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12141:                     $fileloc = $toplevel;
                   12142:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12143:                     my ($udom,$uname,$fname) =
                   12144:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12145:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12146:                 } else {
                   12147:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12148:                 }
1.1071    raeburn  12149:                 $fileloc =~ s{^/}{};
                   12150:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12151:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12152:             }
1.987     raeburn  12153:         }
1.1123    raeburn  12154:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12155:         $udom = $cdom;
                   12156:         $uname = $cnum;
                   12157:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12158:         $toplevel = $url;
                   12159:         $path = $url;
                   12160:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12161:         $fileloc =~ s{^/}{};
1.987     raeburn  12162:     }
1.1249    damieng  12163:     
                   12164:     # parses the dependency paths to get some info
                   12165:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12166:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12167:     # (will be completed later)
                   12168:     # $mapping:
                   12169:     #   for external URLs: external URL -> external URL
                   12170:     #   for relative paths: clean path -> original path
                   12171:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12172:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12173:     foreach my $file (keys(%{$allfiles})) {
                   12174:         my $embed_file;
                   12175:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12176:             $embed_file = $1;
                   12177:         } else {
                   12178:             $embed_file = $file;
                   12179:         }
1.1158    raeburn  12180:         my ($absolutepath,$cleaned_file);
                   12181:         if ($embed_file =~ m{^\w+://}) {
                   12182:             $cleaned_file = $embed_file;
1.1147    raeburn  12183:             $newfiles{$cleaned_file} = 1;
                   12184:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12185:         } else {
1.1158    raeburn  12186:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12187:             if ($embed_file =~ m{^/}) {
                   12188:                 $absolutepath = $embed_file;
                   12189:             }
1.1147    raeburn  12190:             if ($cleaned_file =~ m{/}) {
                   12191:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12192:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12193:                 my $item = $fname;
                   12194:                 if ($path ne '') {
                   12195:                     $item = $path.'/'.$fname;
                   12196:                     $subdependencies{$path}{$fname} = 1;
                   12197:                 } else {
                   12198:                     $dependencies{$item} = 1;
                   12199:                 }
                   12200:                 if ($absolutepath) {
                   12201:                     $mapping{$item} = $absolutepath;
                   12202:                 } else {
                   12203:                     $mapping{$item} = $embed_file;
                   12204:                 }
                   12205:             } else {
                   12206:                 $dependencies{$embed_file} = 1;
                   12207:                 if ($absolutepath) {
1.1147    raeburn  12208:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12209:                 } else {
1.1147    raeburn  12210:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12211:                 }
                   12212:             }
1.984     raeburn  12213:         }
                   12214:     }
1.1249    damieng  12215:     
                   12216:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12217:     # and lists
                   12218:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12219:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12220:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12221:     #                                    the path had to be cleaned up
                   12222:     # $existing: hash clean path -> 1 if the file exists
                   12223:     # $numexisting: number of keys in $existing
                   12224:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12225:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12226:     #                                      dependency subdirectories that are
                   12227:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12228:     my $dirptr = 16384;
1.984     raeburn  12229:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12230:         $currsubfile{$path} = {};
1.1123    raeburn  12231:         if (($actionurl eq '/adm/portfolio') || 
                   12232:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12233:             my ($sublistref,$listerror) =
                   12234:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12235:             if (ref($sublistref) eq 'ARRAY') {
                   12236:                 foreach my $line (@{$sublistref}) {
                   12237:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12238:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12239:                 }
1.984     raeburn  12240:             }
1.987     raeburn  12241:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12242:             if (opendir(my $dir,$url.'/'.$path)) {
                   12243:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12244:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12245:             }
1.1084    raeburn  12246:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12247:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12248:                   ($args->{'context'} eq 'paste')) ||
                   12249:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12250:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12251:                 my $dir;
                   12252:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12253:                     $dir = $fileloc;
                   12254:                 } else {
                   12255:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12256:                 }
1.1071    raeburn  12257:                 if ($dir ne '') {
                   12258:                     my ($sublistref,$listerror) =
                   12259:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12260:                     if (ref($sublistref) eq 'ARRAY') {
                   12261:                         foreach my $line (@{$sublistref}) {
                   12262:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12263:                                 undef,$mtime)=split(/\&/,$line,12);
                   12264:                             unless (($testdir&$dirptr) ||
                   12265:                                     ($file_name =~ /^\.\.?$/)) {
                   12266:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12267:                             }
                   12268:                         }
                   12269:                     }
                   12270:                 }
1.984     raeburn  12271:             }
                   12272:         }
                   12273:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12274:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12275:                 my $item = $path.'/'.$file;
                   12276:                 unless ($mapping{$item} eq $item) {
                   12277:                     $pathchanges{$item} = 1;
                   12278:                 }
                   12279:                 $existing{$item} = 1;
                   12280:                 $numexisting ++;
                   12281:             } else {
                   12282:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12283:             }
                   12284:         }
1.1071    raeburn  12285:         if ($actionurl eq '/adm/dependencies') {
                   12286:             foreach my $path (keys(%currsubfile)) {
                   12287:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12288:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12289:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12290:                              next if (($rem ne '') &&
                   12291:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12292:                                        (ref($navmap) &&
                   12293:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12294:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12295:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12296:                              $unused{$path.'/'.$file} = 1; 
                   12297:                          }
                   12298:                     }
                   12299:                 }
                   12300:             }
                   12301:         }
1.984     raeburn  12302:     }
1.1249    damieng  12303:     
                   12304:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12305:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12306:     my %currfile;
1.1123    raeburn  12307:     if (($actionurl eq '/adm/portfolio') ||
                   12308:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12309:         my ($dirlistref,$listerror) =
                   12310:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12311:         if (ref($dirlistref) eq 'ARRAY') {
                   12312:             foreach my $line (@{$dirlistref}) {
                   12313:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12314:                 $currfile{$file_name} = 1;
                   12315:             }
1.984     raeburn  12316:         }
1.987     raeburn  12317:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12318:         if (opendir(my $dir,$url)) {
1.987     raeburn  12319:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12320:             map {$currfile{$_} = 1;} @dir_list;
                   12321:         }
1.1084    raeburn  12322:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12323:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12324:               ($args->{'context'} eq 'paste')) ||
                   12325:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12326:         if ($env{'request.course.id'} ne '') {
                   12327:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12328:             if ($dir ne '') {
                   12329:                 my ($dirlistref,$listerror) =
                   12330:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12331:                 if (ref($dirlistref) eq 'ARRAY') {
                   12332:                     foreach my $line (@{$dirlistref}) {
                   12333:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12334:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12335:                         unless (($testdir&$dirptr) ||
                   12336:                                 ($file_name =~ /^\.\.?$/)) {
                   12337:                             $currfile{$file_name} = [$size,$mtime];
                   12338:                         }
                   12339:                     }
                   12340:                 }
                   12341:             }
                   12342:         }
1.984     raeburn  12343:     }
1.1249    damieng  12344:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12345:     # are not in subdirectories, using $currfile
1.984     raeburn  12346:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12347:         if (exists($currfile{$file})) {
1.987     raeburn  12348:             unless ($mapping{$file} eq $file) {
                   12349:                 $pathchanges{$file} = 1;
                   12350:             }
                   12351:             $existing{$file} = 1;
                   12352:             $numexisting ++;
                   12353:         } else {
1.984     raeburn  12354:             $newfiles{$file} = 1;
                   12355:         }
                   12356:     }
1.1071    raeburn  12357:     foreach my $file (keys(%currfile)) {
                   12358:         unless (($file eq $filename) ||
                   12359:                 ($file eq $filename.'.bak') ||
                   12360:                 ($dependencies{$file})) {
1.1085    raeburn  12361:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12362:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12363:                     next if (($rem ne '') &&
                   12364:                              (($env{"httpref.$rem".$file} ne '') ||
                   12365:                               (ref($navmap) &&
                   12366:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12367:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12368:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12369:                 }
1.1085    raeburn  12370:             }
1.1071    raeburn  12371:             $unused{$file} = 1;
                   12372:         }
                   12373:     }
1.1249    damieng  12374:     
                   12375:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12376:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12377:         ($args->{'context'} eq 'paste')) {
                   12378:         $counter = scalar(keys(%existing));
                   12379:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12380:         return ($output,$counter,$numpathchg,\%existing);
                   12381:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12382:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12383:         $counter = scalar(keys(%existing));
                   12384:         $numpathchg = scalar(keys(%pathchanges));
                   12385:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12386:     }
1.1249    damieng  12387:     
                   12388:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12389:     
                   12390:     # $upload_output: missing dependencies (with upload form)
                   12391:     # $modify_output: uploaded dependencies (in use)
                   12392:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12393:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12394:         if ($actionurl eq '/adm/dependencies') {
                   12395:             next if ($embed_file =~ m{^\w+://});
                   12396:         }
1.660     raeburn  12397:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12398:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12399:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12400:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12401:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12402:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12403:         }
1.1123    raeburn  12404:         $upload_output .= '</td>';
1.1071    raeburn  12405:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12406:             $upload_output.='<td align="right">'.
                   12407:                             '<span class="LC_info LC_fontsize_medium">'.
                   12408:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12409:             $numremref++;
1.660     raeburn  12410:         } elsif ($args->{'error_on_invalid_names'}
                   12411:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12412:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12413:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12414:             $numinvalid++;
1.660     raeburn  12415:         } else {
1.1123    raeburn  12416:             $upload_output .= '<td>'.
                   12417:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12418:                                                      $embed_file,\%mapping,
1.1071    raeburn  12419:                                                      $allfiles,$codebase,'upload');
                   12420:             $counter ++;
                   12421:             $numnew ++;
1.987     raeburn  12422:         }
                   12423:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12424:     }
                   12425:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12426:         if ($actionurl eq '/adm/dependencies') {
                   12427:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12428:             $modify_output .= &start_data_table_row().
                   12429:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12430:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12431:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12432:                               '<td>'.$size.'</td>'.
                   12433:                               '<td>'.$mtime.'</td>'.
                   12434:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12435:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12436:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12437:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12438:                               &embedded_file_element('upload_embedded',$counter,
                   12439:                                                      $embed_file,\%mapping,
                   12440:                                                      $allfiles,$codebase,'modify').
                   12441:                               '</div></td>'.
                   12442:                               &end_data_table_row()."\n";
                   12443:             $counter ++;
                   12444:         } else {
                   12445:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12446:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12447:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12448:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12449:                               &Apache::loncommon::end_data_table_row()."\n";
                   12450:         }
                   12451:     }
                   12452:     my $delidx = $counter;
                   12453:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12454:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12455:         $delete_output .= &start_data_table_row().
                   12456:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12457:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12458:                           '<td>'.$size.'</td>'.
                   12459:                           '<td>'.$mtime.'</td>'.
                   12460:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12461:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12462:                           &embedded_file_element('upload_embedded',$delidx,
                   12463:                                                  $oldfile,\%mapping,$allfiles,
                   12464:                                                  $codebase,'delete').'</td>'.
                   12465:                           &end_data_table_row()."\n"; 
                   12466:         $numunused ++;
                   12467:         $delidx ++;
1.987     raeburn  12468:     }
                   12469:     if ($upload_output) {
                   12470:         $upload_output = &start_data_table().
                   12471:                          $upload_output.
                   12472:                          &end_data_table()."\n";
                   12473:     }
1.1071    raeburn  12474:     if ($modify_output) {
                   12475:         $modify_output = &start_data_table().
                   12476:                          &start_data_table_header_row().
                   12477:                          '<th>'.&mt('File').'</th>'.
                   12478:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12479:                          '<th>'.&mt('Modified').'</th>'.
                   12480:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12481:                          &end_data_table_header_row().
                   12482:                          $modify_output.
                   12483:                          &end_data_table()."\n";
                   12484:     }
                   12485:     if ($delete_output) {
                   12486:         $delete_output = &start_data_table().
                   12487:                          &start_data_table_header_row().
                   12488:                          '<th>'.&mt('File').'</th>'.
                   12489:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12490:                          '<th>'.&mt('Modified').'</th>'.
                   12491:                          '<th>'.&mt('Delete?').'</th>'.
                   12492:                          &end_data_table_header_row().
                   12493:                          $delete_output.
                   12494:                          &end_data_table()."\n";
                   12495:     }
1.987     raeburn  12496:     my $applies = 0;
                   12497:     if ($numremref) {
                   12498:         $applies ++;
                   12499:     }
                   12500:     if ($numinvalid) {
                   12501:         $applies ++;
                   12502:     }
                   12503:     if ($numexisting) {
                   12504:         $applies ++;
                   12505:     }
1.1071    raeburn  12506:     if ($counter || $numunused) {
1.987     raeburn  12507:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12508:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12509:                   $state.'<h3>'.$heading.'</h3>'; 
                   12510:         if ($actionurl eq '/adm/dependencies') {
                   12511:             if ($numnew) {
                   12512:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12513:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12514:                            $upload_output.'<br />'."\n";
                   12515:             }
                   12516:             if ($numexisting) {
                   12517:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12518:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12519:                            $modify_output.'<br />'."\n";
                   12520:                            $buttontext = &mt('Save changes');
                   12521:             }
                   12522:             if ($numunused) {
                   12523:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12524:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12525:                            $delete_output.'<br />'."\n";
                   12526:                            $buttontext = &mt('Save changes');
                   12527:             }
                   12528:         } else {
                   12529:             $output .= $upload_output.'<br />'."\n";
                   12530:         }
                   12531:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12532:                    $counter.'" />'."\n";
                   12533:         if ($actionurl eq '/adm/dependencies') { 
                   12534:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12535:                        $numnew.'" />'."\n";
                   12536:         } elsif ($actionurl eq '') {
1.987     raeburn  12537:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12538:         }
                   12539:     } elsif ($applies) {
                   12540:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12541:         if ($applies > 1) {
                   12542:             $output .=  
1.1123    raeburn  12543:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12544:             if ($numremref) {
                   12545:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12546:             }
                   12547:             if ($numinvalid) {
                   12548:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12549:             }
                   12550:             if ($numexisting) {
                   12551:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12552:             }
                   12553:             $output .= '</ul><br />';
                   12554:         } elsif ($numremref) {
                   12555:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12556:         } elsif ($numinvalid) {
                   12557:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12558:         } elsif ($numexisting) {
                   12559:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12560:         }
                   12561:         $output .= $upload_output.'<br />';
                   12562:     }
                   12563:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12564:     $chgcount = $counter;
1.987     raeburn  12565:     if (keys(%pathchanges) > 0) {
                   12566:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12567:             if ($counter) {
1.987     raeburn  12568:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12569:                                                   $embed_file,\%mapping,
1.1071    raeburn  12570:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12571:             } else {
                   12572:                 $pathchange_output .= 
                   12573:                     &start_data_table_row().
                   12574:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12575:                     $chgcount.'" checked="checked" /></td>'.
                   12576:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12577:                     '<td>'.$embed_file.
                   12578:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12579:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12580:                     '</td>'.&end_data_table_row();
1.660     raeburn  12581:             }
1.987     raeburn  12582:             $numpathchg ++;
                   12583:             $chgcount ++;
1.660     raeburn  12584:         }
                   12585:     }
1.1127    raeburn  12586:     if (($counter) || ($numunused)) {
1.987     raeburn  12587:         if ($numpathchg) {
                   12588:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12589:                        $numpathchg.'" />'."\n";
                   12590:         }
                   12591:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12592:             ($actionurl eq '/adm/imsimport')) {
                   12593:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12594:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12595:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12596:         } elsif ($actionurl eq '/adm/dependencies') {
                   12597:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12598:         }
1.1123    raeburn  12599:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12600:     } elsif ($numpathchg) {
                   12601:         my %pathchange = ();
                   12602:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12603:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12604:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12605:         }
1.987     raeburn  12606:     }
1.1071    raeburn  12607:     return ($output,$counter,$numpathchg);
1.987     raeburn  12608: }
                   12609: 
1.1147    raeburn  12610: =pod
                   12611: 
                   12612: =item * clean_path($name)
                   12613: 
                   12614: Performs clean-up of directories, subdirectories and filename in an
                   12615: embedded object, referenced in an HTML file which is being uploaded
                   12616: to a course or portfolio, where 
                   12617: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12618: checked.
                   12619: 
                   12620: Clean-up is similar to replacements in lonnet::clean_filename()
                   12621: except each / between sub-directory and next level is preserved.
                   12622: 
                   12623: =cut
                   12624: 
                   12625: sub clean_path {
                   12626:     my ($embed_file) = @_;
                   12627:     $embed_file =~s{^/+}{};
                   12628:     my @contents;
                   12629:     if ($embed_file =~ m{/}) {
                   12630:         @contents = split(/\//,$embed_file);
                   12631:     } else {
                   12632:         @contents = ($embed_file);
                   12633:     }
                   12634:     my $lastidx = scalar(@contents)-1;
                   12635:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12636:         $contents[$i]=~s{\\}{/}g;
                   12637:         $contents[$i]=~s/\s+/\_/g;
                   12638:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12639:         if ($i == $lastidx) {
                   12640:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12641:         }
                   12642:     }
                   12643:     if ($lastidx > 0) {
                   12644:         return join('/',@contents);
                   12645:     } else {
                   12646:         return $contents[0];
                   12647:     }
                   12648: }
                   12649: 
1.987     raeburn  12650: sub embedded_file_element {
1.1071    raeburn  12651:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12652:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12653:                    (ref($codebase) eq 'HASH'));
                   12654:     my $output;
1.1071    raeburn  12655:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12656:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12657:     }
                   12658:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12659:                &escape($embed_file).'" />';
                   12660:     unless (($context eq 'upload_embedded') && 
                   12661:             ($mapping->{$embed_file} eq $embed_file)) {
                   12662:         $output .='
                   12663:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12664:     }
                   12665:     my $attrib;
                   12666:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12667:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12668:     }
                   12669:     $output .=
                   12670:         "\n\t\t".
                   12671:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12672:         $attrib.'" />';
                   12673:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12674:         $output .=
                   12675:             "\n\t\t".
                   12676:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12677:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12678:     }
1.987     raeburn  12679:     return $output;
1.660     raeburn  12680: }
                   12681: 
1.1071    raeburn  12682: sub get_dependency_details {
                   12683:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12684:     my ($size,$mtime,$showsize,$showmtime);
                   12685:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12686:         if ($embed_file =~ m{/}) {
                   12687:             my ($path,$fname) = split(/\//,$embed_file);
                   12688:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12689:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12690:             }
                   12691:         } else {
                   12692:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12693:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12694:             }
                   12695:         }
                   12696:         $showsize = $size/1024.0;
                   12697:         $showsize = sprintf("%.1f",$showsize);
                   12698:         if ($mtime > 0) {
                   12699:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12700:         }
                   12701:     }
                   12702:     return ($showsize,$showmtime);
                   12703: }
                   12704: 
                   12705: sub ask_embedded_js {
                   12706:     return <<"END";
                   12707: <script type="text/javascript"">
                   12708: // <![CDATA[
                   12709: function toggleBrowse(counter) {
                   12710:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12711:     var fileid = document.getElementById('embedded_item_'+counter);
                   12712:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12713:     if (chkboxid.checked == true) {
                   12714:         uploaddivid.style.display='block';
                   12715:     } else {
                   12716:         uploaddivid.style.display='none';
                   12717:         fileid.value = '';
                   12718:     }
                   12719: }
                   12720: // ]]>
                   12721: </script>
                   12722: 
                   12723: END
                   12724: }
                   12725: 
1.661     raeburn  12726: sub upload_embedded {
                   12727:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12728:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12729:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12730:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12731:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12732:         my $orig_uploaded_filename =
                   12733:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12734:         foreach my $type ('orig','ref','attrib','codebase') {
                   12735:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12736:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12737:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12738:             }
                   12739:         }
1.661     raeburn  12740:         my ($path,$fname) =
                   12741:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12742:         # no path, whole string is fname
                   12743:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12744:         $fname = &Apache::lonnet::clean_filename($fname);
                   12745:         # See if there is anything left
                   12746:         next if ($fname eq '');
                   12747: 
                   12748:         # Check if file already exists as a file or directory.
                   12749:         my ($state,$msg);
                   12750:         if ($context eq 'portfolio') {
                   12751:             my $port_path = $dirpath;
                   12752:             if ($group ne '') {
                   12753:                 $port_path = "groups/$group/$port_path";
                   12754:             }
1.987     raeburn  12755:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12756:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12757:                                               $dir_root,$port_path,$disk_quota,
                   12758:                                               $current_disk_usage,$uname,$udom);
                   12759:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12760:                 || $state eq 'file_locked') {
1.661     raeburn  12761:                 $output .= $msg;
                   12762:                 next;
                   12763:             }
                   12764:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12765:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12766:             if ($state eq 'exists') {
                   12767:                 $output .= $msg;
                   12768:                 next;
                   12769:             }
                   12770:         }
                   12771:         # Check if extension is valid
                   12772:         if (($fname =~ /\.(\w+)$/) &&
                   12773:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12774:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12775:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12776:             next;
                   12777:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12778:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12779:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12780:             next;
                   12781:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12782:             $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  12783:             next;
                   12784:         }
                   12785:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12786:         my $subdir = $path;
                   12787:         $subdir =~ s{/+$}{};
1.661     raeburn  12788:         if ($context eq 'portfolio') {
1.984     raeburn  12789:             my $result;
                   12790:             if ($state eq 'existingfile') {
                   12791:                 $result=
                   12792:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12793:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12794:             } else {
1.984     raeburn  12795:                 $result=
                   12796:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12797:                                                     $dirpath.
1.1123    raeburn  12798:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12799:                 if ($result !~ m|^/uploaded/|) {
                   12800:                     $output .= '<span class="LC_error">'
                   12801:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12802:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12803:                                .'</span><br />';
                   12804:                     next;
                   12805:                 } else {
1.987     raeburn  12806:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12807:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12808:                 }
1.661     raeburn  12809:             }
1.1123    raeburn  12810:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12811:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12812:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12813:             my $result =
1.1126    raeburn  12814:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12815:             if ($result !~ m|^/uploaded/|) {
                   12816:                 $output .= '<span class="LC_error">'
                   12817:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12818:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12819:                            .'</span><br />';
                   12820:                     next;
                   12821:             } else {
                   12822:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12823:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12824:                 if ($context eq 'syllabus') {
                   12825:                     &Apache::lonnet::make_public_indefinitely($result);
                   12826:                 }
1.987     raeburn  12827:             }
1.661     raeburn  12828:         } else {
                   12829: # Save the file
                   12830:             my $target = $env{'form.embedded_item_'.$i};
                   12831:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12832:             my $dest = $fullpath.$fname;
                   12833:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12834:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12835:             my $count;
                   12836:             my $filepath = $dir_root;
1.1027    raeburn  12837:             foreach my $subdir (@parts) {
                   12838:                 $filepath .= "/$subdir";
                   12839:                 if (!-e $filepath) {
1.661     raeburn  12840:                     mkdir($filepath,0770);
                   12841:                 }
                   12842:             }
                   12843:             my $fh;
                   12844:             if (!open($fh,'>'.$dest)) {
                   12845:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12846:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12847:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12848:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12849:                            '</span><br />';
                   12850:             } else {
                   12851:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12852:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12853:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12854:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12855:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12856:                               '</span><br />';
                   12857:                 } else {
1.987     raeburn  12858:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12859:                                $url.'</span>').'<br />';
                   12860:                     unless ($context eq 'testbank') {
                   12861:                         $footer .= &mt('View embedded file: [_1]',
                   12862:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12863:                     }
                   12864:                 }
                   12865:                 close($fh);
                   12866:             }
                   12867:         }
                   12868:         if ($env{'form.embedded_ref_'.$i}) {
                   12869:             $pathchange{$i} = 1;
                   12870:         }
                   12871:     }
                   12872:     if ($output) {
                   12873:         $output = '<p>'.$output.'</p>';
                   12874:     }
                   12875:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12876:     $returnflag = 'ok';
1.1071    raeburn  12877:     my $numpathchgs = scalar(keys(%pathchange));
                   12878:     if ($numpathchgs > 0) {
1.987     raeburn  12879:         if ($context eq 'portfolio') {
                   12880:             $output .= '<p>'.&mt('or').'</p>';
                   12881:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12882:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12883:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12884:             $returnflag = 'modify_orightml';
                   12885:         }
                   12886:     }
1.1071    raeburn  12887:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12888: }
                   12889: 
                   12890: sub modify_html_form {
                   12891:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12892:     my $end = 0;
                   12893:     my $modifyform;
                   12894:     if ($context eq 'upload_embedded') {
                   12895:         return unless (ref($pathchange) eq 'HASH');
                   12896:         if ($env{'form.number_embedded_items'}) {
                   12897:             $end += $env{'form.number_embedded_items'};
                   12898:         }
                   12899:         if ($env{'form.number_pathchange_items'}) {
                   12900:             $end += $env{'form.number_pathchange_items'};
                   12901:         }
                   12902:         if ($end) {
                   12903:             for (my $i=0; $i<$end; $i++) {
                   12904:                 if ($i < $env{'form.number_embedded_items'}) {
                   12905:                     next unless($pathchange->{$i});
                   12906:                 }
                   12907:                 $modifyform .=
                   12908:                     &start_data_table_row().
                   12909:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12910:                     'checked="checked" /></td>'.
                   12911:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12912:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12913:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12914:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12915:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12916:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12917:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12918:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12919:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12920:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12921:                     &end_data_table_row();
1.1071    raeburn  12922:             }
1.987     raeburn  12923:         }
                   12924:     } else {
                   12925:         $modifyform = $pathchgtable;
                   12926:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12927:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12928:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12929:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12930:         }
                   12931:     }
                   12932:     if ($modifyform) {
1.1071    raeburn  12933:         if ($actionurl eq '/adm/dependencies') {
                   12934:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12935:         }
1.987     raeburn  12936:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12937:                '<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".
                   12938:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12939:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12940:                '</ol></p>'."\n".'<p>'.
                   12941:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12942:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12943:                &start_data_table()."\n".
                   12944:                &start_data_table_header_row().
                   12945:                '<th>'.&mt('Change?').'</th>'.
                   12946:                '<th>'.&mt('Current reference').'</th>'.
                   12947:                '<th>'.&mt('Required reference').'</th>'.
                   12948:                &end_data_table_header_row()."\n".
                   12949:                $modifyform.
                   12950:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12951:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12952:                '</form>'."\n";
                   12953:     }
                   12954:     return;
                   12955: }
                   12956: 
                   12957: sub modify_html_refs {
1.1123    raeburn  12958:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12959:     my $container;
                   12960:     if ($context eq 'portfolio') {
                   12961:         $container = $env{'form.container'};
                   12962:     } elsif ($context eq 'coursedoc') {
                   12963:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12964:     } elsif ($context eq 'manage_dependencies') {
                   12965:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12966:         $container = "/$container";
1.1123    raeburn  12967:     } elsif ($context eq 'syllabus') {
                   12968:         $container = $url;
1.987     raeburn  12969:     } else {
1.1027    raeburn  12970:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12971:     }
                   12972:     my (%allfiles,%codebase,$output,$content);
                   12973:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12974:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12975:         if (wantarray) {
                   12976:             return ('',0,0); 
                   12977:         } else {
                   12978:             return;
                   12979:         }
                   12980:     }
                   12981:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12982:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12983:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12984:             if (wantarray) {
                   12985:                 return ('',0,0);
                   12986:             } else {
                   12987:                 return;
                   12988:             }
                   12989:         } 
1.987     raeburn  12990:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12991:         if ($content eq '-1') {
                   12992:             if (wantarray) {
                   12993:                 return ('',0,0);
                   12994:             } else {
                   12995:                 return;
                   12996:             }
                   12997:         }
1.987     raeburn  12998:     } else {
1.1071    raeburn  12999:         unless ($container =~ /^\Q$dir_root\E/) {
                   13000:             if (wantarray) {
                   13001:                 return ('',0,0);
                   13002:             } else {
                   13003:                 return;
                   13004:             }
                   13005:         } 
1.1317    raeburn  13006:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13007:             $content = join('', <$fh>);
                   13008:             close($fh);
                   13009:         } else {
1.1071    raeburn  13010:             if (wantarray) {
                   13011:                 return ('',0,0);
                   13012:             } else {
                   13013:                 return;
                   13014:             }
1.987     raeburn  13015:         }
                   13016:     }
                   13017:     my ($count,$codebasecount) = (0,0);
                   13018:     my $mm = new File::MMagic;
                   13019:     my $mime_type = $mm->checktype_contents($content);
                   13020:     if ($mime_type eq 'text/html') {
                   13021:         my $parse_result = 
                   13022:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13023:                                                     \%codebase,\$content);
                   13024:         if ($parse_result eq 'ok') {
                   13025:             foreach my $i (@changes) {
                   13026:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13027:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13028:                 if ($allfiles{$ref}) {
                   13029:                     my $newname =  $orig;
                   13030:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13031:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13032:                     if ($attrib_regexp =~ /:/) {
                   13033:                         $attrib_regexp =~ s/\:/|/g;
                   13034:                     }
                   13035:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13036:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13037:                         $count += $numchg;
1.1123    raeburn  13038:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13039:                         delete($allfiles{$ref});
1.987     raeburn  13040:                     }
                   13041:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13042:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13043:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13044:                         $codebasecount ++;
                   13045:                     }
                   13046:                 }
                   13047:             }
1.1123    raeburn  13048:             my $skiprewrites;
1.987     raeburn  13049:             if ($count || $codebasecount) {
                   13050:                 my $saveresult;
1.1071    raeburn  13051:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13052:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13053:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13054:                     if ($url eq $container) {
                   13055:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13056:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13057:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13058:                                             $fname.'</span>').'</p>';
1.987     raeburn  13059:                     } else {
                   13060:                          $output = '<p class="LC_error">'.
                   13061:                                    &mt('Error: update failed for: [_1].',
                   13062:                                    '<span class="LC_filename">'.
                   13063:                                    $container.'</span>').'</p>';
                   13064:                     }
1.1123    raeburn  13065:                     if ($context eq 'syllabus') {
                   13066:                         unless ($saveresult eq 'ok') {
                   13067:                             $skiprewrites = 1;
                   13068:                         }
                   13069:                     }
1.987     raeburn  13070:                 } else {
1.1317    raeburn  13071:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13072:                         print $fh $content;
                   13073:                         close($fh);
                   13074:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13075:                                   $count,'<span class="LC_filename">'.
                   13076:                                   $container.'</span>').'</p>';
1.661     raeburn  13077:                     } else {
1.987     raeburn  13078:                          $output = '<p class="LC_error">'.
                   13079:                                    &mt('Error: could not update [_1].',
                   13080:                                    '<span class="LC_filename">'.
                   13081:                                    $container.'</span>').'</p>';
1.661     raeburn  13082:                     }
                   13083:                 }
                   13084:             }
1.1123    raeburn  13085:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13086:                 my ($actionurl,$state);
                   13087:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13088:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13089:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13090:                                               \%codebase,
                   13091:                                               {'context' => 'rewrites',
                   13092:                                                'ignore_remote_references' => 1,});
                   13093:                 if (ref($mapping) eq 'HASH') {
                   13094:                     my $rewrites = 0;
                   13095:                     foreach my $key (keys(%{$mapping})) {
                   13096:                         next if ($key =~ m{^https?://});
                   13097:                         my $ref = $mapping->{$key};
                   13098:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13099:                         my $attrib;
                   13100:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13101:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13102:                         }
                   13103:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13104:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13105:                             $rewrites += $numchg;
                   13106:                         }
                   13107:                     }
                   13108:                     if ($rewrites) {
                   13109:                         my $saveresult; 
                   13110:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13111:                         if ($url eq $container) {
                   13112:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13113:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13114:                                             $count,'<span class="LC_filename">'.
                   13115:                                             $fname.'</span>').'</p>';
                   13116:                         } else {
                   13117:                             $output .= '<p class="LC_error">'.
                   13118:                                        &mt('Error: could not update links in [_1].',
                   13119:                                        '<span class="LC_filename">'.
                   13120:                                        $container.'</span>').'</p>';
                   13121: 
                   13122:                         }
                   13123:                     }
                   13124:                 }
                   13125:             }
1.987     raeburn  13126:         } else {
                   13127:             &logthis('Failed to parse '.$container.
                   13128:                      ' to modify references: '.$parse_result);
1.661     raeburn  13129:         }
                   13130:     }
1.1071    raeburn  13131:     if (wantarray) {
                   13132:         return ($output,$count,$codebasecount);
                   13133:     } else {
                   13134:         return $output;
                   13135:     }
1.661     raeburn  13136: }
                   13137: 
                   13138: sub check_for_existing {
                   13139:     my ($path,$fname,$element) = @_;
                   13140:     my ($state,$msg);
                   13141:     if (-d $path.'/'.$fname) {
                   13142:         $state = 'exists';
                   13143:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13144:     } elsif (-e $path.'/'.$fname) {
                   13145:         $state = 'exists';
                   13146:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13147:     }
                   13148:     if ($state eq 'exists') {
                   13149:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13150:     }
                   13151:     return ($state,$msg);
                   13152: }
                   13153: 
                   13154: sub check_for_upload {
                   13155:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13156:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13157:     my $filesize = length($env{'form.'.$element});
                   13158:     if (!$filesize) {
                   13159:         my $msg = '<span class="LC_error">'.
                   13160:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13161:                       '<span class="LC_filename">'.$fname.'</span>',
                   13162:                       $filesize).'<br />'.
1.1007    raeburn  13163:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13164:                   '</span>';
                   13165:         return ('zero_bytes',$msg);
                   13166:     }
                   13167:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13168:     my $getpropath = 1;
1.1021    raeburn  13169:     my ($dirlistref,$listerror) =
                   13170:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13171:     my $found_file = 0;
                   13172:     my $locked_file = 0;
1.991     raeburn  13173:     my @lockers;
                   13174:     my $navmap;
                   13175:     if ($env{'request.course.id'}) {
                   13176:         $navmap = Apache::lonnavmaps::navmap->new();
                   13177:     }
1.1021    raeburn  13178:     if (ref($dirlistref) eq 'ARRAY') {
                   13179:         foreach my $line (@{$dirlistref}) {
                   13180:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13181:             if ($file_name eq $fname){
                   13182:                 $file_name = $path.$file_name;
                   13183:                 if ($group ne '') {
                   13184:                     $file_name = $group.$file_name;
                   13185:                 }
                   13186:                 $found_file = 1;
                   13187:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13188:                     foreach my $lock (@lockers) {
                   13189:                         if (ref($lock) eq 'ARRAY') {
                   13190:                             my ($symb,$crsid) = @{$lock};
                   13191:                             if ($crsid eq $env{'request.course.id'}) {
                   13192:                                 if (ref($navmap)) {
                   13193:                                     my $res = $navmap->getBySymb($symb);
                   13194:                                     foreach my $part (@{$res->parts()}) { 
                   13195:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13196:                                         unless (($slot_status == $res->RESERVED) ||
                   13197:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13198:                                             $locked_file = 1;
                   13199:                                         }
1.991     raeburn  13200:                                     }
1.1021    raeburn  13201:                                 } else {
                   13202:                                     $locked_file = 1;
1.991     raeburn  13203:                                 }
                   13204:                             } else {
                   13205:                                 $locked_file = 1;
                   13206:                             }
                   13207:                         }
1.1021    raeburn  13208:                    }
                   13209:                 } else {
                   13210:                     my @info = split(/\&/,$rest);
                   13211:                     my $currsize = $info[6]/1000;
                   13212:                     if ($currsize < $filesize) {
                   13213:                         my $extra = $filesize - $currsize;
                   13214:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13215:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13216:                                       &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   13217:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13218:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13219:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13220:                             return ('will_exceed_quota',$msg);
                   13221:                         }
1.984     raeburn  13222:                     }
                   13223:                 }
1.661     raeburn  13224:             }
                   13225:         }
                   13226:     }
                   13227:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13228:         my $msg = '<p class="LC_warning">'.
                   13229:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13230:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13231:         return ('will_exceed_quota',$msg);
                   13232:     } elsif ($found_file) {
                   13233:         if ($locked_file) {
1.1179    bisitz   13234:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13235:             $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   13236:             $msg .= '</p>';
1.661     raeburn  13237:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13238:             return ('file_locked',$msg);
                   13239:         } else {
1.1179    bisitz   13240:             my $msg = '<p class="LC_error">';
1.984     raeburn  13241:             $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   13242:             $msg .= '</p>';
1.984     raeburn  13243:             return ('existingfile',$msg);
1.661     raeburn  13244:         }
                   13245:     }
                   13246: }
                   13247: 
1.987     raeburn  13248: sub check_for_traversal {
                   13249:     my ($path,$url,$toplevel) = @_;
                   13250:     my @parts=split(/\//,$path);
                   13251:     my $cleanpath;
                   13252:     my $fullpath = $url;
                   13253:     for (my $i=0;$i<@parts;$i++) {
                   13254:         next if ($parts[$i] eq '.');
                   13255:         if ($parts[$i] eq '..') {
                   13256:             $fullpath =~ s{([^/]+/)$}{};
                   13257:         } else {
                   13258:             $fullpath .= $parts[$i].'/';
                   13259:         }
                   13260:     }
                   13261:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13262:         $cleanpath = $1;
                   13263:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13264:         my $curr_toprel = $1;
                   13265:         my @parts = split(/\//,$curr_toprel);
                   13266:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13267:         my @urlparts = split(/\//,$url_toprel);
                   13268:         my $doubledots;
                   13269:         my $startdiff = -1;
                   13270:         for (my $i=0; $i<@urlparts; $i++) {
                   13271:             if ($startdiff == -1) {
                   13272:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13273:                     $startdiff = $i;
                   13274:                     $doubledots .= '../';
                   13275:                 }
                   13276:             } else {
                   13277:                 $doubledots .= '../';
                   13278:             }
                   13279:         }
                   13280:         if ($startdiff > -1) {
                   13281:             $cleanpath = $doubledots;
                   13282:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13283:                 $cleanpath .= $parts[$i].'/';
                   13284:             }
                   13285:         }
                   13286:     }
                   13287:     $cleanpath =~ s{(/)$}{};
                   13288:     return $cleanpath;
                   13289: }
1.31      albertel 13290: 
1.1053    raeburn  13291: sub is_archive_file {
                   13292:     my ($mimetype) = @_;
                   13293:     if (($mimetype eq 'application/octet-stream') ||
                   13294:         ($mimetype eq 'application/x-stuffit') ||
                   13295:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13296:         return 1;
                   13297:     }
                   13298:     return;
                   13299: }
                   13300: 
                   13301: sub decompress_form {
1.1065    raeburn  13302:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13303:     my %lt = &Apache::lonlocal::texthash (
                   13304:         this => 'This file is an archive file.',
1.1067    raeburn  13305:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13306:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13307:         youm => 'You may wish to extract its contents.',
                   13308:         extr => 'Extract contents',
1.1067    raeburn  13309:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13310:         proa => 'Process automatically?',
1.1053    raeburn  13311:         yes  => 'Yes',
                   13312:         no   => 'No',
1.1067    raeburn  13313:         fold => 'Title for folder containing movie',
                   13314:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13315:     );
1.1065    raeburn  13316:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13317:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13318:     my $info = &list_archive_contents($fileloc,\@paths);
                   13319:     if (@paths) {
                   13320:         foreach my $path (@paths) {
                   13321:             $path =~ s{^/}{};
1.1067    raeburn  13322:             if ($path =~ m{^([^/]+)/$}) {
                   13323:                 $topdir = $1;
                   13324:             }
1.1065    raeburn  13325:             if ($path =~ m{^([^/]+)/}) {
                   13326:                 $toplevel{$1} = $path;
                   13327:             } else {
                   13328:                 $toplevel{$path} = $path;
                   13329:             }
                   13330:         }
                   13331:     }
1.1067    raeburn  13332:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13333:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13334:                         "$topdir/media/",
                   13335:                         "$topdir/media/$topdir.mp4",
                   13336:                         "$topdir/media/FirstFrame.png",
                   13337:                         "$topdir/media/player.swf",
                   13338:                         "$topdir/media/swfobject.js",
                   13339:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13340:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13341:                          "$topdir/$topdir.mp4",
                   13342:                          "$topdir/$topdir\_config.xml",
                   13343:                          "$topdir/$topdir\_controller.swf",
                   13344:                          "$topdir/$topdir\_embed.css",
                   13345:                          "$topdir/$topdir\_First_Frame.png",
                   13346:                          "$topdir/$topdir\_player.html",
                   13347:                          "$topdir/$topdir\_Thumbnails.png",
                   13348:                          "$topdir/playerProductInstall.swf",
                   13349:                          "$topdir/scripts/",
                   13350:                          "$topdir/scripts/config_xml.js",
                   13351:                          "$topdir/scripts/handlebars.js",
                   13352:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13353:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13354:                          "$topdir/scripts/modernizr.js",
                   13355:                          "$topdir/scripts/player-min.js",
                   13356:                          "$topdir/scripts/swfobject.js",
                   13357:                          "$topdir/skins/",
                   13358:                          "$topdir/skins/configuration_express.xml",
                   13359:                          "$topdir/skins/express_show/",
                   13360:                          "$topdir/skins/express_show/player-min.css",
                   13361:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13362:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13363:                          "$topdir/$topdir.mp4",
                   13364:                          "$topdir/$topdir\_config.xml",
                   13365:                          "$topdir/$topdir\_controller.swf",
                   13366:                          "$topdir/$topdir\_embed.css",
                   13367:                          "$topdir/$topdir\_First_Frame.png",
                   13368:                          "$topdir/$topdir\_player.html",
                   13369:                          "$topdir/$topdir\_Thumbnails.png",
                   13370:                          "$topdir/playerProductInstall.swf",
                   13371:                          "$topdir/scripts/",
                   13372:                          "$topdir/scripts/config_xml.js",
                   13373:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13374:                          "$topdir/skins/",
                   13375:                          "$topdir/skins/configuration_express.xml",
                   13376:                          "$topdir/skins/express_show/",
                   13377:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13378:                          "$topdir/skins/express_show/spritesheet.png",
                   13379:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13380:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13381:         if (@diffs == 0) {
1.1164    raeburn  13382:             $is_camtasia = 6;
                   13383:         } else {
1.1197    raeburn  13384:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13385:             if (@diffs == 0) {
                   13386:                 $is_camtasia = 8;
1.1197    raeburn  13387:             } else {
                   13388:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13389:                 if (@diffs == 0) {
                   13390:                     $is_camtasia = 8;
                   13391:                 }
1.1164    raeburn  13392:             }
1.1067    raeburn  13393:         }
                   13394:     }
                   13395:     my $output;
                   13396:     if ($is_camtasia) {
                   13397:         $output = <<"ENDCAM";
                   13398: <script type="text/javascript" language="Javascript">
                   13399: // <![CDATA[
                   13400: 
                   13401: function camtasiaToggle() {
                   13402:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13403:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13404:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13405:                 document.getElementById('camtasia_titles').style.display='block';
                   13406:             } else {
                   13407:                 document.getElementById('camtasia_titles').style.display='none';
                   13408:             }
                   13409:         }
                   13410:     }
                   13411:     return;
                   13412: }
                   13413: 
                   13414: // ]]>
                   13415: </script>
                   13416: <p>$lt{'camt'}</p>
                   13417: ENDCAM
1.1065    raeburn  13418:     } else {
1.1067    raeburn  13419:         $output = '<p>'.$lt{'this'};
                   13420:         if ($info eq '') {
                   13421:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13422:         } else {
                   13423:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13424:                        '<div><pre>'.$info.'</pre></div>';
                   13425:         }
1.1065    raeburn  13426:     }
1.1067    raeburn  13427:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13428:     my $duplicates;
                   13429:     my $num = 0;
                   13430:     if (ref($dirlist) eq 'ARRAY') {
                   13431:         foreach my $item (@{$dirlist}) {
                   13432:             if (ref($item) eq 'ARRAY') {
                   13433:                 if (exists($toplevel{$item->[0]})) {
                   13434:                     $duplicates .= 
                   13435:                         &start_data_table_row().
                   13436:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13437:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13438:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13439:                         'value="1" />'.&mt('Yes').'</label>'.
                   13440:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13441:                         '<td>'.$item->[0].'</td>';
                   13442:                     if ($item->[2]) {
                   13443:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13444:                     } else {
                   13445:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13446:                     }
                   13447:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13448:                                    '<td>'.
                   13449:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13450:                                    '</td>'.
                   13451:                                    &end_data_table_row();
                   13452:                     $num ++;
                   13453:                 }
                   13454:             }
                   13455:         }
                   13456:     }
                   13457:     my $itemcount;
                   13458:     if (@paths > 0) {
                   13459:         $itemcount = scalar(@paths);
                   13460:     } else {
                   13461:         $itemcount = 1;
                   13462:     }
1.1067    raeburn  13463:     if ($is_camtasia) {
                   13464:         $output .= $lt{'auto'}.'<br />'.
                   13465:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13466:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13467:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13468:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13469:                    $lt{'no'}.'</label></span><br />'.
                   13470:                    '<div id="camtasia_titles" style="display:block">'.
                   13471:                    &Apache::lonhtmlcommon::start_pick_box().
                   13472:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13473:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13474:                    &Apache::lonhtmlcommon::row_closure().
                   13475:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13476:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13477:                    &Apache::lonhtmlcommon::row_closure(1).
                   13478:                    &Apache::lonhtmlcommon::end_pick_box().
                   13479:                    '</div>';
                   13480:     }
1.1065    raeburn  13481:     $output .= 
                   13482:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13483:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13484:         "\n";
1.1065    raeburn  13485:     if ($duplicates ne '') {
                   13486:         $output .= '<p><span class="LC_warning">'.
                   13487:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13488:                    &start_data_table().
                   13489:                    &start_data_table_header_row().
                   13490:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13491:                    '<th>'.&mt('Name').'</th>'.
                   13492:                    '<th>'.&mt('Type').'</th>'.
                   13493:                    '<th>'.&mt('Size').'</th>'.
                   13494:                    '<th>'.&mt('Last modified').'</th>'.
                   13495:                    &end_data_table_header_row().
                   13496:                    $duplicates.
                   13497:                    &end_data_table().
                   13498:                    '</p>';
                   13499:     }
1.1067    raeburn  13500:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13501:     if (ref($hiddenelements) eq 'HASH') {
                   13502:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13503:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13504:         }
                   13505:     }
                   13506:     $output .= <<"END";
1.1067    raeburn  13507: <br />
1.1053    raeburn  13508: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13509: </form>
                   13510: $noextract
                   13511: END
                   13512:     return $output;
                   13513: }
                   13514: 
1.1065    raeburn  13515: sub decompression_utility {
                   13516:     my ($program) = @_;
                   13517:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13518:     my $location;
                   13519:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13520:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13521:                          '/usr/sbin/') {
                   13522:             if (-x $dir.$program) {
                   13523:                 $location = $dir.$program;
                   13524:                 last;
                   13525:             }
                   13526:         }
                   13527:     }
                   13528:     return $location;
                   13529: }
                   13530: 
                   13531: sub list_archive_contents {
                   13532:     my ($file,$pathsref) = @_;
                   13533:     my (@cmd,$output);
                   13534:     my $needsregexp;
                   13535:     if ($file =~ /\.zip$/) {
                   13536:         @cmd = (&decompression_utility('unzip'),"-l");
                   13537:         $needsregexp = 1;
                   13538:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13539:              ($file =~ /\.tgz$/)) {
                   13540:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13541:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13542:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13543:     } elsif ($file =~ m|\.tar$|) {
                   13544:         @cmd = (&decompression_utility('tar'),"-tf");
                   13545:     }
                   13546:     if (@cmd) {
                   13547:         undef($!);
                   13548:         undef($@);
                   13549:         if (open(my $fh,"-|", @cmd, $file)) {
                   13550:             while (my $line = <$fh>) {
                   13551:                 $output .= $line;
                   13552:                 chomp($line);
                   13553:                 my $item;
                   13554:                 if ($needsregexp) {
                   13555:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13556:                 } else {
                   13557:                     $item = $line;
                   13558:                 }
                   13559:                 if ($item ne '') {
                   13560:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13561:                         push(@{$pathsref},$item);
                   13562:                     } 
                   13563:                 }
                   13564:             }
                   13565:             close($fh);
                   13566:         }
                   13567:     }
                   13568:     return $output;
                   13569: }
                   13570: 
1.1053    raeburn  13571: sub decompress_uploaded_file {
                   13572:     my ($file,$dir) = @_;
                   13573:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13574:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13575:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13576:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13577:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13578:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13579:     my $decompressed = $env{'cgi.decompressed'};
                   13580:     &Apache::lonnet::delenv('cgi.file');
                   13581:     &Apache::lonnet::delenv('cgi.dir');
                   13582:     &Apache::lonnet::delenv('cgi.decompressed');
                   13583:     return ($decompressed,$result);
                   13584: }
                   13585: 
1.1055    raeburn  13586: sub process_decompression {
                   13587:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13588:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13589:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13590:                &mt('Unexpected file path.').'</p>'."\n";
                   13591:     }
                   13592:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13593:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13594:                &mt('Unexpected course context.').'</p>'."\n";
                   13595:     }
1.1293    raeburn  13596:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13597:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13598:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13599:     }
1.1055    raeburn  13600:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13601:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13602:         $error = &mt('Filename not a supported archive file type.').
                   13603:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13604:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13605:     } else {
                   13606:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13607:         if ($docuhome eq 'no_host') {
                   13608:             $error = &mt('Could not determine home server for course.');
                   13609:         } else {
                   13610:             my @ids=&Apache::lonnet::current_machine_ids();
                   13611:             my $currdir = "$dir_root/$destination";
                   13612:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13613:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13614:                        "$dir_root/$destination";
                   13615:             } else {
                   13616:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13617:                        "$dir_root/$docudom/$docuname/$destination";
                   13618:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13619:                     $error = &mt('Archive file not found.');
                   13620:                 }
                   13621:             }
1.1065    raeburn  13622:             my (@to_overwrite,@to_skip);
                   13623:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13624:                 my $total = $env{'form.archive_overwrite_total'};
                   13625:                 for (my $i=0; $i<$total; $i++) {
                   13626:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13627:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13628:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13629:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13630:                     }
                   13631:                 }
                   13632:             }
                   13633:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13634:             my $numoverwrite = scalar(@to_overwrite);
                   13635:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13636:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13637:             } elsif ($dir eq '') {
1.1055    raeburn  13638:                 $error = &mt('Directory containing archive file unavailable.');
                   13639:             } elsif (!$error) {
1.1065    raeburn  13640:                 my ($decompressed,$display);
1.1292    raeburn  13641:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13642:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13643:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13644:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13645:                         ($decompressed,$display) = 
                   13646:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13647:                         foreach my $item (@to_skip) {
                   13648:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13649:                                 if (-f "$dir/$tempdir/$item") { 
                   13650:                                     unlink("$dir/$tempdir/$item");
                   13651:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13652:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13653:                                 }
                   13654:                             }
                   13655:                         }
                   13656:                         foreach my $item (@to_overwrite) {
                   13657:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13658:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13659:                                     if (-f "$dir/$item") {
                   13660:                                         unlink("$dir/$item");
                   13661:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13662:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13663:                                     }
                   13664:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13665:                                 }
1.1065    raeburn  13666:                             }
                   13667:                         }
1.1292    raeburn  13668:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13669:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13670:                         }
1.1065    raeburn  13671:                     }
                   13672:                 } else {
                   13673:                     ($decompressed,$display) = 
                   13674:                         &decompress_uploaded_file($file,$dir);
                   13675:                 }
1.1055    raeburn  13676:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13677:                     $output = '<p class="LC_info">'.
                   13678:                               &mt('Files extracted successfully from archive.').
                   13679:                               '</p>'."\n";
1.1055    raeburn  13680:                     my ($warning,$result,@contents);
                   13681:                     my ($newdirlistref,$newlisterror) =
                   13682:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13683:                                                  $docuname,1);
                   13684:                     my (%is_dir,%changes,@newitems);
                   13685:                     my $dirptr = 16384;
1.1065    raeburn  13686:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13687:                         foreach my $dir_line (@{$newdirlistref}) {
                   13688:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13689:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13690:                                 push(@newitems,$item);
                   13691:                                 if ($dirptr&$testdir) {
                   13692:                                     $is_dir{$item} = 1;
                   13693:                                 }
                   13694:                                 $changes{$item} = 1;
                   13695:                             }
                   13696:                         }
                   13697:                     }
                   13698:                     if (keys(%changes) > 0) {
                   13699:                         foreach my $item (sort(@newitems)) {
                   13700:                             if ($changes{$item}) {
                   13701:                                 push(@contents,$item);
                   13702:                             }
                   13703:                         }
                   13704:                     }
                   13705:                     if (@contents > 0) {
1.1067    raeburn  13706:                         my $wantform;
                   13707:                         unless ($env{'form.autoextract_camtasia'}) {
                   13708:                             $wantform = 1;
                   13709:                         }
1.1056    raeburn  13710:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13711:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13712:                                                                 $currdir,\%is_dir,
                   13713:                                                                 \%children,\%parent,
1.1056    raeburn  13714:                                                                 \@contents,\%dirorder,
                   13715:                                                                 \%titles,$wantform);
1.1055    raeburn  13716:                         if ($datatable ne '') {
                   13717:                             $output .= &archive_options_form('decompressed',$datatable,
                   13718:                                                              $count,$hiddenelem);
1.1065    raeburn  13719:                             my $startcount = 6;
1.1055    raeburn  13720:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13721:                                                            \%titles,\%children);
1.1055    raeburn  13722:                         }
1.1067    raeburn  13723:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13724:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13725:                             my %displayed;
                   13726:                             my $total = 1;
                   13727:                             $env{'form.archive_directory'} = [];
                   13728:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13729:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13730:                                 $path =~ s{/$}{};
                   13731:                                 my $item;
                   13732:                                 if ($path ne '') {
                   13733:                                     $item = "$path/$titles{$i}";
                   13734:                                 } else {
                   13735:                                     $item = $titles{$i};
                   13736:                                 }
                   13737:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13738:                                 if ($item eq $contents[0]) {
                   13739:                                     push(@{$env{'form.archive_directory'}},$i);
                   13740:                                     $env{'form.archive_'.$i} = 'display';
                   13741:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13742:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13743:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13744:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13745:                                     $env{'form.archive_'.$i} = 'display';
                   13746:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13747:                                     $displayed{'web'} = $i;
                   13748:                                 } else {
1.1164    raeburn  13749:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13750:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13751:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13752:                                         push(@{$env{'form.archive_directory'}},$i);
                   13753:                                     }
                   13754:                                     $env{'form.archive_'.$i} = 'dependency';
                   13755:                                 }
                   13756:                                 $total ++;
                   13757:                             }
                   13758:                             for (my $i=1; $i<$total; $i++) {
                   13759:                                 next if ($i == $displayed{'web'});
                   13760:                                 next if ($i == $displayed{'folder'});
                   13761:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13762:                             }
                   13763:                             $env{'form.phase'} = 'decompress_cleanup';
                   13764:                             $env{'form.archivedelete'} = 1;
                   13765:                             $env{'form.archive_count'} = $total-1;
                   13766:                             $output .=
                   13767:                                 &process_extracted_files('coursedocs',$docudom,
                   13768:                                                          $docuname,$destination,
                   13769:                                                          $dir_root,$hiddenelem);
                   13770:                         }
1.1055    raeburn  13771:                     } else {
                   13772:                         $warning = &mt('No new items extracted from archive file.');
                   13773:                     }
                   13774:                 } else {
                   13775:                     $output = $display;
                   13776:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13777:                 }
                   13778:             }
                   13779:         }
                   13780:     }
                   13781:     if ($error) {
                   13782:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13783:                    $error.'</p>'."\n";
                   13784:     }
                   13785:     if ($warning) {
                   13786:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13787:     }
                   13788:     return $output;
                   13789: }
                   13790: 
                   13791: sub get_extracted {
1.1056    raeburn  13792:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13793:         $titles,$wantform) = @_;
1.1055    raeburn  13794:     my $count = 0;
                   13795:     my $depth = 0;
                   13796:     my $datatable;
1.1056    raeburn  13797:     my @hierarchy;
1.1055    raeburn  13798:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13799:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13800:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13801:     foreach my $item (@{$contents}) {
                   13802:         $count ++;
1.1056    raeburn  13803:         @{$dirorder->{$count}} = @hierarchy;
                   13804:         $titles->{$count} = $item;
1.1055    raeburn  13805:         &archive_hierarchy($depth,$count,$parent,$children);
                   13806:         if ($wantform) {
                   13807:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13808:                                        $currdir,$depth,$count);
                   13809:         }
                   13810:         if ($is_dir->{$item}) {
                   13811:             $depth ++;
1.1056    raeburn  13812:             push(@hierarchy,$count);
                   13813:             $parent->{$depth} = $count;
1.1055    raeburn  13814:             $datatable .=
                   13815:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13816:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13817:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13818:             $depth --;
1.1056    raeburn  13819:             pop(@hierarchy);
1.1055    raeburn  13820:         }
                   13821:     }
                   13822:     return ($count,$datatable);
                   13823: }
                   13824: 
                   13825: sub recurse_extracted_archive {
1.1056    raeburn  13826:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13827:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13828:     my $result='';
1.1056    raeburn  13829:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13830:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13831:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13832:         return $result;
                   13833:     }
                   13834:     my $dirptr = 16384;
                   13835:     my ($newdirlistref,$newlisterror) =
                   13836:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13837:     if (ref($newdirlistref) eq 'ARRAY') {
                   13838:         foreach my $dir_line (@{$newdirlistref}) {
                   13839:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13840:             unless ($item =~ /^\.+$/) {
                   13841:                 $$count ++;
1.1056    raeburn  13842:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13843:                 $titles->{$$count} = $item;
1.1055    raeburn  13844:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13845: 
1.1055    raeburn  13846:                 my $is_dir;
                   13847:                 if ($dirptr&$testdir) {
                   13848:                     $is_dir = 1;
                   13849:                 }
                   13850:                 if ($wantform) {
                   13851:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13852:                 }
                   13853:                 if ($is_dir) {
                   13854:                     $$depth ++;
1.1056    raeburn  13855:                     push(@{$hierarchy},$$count);
                   13856:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13857:                     $result .=
                   13858:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13859:                                                    $docuname,$depth,$count,
1.1056    raeburn  13860:                                                    $hierarchy,$dirorder,$children,
                   13861:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13862:                     $$depth --;
1.1056    raeburn  13863:                     pop(@{$hierarchy});
1.1055    raeburn  13864:                 }
                   13865:             }
                   13866:         }
                   13867:     }
                   13868:     return $result;
                   13869: }
                   13870: 
                   13871: sub archive_hierarchy {
                   13872:     my ($depth,$count,$parent,$children) =@_;
                   13873:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13874:         if (exists($parent->{$depth})) {
                   13875:              $children->{$parent->{$depth}} .= $count.':';
                   13876:         }
                   13877:     }
                   13878:     return;
                   13879: }
                   13880: 
                   13881: sub archive_row {
                   13882:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13883:     my ($name) = ($item =~ m{([^/]+)$});
                   13884:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13885:                                        'display'    => 'Add as file',
1.1055    raeburn  13886:                                        'dependency' => 'Include as dependency',
                   13887:                                        'discard'    => 'Discard',
                   13888:                                       );
                   13889:     if ($is_dir) {
1.1059    raeburn  13890:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13891:     }
1.1056    raeburn  13892:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13893:     my $offset = 0;
1.1055    raeburn  13894:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13895:         $offset ++;
1.1065    raeburn  13896:         if ($action ne 'display') {
                   13897:             $offset ++;
                   13898:         }  
1.1055    raeburn  13899:         $output .= '<td><span class="LC_nobreak">'.
                   13900:                    '<label><input type="radio" name="archive_'.$count.
                   13901:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13902:         my $text = $choices{$action};
                   13903:         if ($is_dir) {
                   13904:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13905:             if ($action eq 'display') {
1.1059    raeburn  13906:                 $text = &mt('Add as folder');
1.1055    raeburn  13907:             }
1.1056    raeburn  13908:         } else {
                   13909:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13910: 
                   13911:         }
                   13912:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13913:         if ($action eq 'dependency') {
                   13914:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13915:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13916:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13917:                        '<option value=""></option>'."\n".
                   13918:                        '</select>'."\n".
                   13919:                        '</div>';
1.1059    raeburn  13920:         } elsif ($action eq 'display') {
                   13921:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13922:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13923:                        '</div>';
1.1055    raeburn  13924:         }
1.1056    raeburn  13925:         $output .= '</td>';
1.1055    raeburn  13926:     }
                   13927:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13928:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13929:     for (my $i=0; $i<$depth; $i++) {
                   13930:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13931:     }
                   13932:     if ($is_dir) {
                   13933:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13934:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13935:     } else {
                   13936:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13937:     }
                   13938:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13939:                &end_data_table_row();
                   13940:     return $output;
                   13941: }
                   13942: 
                   13943: sub archive_options_form {
1.1065    raeburn  13944:     my ($form,$display,$count,$hiddenelem) = @_;
                   13945:     my %lt = &Apache::lonlocal::texthash(
                   13946:                perm => 'Permanently remove archive file?',
                   13947:                hows => 'How should each extracted item be incorporated in the course?',
                   13948:                cont => 'Content actions for all',
                   13949:                addf => 'Add as folder/file',
                   13950:                incd => 'Include as dependency for a displayed file',
                   13951:                disc => 'Discard',
                   13952:                no   => 'No',
                   13953:                yes  => 'Yes',
                   13954:                save => 'Save',
                   13955:     );
                   13956:     my $output = <<"END";
                   13957: <form name="$form" method="post" action="">
                   13958: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13959: <label>
                   13960:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13961: </label>
                   13962: &nbsp;
                   13963: <label>
                   13964:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13965: </span>
                   13966: </p>
                   13967: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13968: <br />$lt{'hows'}
                   13969: <div class="LC_columnSection">
                   13970:   <fieldset>
                   13971:     <legend>$lt{'cont'}</legend>
                   13972:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13973:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13974:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13975:   </fieldset>
                   13976: </div>
                   13977: END
                   13978:     return $output.
1.1055    raeburn  13979:            &start_data_table()."\n".
1.1065    raeburn  13980:            $display."\n".
1.1055    raeburn  13981:            &end_data_table()."\n".
                   13982:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13983:            $hiddenelem.
1.1065    raeburn  13984:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13985:            '</form>';
                   13986: }
                   13987: 
                   13988: sub archive_javascript {
1.1056    raeburn  13989:     my ($startcount,$numitems,$titles,$children) = @_;
                   13990:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13991:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13992:     my $scripttag = <<START;
                   13993: <script type="text/javascript">
                   13994: // <![CDATA[
                   13995: 
                   13996: function checkAll(form,prefix) {
                   13997:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13998:     for (var i=0; i < form.elements.length; i++) {
                   13999:         var id = form.elements[i].id;
                   14000:         if ((id != '') && (id != undefined)) {
                   14001:             if (idstr.test(id)) {
                   14002:                 if (form.elements[i].type == 'radio') {
                   14003:                     form.elements[i].checked = true;
1.1056    raeburn  14004:                     var nostart = i-$startcount;
1.1059    raeburn  14005:                     var offset = nostart%7;
                   14006:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14007:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14008:                 }
                   14009:             }
                   14010:         }
                   14011:     }
                   14012: }
                   14013: 
                   14014: function propagateCheck(form,count) {
                   14015:     if (count > 0) {
1.1059    raeburn  14016:         var startelement = $startcount + ((count-1) * 7);
                   14017:         for (var j=1; j<6; j++) {
                   14018:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14019:                 var item = startelement + j; 
                   14020:                 if (form.elements[item].type == 'radio') {
                   14021:                     if (form.elements[item].checked) {
                   14022:                         containerCheck(form,count,j);
                   14023:                         break;
                   14024:                     }
1.1055    raeburn  14025:                 }
                   14026:             }
                   14027:         }
                   14028:     }
                   14029: }
                   14030: 
                   14031: numitems = $numitems
1.1056    raeburn  14032: var titles = new Array(numitems);
                   14033: var parents = new Array(numitems);
1.1055    raeburn  14034: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14035:     parents[i] = new Array;
1.1055    raeburn  14036: }
1.1059    raeburn  14037: var maintitle = '$maintitle';
1.1055    raeburn  14038: 
                   14039: START
                   14040: 
1.1056    raeburn  14041:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14042:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14043:         for (my $i=0; $i<@contents; $i ++) {
                   14044:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14045:         }
                   14046:     }
                   14047: 
1.1056    raeburn  14048:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14049:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14050:     }
                   14051: 
1.1055    raeburn  14052:     $scripttag .= <<END;
                   14053: 
                   14054: function containerCheck(form,count,offset) {
                   14055:     if (count > 0) {
1.1056    raeburn  14056:         dependencyCheck(form,count,offset);
1.1059    raeburn  14057:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14058:         form.elements[item].checked = true;
                   14059:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14060:             if (parents[count].length > 0) {
                   14061:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14062:                     containerCheck(form,parents[count][j],offset);
                   14063:                 }
                   14064:             }
                   14065:         }
                   14066:     }
                   14067: }
                   14068: 
                   14069: function dependencyCheck(form,count,offset) {
                   14070:     if (count > 0) {
1.1059    raeburn  14071:         var chosen = (offset+$startcount)+7*(count-1);
                   14072:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14073:         var currtype = form.elements[depitem].type;
                   14074:         if (form.elements[chosen].value == 'dependency') {
                   14075:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14076:             form.elements[depitem].options.length = 0;
                   14077:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14078:             for (var i=1; i<=numitems; i++) {
                   14079:                 if (i == count) {
                   14080:                     continue;
                   14081:                 }
1.1059    raeburn  14082:                 var startelement = $startcount + (i-1) * 7;
                   14083:                 for (var j=1; j<6; j++) {
                   14084:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14085:                         var item = startelement + j;
                   14086:                         if (form.elements[item].type == 'radio') {
                   14087:                             if (form.elements[item].checked) {
                   14088:                                 if (form.elements[item].value == 'display') {
                   14089:                                     var n = form.elements[depitem].options.length;
                   14090:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14091:                                 }
                   14092:                             }
                   14093:                         }
                   14094:                     }
                   14095:                 }
                   14096:             }
                   14097:         } else {
                   14098:             document.getElementById('arc_depon_'+count).style.display='none';
                   14099:             form.elements[depitem].options.length = 0;
                   14100:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14101:         }
1.1059    raeburn  14102:         titleCheck(form,count,offset);
1.1056    raeburn  14103:     }
                   14104: }
                   14105: 
                   14106: function propagateSelect(form,count,offset) {
                   14107:     if (count > 0) {
1.1065    raeburn  14108:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14109:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14110:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14111:             if (parents[count].length > 0) {
                   14112:                 for (var j=0; j<parents[count].length; j++) {
                   14113:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14114:                 }
                   14115:             }
                   14116:         }
                   14117:     }
                   14118: }
1.1056    raeburn  14119: 
                   14120: function containerSelect(form,count,offset,picked) {
                   14121:     if (count > 0) {
1.1065    raeburn  14122:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14123:         if (form.elements[item].type == 'radio') {
                   14124:             if (form.elements[item].value == 'dependency') {
                   14125:                 if (form.elements[item+1].type == 'select-one') {
                   14126:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14127:                         if (form.elements[item+1].options[i].value == picked) {
                   14128:                             form.elements[item+1].selectedIndex = i;
                   14129:                             break;
                   14130:                         }
                   14131:                     }
                   14132:                 }
                   14133:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14134:                     if (parents[count].length > 0) {
                   14135:                         for (var j=0; j<parents[count].length; j++) {
                   14136:                             containerSelect(form,parents[count][j],offset,picked);
                   14137:                         }
                   14138:                     }
                   14139:                 }
                   14140:             }
                   14141:         }
                   14142:     }
                   14143: }
                   14144: 
1.1059    raeburn  14145: function titleCheck(form,count,offset) {
                   14146:     if (count > 0) {
                   14147:         var chosen = (offset+$startcount)+7*(count-1);
                   14148:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14149:         var currtype = form.elements[depitem].type;
                   14150:         if (form.elements[chosen].value == 'display') {
                   14151:             document.getElementById('arc_title_'+count).style.display='block';
                   14152:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14153:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14154:             }
                   14155:         } else {
                   14156:             document.getElementById('arc_title_'+count).style.display='none';
                   14157:             if (currtype == 'text') { 
                   14158:                 document.getElementById('archive_title_'+count).value='';
                   14159:             }
                   14160:         }
                   14161:     }
                   14162:     return;
                   14163: }
                   14164: 
1.1055    raeburn  14165: // ]]>
                   14166: </script>
                   14167: END
                   14168:     return $scripttag;
                   14169: }
                   14170: 
                   14171: sub process_extracted_files {
1.1067    raeburn  14172:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14173:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14174:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14175:     my @ids=&Apache::lonnet::current_machine_ids();
                   14176:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14177:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14178:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14179:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14180:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14181:         $pathtocheck = "$dir_root/$destination";
                   14182:         $dir = $dir_root;
                   14183:         $ishome = 1;
                   14184:     } else {
                   14185:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14186:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14187:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14188:     }
                   14189:     my $currdir = "$dir_root/$destination";
                   14190:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14191:     if ($env{'form.folderpath'}) {
                   14192:         my @items = split('&',$env{'form.folderpath'});
                   14193:         $folders{'0'} = $items[-2];
1.1099    raeburn  14194:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14195:             $containers{'0'}='page';
                   14196:         } else {  
                   14197:             $containers{'0'}='sequence';
                   14198:         }
1.1055    raeburn  14199:     }
                   14200:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14201:     if ($numitems) {
                   14202:         for (my $i=1; $i<=$numitems; $i++) {
                   14203:             my $path = $env{'form.archive_content_'.$i};
                   14204:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14205:                 my $item = $1;
                   14206:                 $toplevelitems{$item} = $i;
                   14207:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14208:                     $is_dir{$item} = 1;
                   14209:                 }
                   14210:             }
                   14211:         }
                   14212:     }
1.1067    raeburn  14213:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14214:     if (keys(%toplevelitems) > 0) {
                   14215:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14216:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14217:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14218:     }
1.1066    raeburn  14219:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14220:     if ($numitems) {
                   14221:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14222:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14223:             my $path = $env{'form.archive_content_'.$i};
                   14224:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14225:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14226:                     if ($prefix ne '' && $path ne '') {
                   14227:                         if (-e $prefix.$path) {
1.1066    raeburn  14228:                             if ((@archdirs > 0) && 
                   14229:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14230:                                 $todeletedir{$prefix.$path} = 1;
                   14231:                             } else {
                   14232:                                 $todelete{$prefix.$path} = 1;
                   14233:                             }
1.1055    raeburn  14234:                         }
                   14235:                     }
                   14236:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14237:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14238:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14239:                     $docstitle = $env{'form.archive_title_'.$i};
                   14240:                     if ($docstitle eq '') {
                   14241:                         $docstitle = $title;
                   14242:                     }
1.1055    raeburn  14243:                     $outer = 0;
1.1056    raeburn  14244:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14245:                         if (@{$dirorder{$i}} > 0) {
                   14246:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14247:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14248:                                     $outer = $item;
                   14249:                                     last;
                   14250:                                 }
                   14251:                             }
                   14252:                         }
                   14253:                     }
                   14254:                     my ($errtext,$fatal) = 
                   14255:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14256:                                                '/'.$folders{$outer}.'.'.
                   14257:                                                $containers{$outer});
                   14258:                     next if ($fatal);
                   14259:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14260:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14261:                             $mapinner{$i} = time;
1.1055    raeburn  14262:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14263:                             $containers{$i} = 'sequence';
                   14264:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14265:                                       $folders{$i}.'.'.$containers{$i};
                   14266:                             my $newidx = &LONCAPA::map::getresidx();
                   14267:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14268:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14269:                             push(@LONCAPA::map::order,$newidx);
                   14270:                             my ($outtext,$errtext) =
                   14271:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14272:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14273:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14274:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14275:                             unless ($errtext) {
1.1294    raeburn  14276:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14277:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14278:                                             '</li>'."\n";
1.1067    raeburn  14279:                             }
1.1055    raeburn  14280:                         }
                   14281:                     } else {
                   14282:                         if ($context eq 'coursedocs') {
                   14283:                             my $newidx=&LONCAPA::map::getresidx();
                   14284:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14285:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14286:                                       $title;
1.1294    raeburn  14287:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   14288:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14289:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14290:                                 }
                   14291:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14292:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14293:                                 }
                   14294:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14295:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14296:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14297:                                         unless ($ishome) {
                   14298:                                             my $fetch = "$newdest{$i}/$title";
                   14299:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14300:                                             $prompttofetch{$fetch} = 1;
                   14301:                                         }
1.1292    raeburn  14302:                                     }
1.1067    raeburn  14303:                                 }
1.1294    raeburn  14304:                                 $LONCAPA::map::resources[$newidx]=
                   14305:                                     $docstitle.':'.$url.':false:normal:res';
                   14306:                                 push(@LONCAPA::map::order, $newidx);
                   14307:                                 my ($outtext,$errtext)=
                   14308:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14309:                                                             $docuname.'/'.$folders{$outer}.
                   14310:                                                             '.'.$containers{$outer},1,1);
                   14311:                                 unless ($errtext) {
                   14312:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14313:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14314:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14315:                                                    '</li>'."\n";
                   14316:                                     }
1.1067    raeburn  14317:                                 }
1.1294    raeburn  14318:                             } else {
                   14319:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14320:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14321:                             }
1.1055    raeburn  14322:                         }
                   14323:                     }
1.1086    raeburn  14324:                 }
                   14325:             } else {
1.1294    raeburn  14326:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14327:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14328:             }
                   14329:         }
                   14330:         for (my $i=1; $i<=$numitems; $i++) {
                   14331:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14332:             my $path = $env{'form.archive_content_'.$i};
                   14333:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14334:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14335:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14336:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14337:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14338:                         my ($itemidx,$fullpath,$relpath);
                   14339:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14340:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14341:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14342:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14343:                                     $itemidx = $j;
1.1056    raeburn  14344:                                 }
                   14345:                             }
1.1086    raeburn  14346:                         }
                   14347:                         if ($itemidx eq '') {
                   14348:                             $itemidx =  0;
                   14349:                         } 
                   14350:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14351:                             if ($mapinner{$referrer{$i}}) {
                   14352:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14353:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14354:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14355:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14356:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14357:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14358:                                             if (!-e $fullpath) {
                   14359:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14360:                                             }
                   14361:                                         }
1.1086    raeburn  14362:                                     } else {
                   14363:                                         last;
1.1056    raeburn  14364:                                     }
1.1086    raeburn  14365:                                 }
                   14366:                             }
                   14367:                         } elsif ($newdest{$referrer{$i}}) {
                   14368:                             $fullpath = $newdest{$referrer{$i}};
                   14369:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14370:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14371:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14372:                                     last;
                   14373:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14374:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14375:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14376:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14377:                                         if (!-e $fullpath) {
                   14378:                                             mkdir($fullpath,0755);
1.1056    raeburn  14379:                                         }
                   14380:                                     }
1.1086    raeburn  14381:                                 } else {
                   14382:                                     last;
1.1056    raeburn  14383:                                 }
1.1055    raeburn  14384:                             }
                   14385:                         }
1.1086    raeburn  14386:                         if ($fullpath ne '') {
                   14387:                             if (-e "$prefix$path") {
1.1292    raeburn  14388:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14389:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14390:                                 }
1.1086    raeburn  14391:                             }
                   14392:                             if (-e "$fullpath/$title") {
                   14393:                                 my $showpath;
                   14394:                                 if ($relpath ne '') {
                   14395:                                     $showpath = "$relpath/$title";
                   14396:                                 } else {
                   14397:                                     $showpath = "/$title";
                   14398:                                 } 
1.1294    raeburn  14399:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14400:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14401:                                            '</li>'."\n";
1.1292    raeburn  14402:                                 unless ($ishome) {
                   14403:                                     my $fetch = "$fullpath/$title";
                   14404:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14405:                                     $prompttofetch{$fetch} = 1;
                   14406:                                 }
1.1086    raeburn  14407:                             }
                   14408:                         }
1.1055    raeburn  14409:                     }
1.1086    raeburn  14410:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14411:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14412:                                     &HTML::Entities::encode($path,'<>&"'),
                   14413:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14414:                                 '<br />';
1.1055    raeburn  14415:                 }
                   14416:             } else {
1.1294    raeburn  14417:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14418:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14419:             }
                   14420:         }
                   14421:         if (keys(%todelete)) {
                   14422:             foreach my $key (keys(%todelete)) {
                   14423:                 unlink($key);
1.1066    raeburn  14424:             }
                   14425:         }
                   14426:         if (keys(%todeletedir)) {
                   14427:             foreach my $key (keys(%todeletedir)) {
                   14428:                 rmdir($key);
                   14429:             }
                   14430:         }
                   14431:         foreach my $dir (sort(keys(%is_dir))) {
                   14432:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14433:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14434:             }
                   14435:         }
1.1067    raeburn  14436:         if ($result ne '') {
                   14437:             $output .= '<ul>'."\n".
                   14438:                        $result."\n".
                   14439:                        '</ul>';
                   14440:         }
                   14441:         unless ($ishome) {
                   14442:             my $replicationfail;
                   14443:             foreach my $item (keys(%prompttofetch)) {
                   14444:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14445:                 unless ($fetchresult eq 'ok') {
                   14446:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14447:                 }
                   14448:             }
                   14449:             if ($replicationfail) {
                   14450:                 $output .= '<p class="LC_error">'.
                   14451:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14452:                            $replicationfail.
                   14453:                            '</ul></p>';
                   14454:             }
                   14455:         }
1.1055    raeburn  14456:     } else {
                   14457:         $warning = &mt('No items found in archive.');
                   14458:     }
                   14459:     if ($error) {
                   14460:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14461:                    $error.'</p>'."\n";
                   14462:     }
                   14463:     if ($warning) {
                   14464:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14465:     }
                   14466:     return $output;
                   14467: }
                   14468: 
1.1066    raeburn  14469: sub cleanup_empty_dirs {
                   14470:     my ($path) = @_;
                   14471:     if (($path ne '') && (-d $path)) {
                   14472:         if (opendir(my $dirh,$path)) {
                   14473:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14474:             my $numitems = 0;
                   14475:             foreach my $item (@dircontents) {
                   14476:                 if (-d "$path/$item") {
1.1111    raeburn  14477:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14478:                     if (-e "$path/$item") {
                   14479:                         $numitems ++;
                   14480:                     }
                   14481:                 } else {
                   14482:                     $numitems ++;
                   14483:                 }
                   14484:             }
                   14485:             if ($numitems == 0) {
                   14486:                 rmdir($path);
                   14487:             }
                   14488:             closedir($dirh);
                   14489:         }
                   14490:     }
                   14491:     return;
                   14492: }
                   14493: 
1.41      ng       14494: =pod
1.45      matthew  14495: 
1.1162    raeburn  14496: =item * &get_folder_hierarchy()
1.1068    raeburn  14497: 
                   14498: Provides hierarchy of names of folders/sub-folders containing the current
                   14499: item,
                   14500: 
                   14501: Inputs: 3
                   14502:      - $navmap - navmaps object
                   14503: 
                   14504:      - $map - url for map (either the trigger itself, or map containing
                   14505:                            the resource, which is the trigger).
                   14506: 
                   14507:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14508: 
                   14509: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14510: 
                   14511: =cut
                   14512: 
                   14513: sub get_folder_hierarchy {
                   14514:     my ($navmap,$map,$showitem) = @_;
                   14515:     my @pathitems;
                   14516:     if (ref($navmap)) {
                   14517:         my $mapres = $navmap->getResourceByUrl($map);
                   14518:         if (ref($mapres)) {
                   14519:             my $pcslist = $mapres->map_hierarchy();
                   14520:             if ($pcslist ne '') {
                   14521:                 my @pcs = split(/,/,$pcslist);
                   14522:                 foreach my $pc (@pcs) {
                   14523:                     if ($pc == 1) {
1.1129    raeburn  14524:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14525:                     } else {
                   14526:                         my $res = $navmap->getByMapPc($pc);
                   14527:                         if (ref($res)) {
                   14528:                             my $title = $res->compTitle();
                   14529:                             $title =~ s/\W+/_/g;
                   14530:                             if ($title ne '') {
                   14531:                                 push(@pathitems,$title);
                   14532:                             }
                   14533:                         }
                   14534:                     }
                   14535:                 }
                   14536:             }
1.1071    raeburn  14537:             if ($showitem) {
                   14538:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14539:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14540:                 } else {
                   14541:                     my $maptitle = $mapres->compTitle();
                   14542:                     $maptitle =~ s/\W+/_/g;
                   14543:                     if ($maptitle ne '') {
                   14544:                         push(@pathitems,$maptitle);
                   14545:                     }
1.1068    raeburn  14546:                 }
                   14547:             }
                   14548:         }
                   14549:     }
                   14550:     return @pathitems;
                   14551: }
                   14552: 
                   14553: =pod
                   14554: 
1.1015    raeburn  14555: =item * &get_turnedin_filepath()
                   14556: 
                   14557: Determines path in a user's portfolio file for storage of files uploaded
                   14558: to a specific essayresponse or dropbox item.
                   14559: 
                   14560: Inputs: 3 required + 1 optional.
                   14561: $symb is symb for resource, $uname and $udom are for current user (required).
                   14562: $caller is optional (can be "submission", if routine is called when storing
                   14563: an upoaded file when "Submit Answer" button was pressed).
                   14564: 
                   14565: Returns array containing $path and $multiresp. 
                   14566: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14567: than one file upload item.  Callers of routine should append partid as a 
                   14568: subdirectory to $path in cases where $multiresp is 1.
                   14569: 
                   14570: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14571: 
                   14572: =cut
                   14573: 
                   14574: sub get_turnedin_filepath {
                   14575:     my ($symb,$uname,$udom,$caller) = @_;
                   14576:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14577:     my $turnindir;
                   14578:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14579:     $turnindir = $userhash{'turnindir'};
                   14580:     my ($path,$multiresp);
                   14581:     if ($turnindir eq '') {
                   14582:         if ($caller eq 'submission') {
                   14583:             $turnindir = &mt('turned in');
                   14584:             $turnindir =~ s/\W+/_/g;
                   14585:             my %newhash = (
                   14586:                             'turnindir' => $turnindir,
                   14587:                           );
                   14588:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14589:         }
                   14590:     }
                   14591:     if ($turnindir ne '') {
                   14592:         $path = '/'.$turnindir.'/';
                   14593:         my ($multipart,$turnin,@pathitems);
                   14594:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14595:         if (defined($navmap)) {
                   14596:             my $mapres = $navmap->getResourceByUrl($map);
                   14597:             if (ref($mapres)) {
                   14598:                 my $pcslist = $mapres->map_hierarchy();
                   14599:                 if ($pcslist ne '') {
                   14600:                     foreach my $pc (split(/,/,$pcslist)) {
                   14601:                         my $res = $navmap->getByMapPc($pc);
                   14602:                         if (ref($res)) {
                   14603:                             my $title = $res->compTitle();
                   14604:                             $title =~ s/\W+/_/g;
                   14605:                             if ($title ne '') {
1.1149    raeburn  14606:                                 if (($pc > 1) && (length($title) > 12)) {
                   14607:                                     $title = substr($title,0,12);
                   14608:                                 }
1.1015    raeburn  14609:                                 push(@pathitems,$title);
                   14610:                             }
                   14611:                         }
                   14612:                     }
                   14613:                 }
                   14614:                 my $maptitle = $mapres->compTitle();
                   14615:                 $maptitle =~ s/\W+/_/g;
                   14616:                 if ($maptitle ne '') {
1.1149    raeburn  14617:                     if (length($maptitle) > 12) {
                   14618:                         $maptitle = substr($maptitle,0,12);
                   14619:                     }
1.1015    raeburn  14620:                     push(@pathitems,$maptitle);
                   14621:                 }
                   14622:                 unless ($env{'request.state'} eq 'construct') {
                   14623:                     my $res = $navmap->getBySymb($symb);
                   14624:                     if (ref($res)) {
                   14625:                         my $partlist = $res->parts();
                   14626:                         my $totaluploads = 0;
                   14627:                         if (ref($partlist) eq 'ARRAY') {
                   14628:                             foreach my $part (@{$partlist}) {
                   14629:                                 my @types = $res->responseType($part);
                   14630:                                 my @ids = $res->responseIds($part);
                   14631:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14632:                                     if ($types[$i] eq 'essay') {
                   14633:                                         my $partid = $part.'_'.$ids[$i];
                   14634:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14635:                                             $totaluploads ++;
                   14636:                                         }
                   14637:                                     }
                   14638:                                 }
                   14639:                             }
                   14640:                             if ($totaluploads > 1) {
                   14641:                                 $multiresp = 1;
                   14642:                             }
                   14643:                         }
                   14644:                     }
                   14645:                 }
                   14646:             } else {
                   14647:                 return;
                   14648:             }
                   14649:         } else {
                   14650:             return;
                   14651:         }
                   14652:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14653:         $restitle =~ s/\W+/_/g;
                   14654:         if ($restitle eq '') {
                   14655:             $restitle = ($resurl =~ m{/[^/]+$});
                   14656:             if ($restitle eq '') {
                   14657:                 $restitle = time;
                   14658:             }
                   14659:         }
1.1149    raeburn  14660:         if (length($restitle) > 12) {
                   14661:             $restitle = substr($restitle,0,12);
                   14662:         }
1.1015    raeburn  14663:         push(@pathitems,$restitle);
                   14664:         $path .= join('/',@pathitems);
                   14665:     }
                   14666:     return ($path,$multiresp);
                   14667: }
                   14668: 
                   14669: =pod
                   14670: 
1.464     albertel 14671: =back
1.41      ng       14672: 
1.112     bowersj2 14673: =head1 CSV Upload/Handling functions
1.38      albertel 14674: 
1.41      ng       14675: =over 4
                   14676: 
1.648     raeburn  14677: =item * &upfile_store($r)
1.41      ng       14678: 
                   14679: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14680: needs $env{'form.upfile'}
1.41      ng       14681: returns $datatoken to be put into hidden field
                   14682: 
                   14683: =cut
1.31      albertel 14684: 
                   14685: sub upfile_store {
                   14686:     my $r=shift;
1.258     albertel 14687:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14688:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14689:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14690:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14691: 
1.1299    raeburn  14692:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14693:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14694:                                      time.'_'.$$);
                   14695:     return if ($datatoken eq '');
                   14696: 
1.31      albertel 14697:     {
1.158     raeburn  14698:         my $datafile = $r->dir_config('lonDaemons').
                   14699:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14700:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14701:             print $fh $env{'form.upfile'};
1.158     raeburn  14702:             close($fh);
                   14703:         }
1.31      albertel 14704:     }
                   14705:     return $datatoken;
                   14706: }
                   14707: 
1.56      matthew  14708: =pod
                   14709: 
1.1290    raeburn  14710: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14711: 
                   14712: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14713: $datatoken is the name to assign to the temporary file.
1.258     albertel 14714: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14715: 
                   14716: =cut
1.31      albertel 14717: 
                   14718: sub load_tmp_file {
1.1290    raeburn  14719:     my ($r,$datatoken) = @_;
                   14720:     return if ($datatoken eq '');
1.31      albertel 14721:     my @studentdata=();
                   14722:     {
1.158     raeburn  14723:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14724:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14725:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14726:             @studentdata=<$fh>;
                   14727:             close($fh);
                   14728:         }
1.31      albertel 14729:     }
1.258     albertel 14730:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14731: }
                   14732: 
1.1290    raeburn  14733: sub valid_datatoken {
                   14734:     my ($datatoken) = @_;
1.1325    raeburn  14735:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14736:         return $datatoken;
                   14737:     }
                   14738:     return;
                   14739: }
                   14740: 
1.56      matthew  14741: =pod
                   14742: 
1.648     raeburn  14743: =item * &upfile_record_sep()
1.41      ng       14744: 
                   14745: Separate uploaded file into records
                   14746: returns array of records,
1.258     albertel 14747: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14748: 
                   14749: =cut
1.31      albertel 14750: 
                   14751: sub upfile_record_sep {
1.258     albertel 14752:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14753:     } else {
1.248     albertel 14754: 	my @records;
1.258     albertel 14755: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14756: 	    if ($line=~/^\s*$/) { next; }
                   14757: 	    push(@records,$line);
                   14758: 	}
                   14759: 	return @records;
1.31      albertel 14760:     }
                   14761: }
                   14762: 
1.56      matthew  14763: =pod
                   14764: 
1.648     raeburn  14765: =item * &record_sep($record)
1.41      ng       14766: 
1.258     albertel 14767: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14768: 
                   14769: =cut
                   14770: 
1.263     www      14771: sub takeleft {
                   14772:     my $index=shift;
                   14773:     return substr('0000'.$index,-4,4);
                   14774: }
                   14775: 
1.31      albertel 14776: sub record_sep {
                   14777:     my $record=shift;
                   14778:     my %components=();
1.258     albertel 14779:     if ($env{'form.upfiletype'} eq 'xml') {
                   14780:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14781:         my $i=0;
1.356     albertel 14782:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14783:             $field=~s/^(\"|\')//;
                   14784:             $field=~s/(\"|\')$//;
1.263     www      14785:             $components{&takeleft($i)}=$field;
1.31      albertel 14786:             $i++;
                   14787:         }
1.258     albertel 14788:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14789:         my $i=0;
1.356     albertel 14790:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14791:             $field=~s/^(\"|\')//;
                   14792:             $field=~s/(\"|\')$//;
1.263     www      14793:             $components{&takeleft($i)}=$field;
1.31      albertel 14794:             $i++;
                   14795:         }
                   14796:     } else {
1.561     www      14797:         my $separator=',';
1.480     banghart 14798:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14799:             $separator=';';
1.480     banghart 14800:         }
1.31      albertel 14801:         my $i=0;
1.561     www      14802: # the character we are looking for to indicate the end of a quote or a record 
                   14803:         my $looking_for=$separator;
                   14804: # do not add the characters to the fields
                   14805:         my $ignore=0;
                   14806: # we just encountered a separator (or the beginning of the record)
                   14807:         my $just_found_separator=1;
                   14808: # store the field we are working on here
                   14809:         my $field='';
                   14810: # work our way through all characters in record
                   14811:         foreach my $character ($record=~/(.)/g) {
                   14812:             if ($character eq $looking_for) {
                   14813:                if ($character ne $separator) {
                   14814: # Found the end of a quote, again looking for separator
                   14815:                   $looking_for=$separator;
                   14816:                   $ignore=1;
                   14817:                } else {
                   14818: # Found a separator, store away what we got
                   14819:                   $components{&takeleft($i)}=$field;
                   14820: 	          $i++;
                   14821:                   $just_found_separator=1;
                   14822:                   $ignore=0;
                   14823:                   $field='';
                   14824:                }
                   14825:                next;
                   14826:             }
                   14827: # single or double quotation marks after a separator indicate beginning of a quote
                   14828: # we are now looking for the end of the quote and need to ignore separators
                   14829:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14830:                $looking_for=$character;
                   14831:                next;
                   14832:             }
                   14833: # ignore would be true after we reached the end of a quote
                   14834:             if ($ignore) { next; }
                   14835:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14836:             $field.=$character;
                   14837:             $just_found_separator=0; 
1.31      albertel 14838:         }
1.561     www      14839: # catch the very last entry, since we never encountered the separator
                   14840:         $components{&takeleft($i)}=$field;
1.31      albertel 14841:     }
                   14842:     return %components;
                   14843: }
                   14844: 
1.144     matthew  14845: ######################################################
                   14846: ######################################################
                   14847: 
1.56      matthew  14848: =pod
                   14849: 
1.648     raeburn  14850: =item * &upfile_select_html()
1.41      ng       14851: 
1.144     matthew  14852: Return HTML code to select a file from the users machine and specify 
                   14853: the file type.
1.41      ng       14854: 
                   14855: =cut
                   14856: 
1.144     matthew  14857: ######################################################
                   14858: ######################################################
1.31      albertel 14859: sub upfile_select_html {
1.144     matthew  14860:     my %Types = (
                   14861:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14862:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14863:                  space => &mt('Space separated'),
                   14864:                  tab   => &mt('Tabulator separated'),
                   14865: #                 xml   => &mt('HTML/XML'),
                   14866:                  );
                   14867:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14868:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14869:     foreach my $type (sort(keys(%Types))) {
                   14870:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14871:     }
                   14872:     $Str .= "</select>\n";
                   14873:     return $Str;
1.31      albertel 14874: }
                   14875: 
1.301     albertel 14876: sub get_samples {
                   14877:     my ($records,$toget) = @_;
                   14878:     my @samples=({});
                   14879:     my $got=0;
                   14880:     foreach my $rec (@$records) {
                   14881: 	my %temp = &record_sep($rec);
                   14882: 	if (! grep(/\S/, values(%temp))) { next; }
                   14883: 	if (%temp) {
                   14884: 	    $samples[$got]=\%temp;
                   14885: 	    $got++;
                   14886: 	    if ($got == $toget) { last; }
                   14887: 	}
                   14888:     }
                   14889:     return \@samples;
                   14890: }
                   14891: 
1.144     matthew  14892: ######################################################
                   14893: ######################################################
                   14894: 
1.56      matthew  14895: =pod
                   14896: 
1.648     raeburn  14897: =item * &csv_print_samples($r,$records)
1.41      ng       14898: 
                   14899: Prints a table of sample values from each column uploaded $r is an
                   14900: Apache Request ref, $records is an arrayref from
                   14901: &Apache::loncommon::upfile_record_sep
                   14902: 
                   14903: =cut
                   14904: 
1.144     matthew  14905: ######################################################
                   14906: ######################################################
1.31      albertel 14907: sub csv_print_samples {
                   14908:     my ($r,$records) = @_;
1.662     bisitz   14909:     my $samples = &get_samples($records,5);
1.301     albertel 14910: 
1.594     raeburn  14911:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14912:               &start_data_table_header_row());
1.356     albertel 14913:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14914:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14915:     $r->print(&end_data_table_header_row());
1.301     albertel 14916:     foreach my $hash (@$samples) {
1.594     raeburn  14917: 	$r->print(&start_data_table_row());
1.356     albertel 14918: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14919: 	    $r->print('<td>');
1.356     albertel 14920: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14921: 	    $r->print('</td>');
                   14922: 	}
1.594     raeburn  14923: 	$r->print(&end_data_table_row());
1.31      albertel 14924:     }
1.594     raeburn  14925:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14926: }
                   14927: 
1.144     matthew  14928: ######################################################
                   14929: ######################################################
                   14930: 
1.56      matthew  14931: =pod
                   14932: 
1.648     raeburn  14933: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14934: 
                   14935: Prints a table to create associations between values and table columns.
1.144     matthew  14936: 
1.41      ng       14937: $r is an Apache Request ref,
                   14938: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14939: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14940: 
                   14941: =cut
                   14942: 
1.144     matthew  14943: ######################################################
                   14944: ######################################################
1.31      albertel 14945: sub csv_print_select_table {
                   14946:     my ($r,$records,$d) = @_;
1.301     albertel 14947:     my $i=0;
                   14948:     my $samples = &get_samples($records,1);
1.144     matthew  14949:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14950: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14951:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14952:               '<th>'.&mt('Column').'</th>'.
                   14953:               &end_data_table_header_row()."\n");
1.356     albertel 14954:     foreach my $array_ref (@$d) {
                   14955: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14956: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14957: 
1.875     bisitz   14958: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14959: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14960: 	$r->print('<option value="none"></option>');
1.356     albertel 14961: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14962: 	    $r->print('<option value="'.$sample.'"'.
                   14963:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14964:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14965: 	}
1.594     raeburn  14966: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14967: 	$i++;
                   14968:     }
1.594     raeburn  14969:     $r->print(&end_data_table());
1.31      albertel 14970:     $i--;
                   14971:     return $i;
                   14972: }
1.56      matthew  14973: 
1.144     matthew  14974: ######################################################
                   14975: ######################################################
                   14976: 
1.56      matthew  14977: =pod
1.31      albertel 14978: 
1.648     raeburn  14979: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14980: 
                   14981: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14982: 
                   14983: $r is an Apache Request ref,
                   14984: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14985: $d is an array of 2 element arrays (internal name, displayed name)
                   14986: 
                   14987: =cut
                   14988: 
1.144     matthew  14989: ######################################################
                   14990: ######################################################
1.31      albertel 14991: sub csv_samples_select_table {
                   14992:     my ($r,$records,$d) = @_;
                   14993:     my $i=0;
1.144     matthew  14994:     #
1.662     bisitz   14995:     my $max_samples = 5;
                   14996:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14997:     $r->print(&start_data_table().
                   14998:               &start_data_table_header_row().'<th>'.
                   14999:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15000:               &end_data_table_header_row());
1.301     albertel 15001: 
                   15002:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15003: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15004: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15005: 	foreach my $option (@$d) {
                   15006: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15007: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15008:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15009:                       $display.'</option>');
1.31      albertel 15010: 	}
                   15011: 	$r->print('</select></td><td>');
1.662     bisitz   15012: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15013: 	    if (defined($samples->[$line]{$key})) { 
                   15014: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15015: 	    }
                   15016: 	}
1.594     raeburn  15017: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15018: 	$i++;
                   15019:     }
1.594     raeburn  15020:     $r->print(&end_data_table());
1.31      albertel 15021:     $i--;
                   15022:     return($i);
1.115     matthew  15023: }
                   15024: 
1.144     matthew  15025: ######################################################
                   15026: ######################################################
                   15027: 
1.115     matthew  15028: =pod
                   15029: 
1.648     raeburn  15030: =item * &clean_excel_name($name)
1.115     matthew  15031: 
                   15032: Returns a replacement for $name which does not contain any illegal characters.
                   15033: 
                   15034: =cut
                   15035: 
1.144     matthew  15036: ######################################################
                   15037: ######################################################
1.115     matthew  15038: sub clean_excel_name {
                   15039:     my ($name) = @_;
                   15040:     $name =~ s/[:\*\?\/\\]//g;
                   15041:     if (length($name) > 31) {
                   15042:         $name = substr($name,0,31);
                   15043:     }
                   15044:     return $name;
1.25      albertel 15045: }
1.84      albertel 15046: 
1.85      albertel 15047: =pod
                   15048: 
1.648     raeburn  15049: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15050: 
                   15051: Returns either 1 or undef
                   15052: 
                   15053: 1 if the part is to be hidden, undef if it is to be shown
                   15054: 
                   15055: Arguments are:
                   15056: 
                   15057: $id the id of the part to be checked
                   15058: $symb, optional the symb of the resource to check
                   15059: $udom, optional the domain of the user to check for
                   15060: $uname, optional the username of the user to check for
                   15061: 
                   15062: =cut
1.84      albertel 15063: 
                   15064: sub check_if_partid_hidden {
                   15065:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15066:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15067: 					 $symb,$udom,$uname);
1.141     albertel 15068:     my $truth=1;
                   15069:     #if the string starts with !, then the list is the list to show not hide
                   15070:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15071:     my @hiddenlist=split(/,/,$hiddenparts);
                   15072:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15073: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15074:     }
1.141     albertel 15075:     return !$truth;
1.84      albertel 15076: }
1.127     matthew  15077: 
1.138     matthew  15078: 
                   15079: ############################################################
                   15080: ############################################################
                   15081: 
                   15082: =pod
                   15083: 
1.157     matthew  15084: =back 
                   15085: 
1.138     matthew  15086: =head1 cgi-bin script and graphing routines
                   15087: 
1.157     matthew  15088: =over 4
                   15089: 
1.648     raeburn  15090: =item * &get_cgi_id()
1.138     matthew  15091: 
                   15092: Inputs: none
                   15093: 
                   15094: Returns an id which can be used to pass environment variables
                   15095: to various cgi-bin scripts.  These environment variables will
                   15096: be removed from the users environment after a given time by
                   15097: the routine &Apache::lonnet::transfer_profile_to_env.
                   15098: 
                   15099: =cut
                   15100: 
                   15101: ############################################################
                   15102: ############################################################
1.152     albertel 15103: my $uniq=0;
1.136     matthew  15104: sub get_cgi_id {
1.154     albertel 15105:     $uniq=($uniq+1)%100000;
1.280     albertel 15106:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15107: }
                   15108: 
1.127     matthew  15109: ############################################################
                   15110: ############################################################
                   15111: 
                   15112: =pod
                   15113: 
1.648     raeburn  15114: =item * &DrawBarGraph()
1.127     matthew  15115: 
1.138     matthew  15116: Facilitates the plotting of data in a (stacked) bar graph.
                   15117: Puts plot definition data into the users environment in order for 
                   15118: graph.png to plot it.  Returns an <img> tag for the plot.
                   15119: The bars on the plot are labeled '1','2',...,'n'.
                   15120: 
                   15121: Inputs:
                   15122: 
                   15123: =over 4
                   15124: 
                   15125: =item $Title: string, the title of the plot
                   15126: 
                   15127: =item $xlabel: string, text describing the X-axis of the plot
                   15128: 
                   15129: =item $ylabel: string, text describing the Y-axis of the plot
                   15130: 
                   15131: =item $Max: scalar, the maximum Y value to use in the plot
                   15132: If $Max is < any data point, the graph will not be rendered.
                   15133: 
1.140     matthew  15134: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15135: they are plotted.  If undefined, default values will be used.
                   15136: 
1.178     matthew  15137: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15138: 
1.138     matthew  15139: =item @Values: An array of array references.  Each array reference holds data
                   15140: to be plotted in a stacked bar chart.
                   15141: 
1.239     matthew  15142: =item If the final element of @Values is a hash reference the key/value
                   15143: pairs will be added to the graph definition.
                   15144: 
1.138     matthew  15145: =back
                   15146: 
                   15147: Returns:
                   15148: 
                   15149: An <img> tag which references graph.png and the appropriate identifying
                   15150: information for the plot.
                   15151: 
1.127     matthew  15152: =cut
                   15153: 
                   15154: ############################################################
                   15155: ############################################################
1.134     matthew  15156: sub DrawBarGraph {
1.178     matthew  15157:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15158:     #
                   15159:     if (! defined($colors)) {
                   15160:         $colors = ['#33ff00', 
                   15161:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15162:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15163:                   ]; 
                   15164:     }
1.228     matthew  15165:     my $extra_settings = {};
                   15166:     if (ref($Values[-1]) eq 'HASH') {
                   15167:         $extra_settings = pop(@Values);
                   15168:     }
1.127     matthew  15169:     #
1.136     matthew  15170:     my $identifier = &get_cgi_id();
                   15171:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15172:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15173:         return '';
                   15174:     }
1.225     matthew  15175:     #
                   15176:     my @Labels;
                   15177:     if (defined($labels)) {
                   15178:         @Labels = @$labels;
                   15179:     } else {
                   15180:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15181:             push(@Labels,$i+1);
1.225     matthew  15182:         }
                   15183:     }
                   15184:     #
1.129     matthew  15185:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15186:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15187:     my %ValuesHash;
                   15188:     my $NumSets=1;
                   15189:     foreach my $array (@Values) {
                   15190:         next if (! ref($array));
1.136     matthew  15191:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15192:             join(',',@$array);
1.129     matthew  15193:     }
1.127     matthew  15194:     #
1.136     matthew  15195:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15196:     if ($NumBars < 3) {
                   15197:         $width = 120+$NumBars*32;
1.220     matthew  15198:         $xskip = 1;
1.225     matthew  15199:         $bar_width = 30;
                   15200:     } elsif ($NumBars < 5) {
                   15201:         $width = 120+$NumBars*20;
                   15202:         $xskip = 1;
                   15203:         $bar_width = 20;
1.220     matthew  15204:     } elsif ($NumBars < 10) {
1.136     matthew  15205:         $width = 120+$NumBars*15;
                   15206:         $xskip = 1;
                   15207:         $bar_width = 15;
                   15208:     } elsif ($NumBars <= 25) {
                   15209:         $width = 120+$NumBars*11;
                   15210:         $xskip = 5;
                   15211:         $bar_width = 8;
                   15212:     } elsif ($NumBars <= 50) {
                   15213:         $width = 120+$NumBars*8;
                   15214:         $xskip = 5;
                   15215:         $bar_width = 4;
                   15216:     } else {
                   15217:         $width = 120+$NumBars*8;
                   15218:         $xskip = 5;
                   15219:         $bar_width = 4;
                   15220:     }
                   15221:     #
1.137     matthew  15222:     $Max = 1 if ($Max < 1);
                   15223:     if ( int($Max) < $Max ) {
                   15224:         $Max++;
                   15225:         $Max = int($Max);
                   15226:     }
1.127     matthew  15227:     $Title  = '' if (! defined($Title));
                   15228:     $xlabel = '' if (! defined($xlabel));
                   15229:     $ylabel = '' if (! defined($ylabel));
1.369     www      15230:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15231:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15232:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15233:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15234:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15235:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15236:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15237:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15238:     $ValuesHash{$id.'.height'}   = $height;
                   15239:     $ValuesHash{$id.'.width'}    = $width;
                   15240:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15241:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15242:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15243:     #
1.228     matthew  15244:     # Deal with other parameters
                   15245:     while (my ($key,$value) = each(%$extra_settings)) {
                   15246:         $ValuesHash{$id.'.'.$key} = $value;
                   15247:     }
                   15248:     #
1.646     raeburn  15249:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15250:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15251: }
                   15252: 
                   15253: ############################################################
                   15254: ############################################################
                   15255: 
                   15256: =pod
                   15257: 
1.648     raeburn  15258: =item * &DrawXYGraph()
1.137     matthew  15259: 
1.138     matthew  15260: Facilitates the plotting of data in an XY graph.
                   15261: Puts plot definition data into the users environment in order for 
                   15262: graph.png to plot it.  Returns an <img> tag for the plot.
                   15263: 
                   15264: Inputs:
                   15265: 
                   15266: =over 4
                   15267: 
                   15268: =item $Title: string, the title of the plot
                   15269: 
                   15270: =item $xlabel: string, text describing the X-axis of the plot
                   15271: 
                   15272: =item $ylabel: string, text describing the Y-axis of the plot
                   15273: 
                   15274: =item $Max: scalar, the maximum Y value to use in the plot
                   15275: If $Max is < any data point, the graph will not be rendered.
                   15276: 
                   15277: =item $colors: Array ref containing the hex color codes for the data to be 
                   15278: plotted in.  If undefined, default values will be used.
                   15279: 
                   15280: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15281: 
                   15282: =item $Ydata: Array ref containing Array refs.  
1.185     www      15283: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15284: 
                   15285: =item %Values: hash indicating or overriding any default values which are 
                   15286: passed to graph.png.  
                   15287: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15288: 
                   15289: =back
                   15290: 
                   15291: Returns:
                   15292: 
                   15293: An <img> tag which references graph.png and the appropriate identifying
                   15294: information for the plot.
                   15295: 
1.137     matthew  15296: =cut
                   15297: 
                   15298: ############################################################
                   15299: ############################################################
                   15300: sub DrawXYGraph {
                   15301:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15302:     #
                   15303:     # Create the identifier for the graph
                   15304:     my $identifier = &get_cgi_id();
                   15305:     my $id = 'cgi.'.$identifier;
                   15306:     #
                   15307:     $Title  = '' if (! defined($Title));
                   15308:     $xlabel = '' if (! defined($xlabel));
                   15309:     $ylabel = '' if (! defined($ylabel));
                   15310:     my %ValuesHash = 
                   15311:         (
1.369     www      15312:          $id.'.title'  => &escape($Title),
                   15313:          $id.'.xlabel' => &escape($xlabel),
                   15314:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15315:          $id.'.y_max_value'=> $Max,
                   15316:          $id.'.labels'     => join(',',@$Xlabels),
                   15317:          $id.'.PlotType'   => 'XY',
                   15318:          );
                   15319:     #
                   15320:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15321:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15322:     }
                   15323:     #
                   15324:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15325:         return '';
                   15326:     }
                   15327:     my $NumSets=1;
1.138     matthew  15328:     foreach my $array (@{$Ydata}){
1.137     matthew  15329:         next if (! ref($array));
                   15330:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15331:     }
1.138     matthew  15332:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15333:     #
                   15334:     # Deal with other parameters
                   15335:     while (my ($key,$value) = each(%Values)) {
                   15336:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15337:     }
                   15338:     #
1.646     raeburn  15339:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15340:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15341: }
                   15342: 
                   15343: ############################################################
                   15344: ############################################################
                   15345: 
                   15346: =pod
                   15347: 
1.648     raeburn  15348: =item * &DrawXYYGraph()
1.138     matthew  15349: 
                   15350: Facilitates the plotting of data in an XY graph with two Y axes.
                   15351: Puts plot definition data into the users environment in order for 
                   15352: graph.png to plot it.  Returns an <img> tag for the plot.
                   15353: 
                   15354: Inputs:
                   15355: 
                   15356: =over 4
                   15357: 
                   15358: =item $Title: string, the title of the plot
                   15359: 
                   15360: =item $xlabel: string, text describing the X-axis of the plot
                   15361: 
                   15362: =item $ylabel: string, text describing the Y-axis of the plot
                   15363: 
                   15364: =item $colors: Array ref containing the hex color codes for the data to be 
                   15365: plotted in.  If undefined, default values will be used.
                   15366: 
                   15367: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15368: 
                   15369: =item $Ydata1: The first data set
                   15370: 
                   15371: =item $Min1: The minimum value of the left Y-axis
                   15372: 
                   15373: =item $Max1: The maximum value of the left Y-axis
                   15374: 
                   15375: =item $Ydata2: The second data set
                   15376: 
                   15377: =item $Min2: The minimum value of the right Y-axis
                   15378: 
                   15379: =item $Max2: The maximum value of the left Y-axis
                   15380: 
                   15381: =item %Values: hash indicating or overriding any default values which are 
                   15382: passed to graph.png.  
                   15383: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15384: 
                   15385: =back
                   15386: 
                   15387: Returns:
                   15388: 
                   15389: An <img> tag which references graph.png and the appropriate identifying
                   15390: information for the plot.
1.136     matthew  15391: 
                   15392: =cut
                   15393: 
                   15394: ############################################################
                   15395: ############################################################
1.137     matthew  15396: sub DrawXYYGraph {
                   15397:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15398:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15399:     #
                   15400:     # Create the identifier for the graph
                   15401:     my $identifier = &get_cgi_id();
                   15402:     my $id = 'cgi.'.$identifier;
                   15403:     #
                   15404:     $Title  = '' if (! defined($Title));
                   15405:     $xlabel = '' if (! defined($xlabel));
                   15406:     $ylabel = '' if (! defined($ylabel));
                   15407:     my %ValuesHash = 
                   15408:         (
1.369     www      15409:          $id.'.title'  => &escape($Title),
                   15410:          $id.'.xlabel' => &escape($xlabel),
                   15411:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15412:          $id.'.labels' => join(',',@$Xlabels),
                   15413:          $id.'.PlotType' => 'XY',
                   15414:          $id.'.NumSets' => 2,
1.137     matthew  15415:          $id.'.two_axes' => 1,
                   15416:          $id.'.y1_max_value' => $Max1,
                   15417:          $id.'.y1_min_value' => $Min1,
                   15418:          $id.'.y2_max_value' => $Max2,
                   15419:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15420:          );
                   15421:     #
1.137     matthew  15422:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15423:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15424:     }
                   15425:     #
                   15426:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15427:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15428:         return '';
                   15429:     }
                   15430:     my $NumSets=1;
1.137     matthew  15431:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15432:         next if (! ref($array));
                   15433:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15434:     }
                   15435:     #
                   15436:     # Deal with other parameters
                   15437:     while (my ($key,$value) = each(%Values)) {
                   15438:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15439:     }
                   15440:     #
1.646     raeburn  15441:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15442:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15443: }
                   15444: 
                   15445: ############################################################
                   15446: ############################################################
                   15447: 
                   15448: =pod
                   15449: 
1.157     matthew  15450: =back 
                   15451: 
1.139     matthew  15452: =head1 Statistics helper routines?  
                   15453: 
                   15454: Bad place for them but what the hell.
                   15455: 
1.157     matthew  15456: =over 4
                   15457: 
1.648     raeburn  15458: =item * &chartlink()
1.139     matthew  15459: 
                   15460: Returns a link to the chart for a specific student.  
                   15461: 
                   15462: Inputs:
                   15463: 
                   15464: =over 4
                   15465: 
                   15466: =item $linktext: The text of the link
                   15467: 
                   15468: =item $sname: The students username
                   15469: 
                   15470: =item $sdomain: The students domain
                   15471: 
                   15472: =back
                   15473: 
1.157     matthew  15474: =back
                   15475: 
1.139     matthew  15476: =cut
                   15477: 
                   15478: ############################################################
                   15479: ############################################################
                   15480: sub chartlink {
                   15481:     my ($linktext, $sname, $sdomain) = @_;
                   15482:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15483:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15484:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15485:        '">'.$linktext.'</a>';
1.153     matthew  15486: }
                   15487: 
                   15488: #######################################################
                   15489: #######################################################
                   15490: 
                   15491: =pod
                   15492: 
                   15493: =head1 Course Environment Routines
1.157     matthew  15494: 
                   15495: =over 4
1.153     matthew  15496: 
1.648     raeburn  15497: =item * &restore_course_settings()
1.153     matthew  15498: 
1.648     raeburn  15499: =item * &store_course_settings()
1.153     matthew  15500: 
                   15501: Restores/Store indicated form parameters from the course environment.
                   15502: Will not overwrite existing values of the form parameters.
                   15503: 
                   15504: Inputs: 
                   15505: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15506: 
                   15507: a hash ref describing the data to be stored.  For example:
                   15508:    
                   15509: %Save_Parameters = ('Status' => 'scalar',
                   15510:     'chartoutputmode' => 'scalar',
                   15511:     'chartoutputdata' => 'scalar',
                   15512:     'Section' => 'array',
1.373     raeburn  15513:     'Group' => 'array',
1.153     matthew  15514:     'StudentData' => 'array',
                   15515:     'Maps' => 'array');
                   15516: 
                   15517: Returns: both routines return nothing
                   15518: 
1.631     raeburn  15519: =back
                   15520: 
1.153     matthew  15521: =cut
                   15522: 
                   15523: #######################################################
                   15524: #######################################################
                   15525: sub store_course_settings {
1.496     albertel 15526:     return &store_settings($env{'request.course.id'},@_);
                   15527: }
                   15528: 
                   15529: sub store_settings {
1.153     matthew  15530:     # save to the environment
                   15531:     # appenv the same items, just to be safe
1.300     albertel 15532:     my $udom  = $env{'user.domain'};
                   15533:     my $uname = $env{'user.name'};
1.496     albertel 15534:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15535:     my %SaveHash;
                   15536:     my %AppHash;
                   15537:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15538:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15539:         my $envname = 'environment.'.$basename;
1.258     albertel 15540:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15541:             # Save this value away
                   15542:             if ($type eq 'scalar' &&
1.258     albertel 15543:                 (! exists($env{$envname}) || 
                   15544:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15545:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15546:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15547:             } elsif ($type eq 'array') {
                   15548:                 my $stored_form;
1.258     albertel 15549:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15550:                     $stored_form = join(',',
                   15551:                                         map {
1.369     www      15552:                                             &escape($_);
1.258     albertel 15553:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15554:                 } else {
                   15555:                     $stored_form = 
1.369     www      15556:                         &escape($env{'form.'.$setting});
1.153     matthew  15557:                 }
                   15558:                 # Determine if the array contents are the same.
1.258     albertel 15559:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15560:                     $SaveHash{$basename} = $stored_form;
                   15561:                     $AppHash{$envname}   = $stored_form;
                   15562:                 }
                   15563:             }
                   15564:         }
                   15565:     }
                   15566:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15567:                                           $udom,$uname);
1.153     matthew  15568:     if ($put_result !~ /^(ok|delayed)/) {
                   15569:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15570:                                  'got error:'.$put_result);
                   15571:     }
                   15572:     # Make sure these settings stick around in this session, too
1.646     raeburn  15573:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15574:     return;
                   15575: }
                   15576: 
                   15577: sub restore_course_settings {
1.499     albertel 15578:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15579: }
                   15580: 
                   15581: sub restore_settings {
                   15582:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15583:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15584:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15585:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15586:             '.'.$setting;
1.258     albertel 15587:         if (exists($env{$envname})) {
1.153     matthew  15588:             if ($type eq 'scalar') {
1.258     albertel 15589:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15590:             } elsif ($type eq 'array') {
1.258     albertel 15591:                 $env{'form.'.$setting} = [ 
1.153     matthew  15592:                                            map { 
1.369     www      15593:                                                &unescape($_); 
1.258     albertel 15594:                                            } split(',',$env{$envname})
1.153     matthew  15595:                                            ];
                   15596:             }
                   15597:         }
                   15598:     }
1.127     matthew  15599: }
                   15600: 
1.618     raeburn  15601: #######################################################
                   15602: #######################################################
                   15603: 
                   15604: =pod
                   15605: 
                   15606: =head1 Domain E-mail Routines  
                   15607: 
                   15608: =over 4
                   15609: 
1.648     raeburn  15610: =item * &build_recipient_list()
1.618     raeburn  15611: 
1.1144    raeburn  15612: Build recipient lists for following types of e-mail:
1.766     raeburn  15613: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15614: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15615: module change checking, student/employee ID conflict checks, as
                   15616: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15617: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15618: 
                   15619: Inputs:
1.619     raeburn  15620: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15621: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15622: requestsmail, updatesmail, or idconflictsmail).
                   15623: 
1.619     raeburn  15624: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15625: 
1.619     raeburn  15626: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15627: i.e., predates configuration by DC via domainprefs.pm
                   15628: 
                   15629: $requname username of requester (if mailing type is helpdeskmail)
                   15630: 
                   15631: $requdom domain of requester (if mailing type is helpdeskmail)
                   15632: 
                   15633: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15634: 
1.618     raeburn  15635: 
1.655     raeburn  15636: Returns: comma separated list of addresses to which to send e-mail.
                   15637: 
                   15638: =back
1.618     raeburn  15639: 
                   15640: =cut
                   15641: 
                   15642: ############################################################
                   15643: ############################################################
                   15644: sub build_recipient_list {
1.1297    raeburn  15645:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15646:     my @recipients;
1.1270    raeburn  15647:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15648:     my %domconfig =
1.1270    raeburn  15649:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15650:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15651:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15652:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15653:                 my @contacts = ('adminemail','supportemail');
                   15654:                 foreach my $item (@contacts) {
                   15655:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15656:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15657:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15658:                             push(@recipients,$addr);
                   15659:                         }
1.619     raeburn  15660:                     }
1.1270    raeburn  15661:                 }
                   15662:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15663:                 if ($mailing eq 'helpdeskmail') {
                   15664:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15665:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15666:                         my @ok_bccs;
                   15667:                         foreach my $bcc (@bccs) {
                   15668:                             $bcc =~ s/^\s+//g;
                   15669:                             $bcc =~ s/\s+$//g;
                   15670:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15671:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15672:                                     push(@ok_bccs,$bcc);
                   15673:                                 }
                   15674:                             }
                   15675:                         }
                   15676:                         if (@ok_bccs > 0) {
                   15677:                             $allbcc = join(', ',@ok_bccs);
                   15678:                         }
                   15679:                     }
                   15680:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15681:                 }
                   15682:             }
1.766     raeburn  15683:         } elsif ($origmail ne '') {
1.1270    raeburn  15684:             $lastresort = $origmail;
1.618     raeburn  15685:         }
1.1297    raeburn  15686:         if ($mailing eq 'helpdeskmail') {
                   15687:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15688:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15689:                 my ($inststatus,$inststatus_checked);
                   15690:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15691:                     ($env{'user.domain'} ne 'public')) {
                   15692:                     $inststatus_checked = 1;
                   15693:                     $inststatus = $env{'environment.inststatus'};
                   15694:                 }
                   15695:                 unless ($inststatus_checked) {
                   15696:                     if (($requname ne '') && ($requdom ne '')) {
                   15697:                         if (($requname =~ /^$match_username$/) &&
                   15698:                             ($requdom =~ /^$match_domain$/) &&
                   15699:                             (&Apache::lonnet::domain($requdom))) {
                   15700:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15701:                                                                       $requdom);
                   15702:                             unless ($requhome eq 'no_host') {
                   15703:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15704:                                 $inststatus = $userenv{'inststatus'};
                   15705:                                 $inststatus_checked = 1;
                   15706:                             }
                   15707:                         }
                   15708:                     }
                   15709:                 }
                   15710:                 unless ($inststatus_checked) {
                   15711:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15712:                         my %srch = (srchby     => 'email',
                   15713:                                     srchdomain => $defdom,
                   15714:                                     srchterm   => $reqemail,
                   15715:                                     srchtype   => 'exact');
                   15716:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15717:                         foreach my $uname (keys(%srch_results)) {
                   15718:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15719:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15720:                                 $inststatus_checked = 1;
                   15721:                                 last;
                   15722:                             }
                   15723:                         }
                   15724:                         unless ($inststatus_checked) {
                   15725:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15726:                             if ($dirsrchres eq 'ok') {
                   15727:                                 foreach my $uname (keys(%srch_results)) {
                   15728:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15729:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15730:                                         $inststatus_checked = 1;
                   15731:                                         last;
                   15732:                                     }
                   15733:                                 }
                   15734:                             }
                   15735:                         }
                   15736:                     }
                   15737:                 }
                   15738:                 if ($inststatus ne '') {
                   15739:                     foreach my $status (split(/\:/,$inststatus)) {
                   15740:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15741:                             my @contacts = ('adminemail','supportemail');
                   15742:                             foreach my $item (@contacts) {
                   15743:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15744:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15745:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15746:                                         push(@recipients,$addr);
                   15747:                                     }
                   15748:                                 }
                   15749:                             }
                   15750:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15751:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15752:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15753:                                 my @ok_bccs;
                   15754:                                 foreach my $bcc (@bccs) {
                   15755:                                     $bcc =~ s/^\s+//g;
                   15756:                                     $bcc =~ s/\s+$//g;
                   15757:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15758:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15759:                                             push(@ok_bccs,$bcc);
                   15760:                                         }
                   15761:                                     }
                   15762:                                 }
                   15763:                                 if (@ok_bccs > 0) {
                   15764:                                     $allbcc = join(', ',@ok_bccs);
                   15765:                                 }
                   15766:                             }
                   15767:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15768:                             last;
                   15769:                         }
                   15770:                     }
                   15771:                 }
                   15772:             }
                   15773:         }
1.619     raeburn  15774:     } elsif ($origmail ne '') {
1.1270    raeburn  15775:         $lastresort = $origmail;
                   15776:     }
1.1297    raeburn  15777:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15778:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15779:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15780:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15781:             my %what = (
                   15782:                           perlvar => 1,
                   15783:                        );
                   15784:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15785:             if ($primary) {
                   15786:                 my $gotaddr;
                   15787:                 my ($result,$returnhash) =
                   15788:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15789:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15790:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15791:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15792:                         $gotaddr = 1;
                   15793:                     }
                   15794:                 }
                   15795:                 unless ($gotaddr) {
                   15796:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15797:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15798:                     unless ($uintdom eq $intdom) {
                   15799:                         my %domconfig =
                   15800:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15801:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15802:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15803:                                 my @contacts = ('adminemail','supportemail');
                   15804:                                 foreach my $item (@contacts) {
                   15805:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15806:                                         my $addr = $domconfig{'contacts'}{$item};
                   15807:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15808:                                             push(@recipients,$addr);
                   15809:                                         }
                   15810:                                     }
                   15811:                                 }
                   15812:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15813:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15814:                                 }
                   15815:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15816:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15817:                                     my @ok_bccs;
                   15818:                                     foreach my $bcc (@bccs) {
                   15819:                                         $bcc =~ s/^\s+//g;
                   15820:                                         $bcc =~ s/\s+$//g;
                   15821:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15822:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15823:                                                 push(@ok_bccs,$bcc);
                   15824:                                             }
                   15825:                                         }
                   15826:                                     }
                   15827:                                     if (@ok_bccs > 0) {
                   15828:                                         $allbcc = join(', ',@ok_bccs);
                   15829:                                     }
                   15830:                                 }
                   15831:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15832:                             }
                   15833:                         }
                   15834:                     }
                   15835:                 }
                   15836:             }
                   15837:         }
1.618     raeburn  15838:     }
1.688     raeburn  15839:     if (defined($defmail)) {
                   15840:         if ($defmail ne '') {
                   15841:             push(@recipients,$defmail);
                   15842:         }
1.618     raeburn  15843:     }
                   15844:     if ($otheremails) {
1.619     raeburn  15845:         my @others;
                   15846:         if ($otheremails =~ /,/) {
                   15847:             @others = split(/,/,$otheremails);
1.618     raeburn  15848:         } else {
1.619     raeburn  15849:             push(@others,$otheremails);
                   15850:         }
                   15851:         foreach my $addr (@others) {
                   15852:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15853:                 push(@recipients,$addr);
                   15854:             }
1.618     raeburn  15855:         }
                   15856:     }
1.1298    raeburn  15857:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15858:         if ((!@recipients) && ($lastresort ne '')) {
                   15859:             push(@recipients,$lastresort);
                   15860:         }
                   15861:     } elsif ($lastresort ne '') {
                   15862:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15863:             push(@recipients,$lastresort);
                   15864:         }
                   15865:     }
1.1271    raeburn  15866:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15867:     if (wantarray) {
                   15868:         return ($recipientlist,$allbcc,$addtext);
                   15869:     } else {
                   15870:         return $recipientlist;
                   15871:     }
1.618     raeburn  15872: }
                   15873: 
1.127     matthew  15874: ############################################################
                   15875: ############################################################
1.154     albertel 15876: 
1.655     raeburn  15877: =pod
                   15878: 
1.1224    musolffc 15879: =over 4
                   15880: 
1.1223    musolffc 15881: =item * &mime_email()
                   15882: 
                   15883: Sends an email with a possible attachment
                   15884: 
                   15885: Inputs:
                   15886: 
                   15887: =over 4
                   15888: 
                   15889: from -              Sender's email address
                   15890: 
1.1343    raeburn  15891: replyto -           Reply-To email address
                   15892: 
1.1223    musolffc 15893: to -                Email address of recipient
                   15894: 
                   15895: subject -           Subject of email
                   15896: 
                   15897: body -              Body of email
                   15898: 
                   15899: cc_string -         Carbon copy email address
                   15900: 
                   15901: bcc -               Blind carbon copy email address
                   15902: 
                   15903: attachment_path -   Path of file to be attached
                   15904: 
                   15905: file_name -         Name of file to be attached
                   15906: 
                   15907: attachment_text -   The body of an attachment of type "TEXT"
                   15908: 
                   15909: =back
                   15910: 
                   15911: =back
                   15912: 
                   15913: =cut
                   15914: 
                   15915: ############################################################
                   15916: ############################################################
                   15917: 
                   15918: sub mime_email {
1.1343    raeburn  15919:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15920:         $file_name,$attachment_text) = @_;
                   15921:  
1.1223    musolffc 15922:     my $msg = MIME::Lite->new(
                   15923:              From    => $from,
                   15924:              To      => $to,
                   15925:              Subject => $subject,
                   15926:              Type    =>'TEXT',
                   15927:              Data    => $body,
                   15928:              );
1.1343    raeburn  15929:     if ($replyto ne '') {
                   15930:         $msg->add("Reply-To" => $replyto);
                   15931:     }
1.1223    musolffc 15932:     if ($cc_string ne '') {
                   15933:         $msg->add("Cc" => $cc_string);
                   15934:     }
                   15935:     if ($bcc ne '') {
                   15936:         $msg->add("Bcc" => $bcc);
                   15937:     }
                   15938:     $msg->attr("content-type"         => "text/plain");
                   15939:     $msg->attr("content-type.charset" => "UTF-8");
                   15940:     # Attach file if given
                   15941:     if ($attachment_path) {
                   15942:         unless ($file_name) {
                   15943:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15944:         }
                   15945:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15946:         $msg->attach(Type     => $type,
                   15947:                      Path     => $attachment_path,
                   15948:                      Filename => $file_name
                   15949:                      );
                   15950:     # Otherwise attach text if given
                   15951:     } elsif ($attachment_text) {
                   15952:         $msg->attach(Type => 'TEXT',
                   15953:                      Data => $attachment_text);
                   15954:     }
                   15955:     # Send it
                   15956:     $msg->send('sendmail');
                   15957: }
                   15958: 
                   15959: ############################################################
                   15960: ############################################################
                   15961: 
                   15962: =pod
                   15963: 
1.655     raeburn  15964: =head1 Course Catalog Routines
                   15965: 
                   15966: =over 4
                   15967: 
                   15968: =item * &gather_categories()
                   15969: 
                   15970: Converts category definitions - keys of categories hash stored in  
                   15971: coursecategories in configuration.db on the primary library server in a 
                   15972: domain - to an array.  Also generates javascript and idx hash used to 
                   15973: generate Domain Coordinator interface for editing Course Categories.
                   15974: 
                   15975: Inputs:
1.663     raeburn  15976: 
1.655     raeburn  15977: categories (reference to hash of category definitions).
1.663     raeburn  15978: 
1.655     raeburn  15979: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15980:       categories and subcategories).
1.663     raeburn  15981: 
1.655     raeburn  15982: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15983:       editing Course Categories).
1.663     raeburn  15984: 
1.655     raeburn  15985: jsarray (reference to array of categories used to create Javascript arrays for
                   15986:          Domain Coordinator interface for editing Course Categories).
                   15987: 
                   15988: Returns: nothing
                   15989: 
                   15990: Side effects: populates cats, idx and jsarray. 
                   15991: 
                   15992: =cut
                   15993: 
                   15994: sub gather_categories {
                   15995:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15996:     my %counters;
                   15997:     my $num = 0;
                   15998:     foreach my $item (keys(%{$categories})) {
                   15999:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16000:         if ($container eq '' && $depth == 0) {
                   16001:             $cats->[$depth][$categories->{$item}] = $cat;
                   16002:         } else {
                   16003:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16004:         }
                   16005:         my ($escitem,$tail) = split(/:/,$item,2);
                   16006:         if ($counters{$tail} eq '') {
                   16007:             $counters{$tail} = $num;
                   16008:             $num ++;
                   16009:         }
                   16010:         if (ref($idx) eq 'HASH') {
                   16011:             $idx->{$item} = $counters{$tail};
                   16012:         }
                   16013:         if (ref($jsarray) eq 'ARRAY') {
                   16014:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16015:         }
                   16016:     }
                   16017:     return;
                   16018: }
                   16019: 
                   16020: =pod
                   16021: 
                   16022: =item * &extract_categories()
                   16023: 
                   16024: Used to generate breadcrumb trails for course categories.
                   16025: 
                   16026: Inputs:
1.663     raeburn  16027: 
1.655     raeburn  16028: categories (reference to hash of category definitions).
1.663     raeburn  16029: 
1.655     raeburn  16030: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16031:       categories and subcategories).
1.663     raeburn  16032: 
1.655     raeburn  16033: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16034: 
1.655     raeburn  16035: allitems (reference to hash - key is category key 
                   16036:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16037: 
1.655     raeburn  16038: idx (reference to hash of counters used in Domain Coordinator interface for
                   16039:       editing Course Categories).
1.663     raeburn  16040: 
1.655     raeburn  16041: jsarray (reference to array of categories used to create Javascript arrays for
                   16042:          Domain Coordinator interface for editing Course Categories).
                   16043: 
1.665     raeburn  16044: subcats (reference to hash of arrays containing all subcategories within each 
                   16045:          category, -recursive)
                   16046: 
1.1321    raeburn  16047: maxd (reference to hash used to hold max depth for all top-level categories).
                   16048: 
1.655     raeburn  16049: Returns: nothing
                   16050: 
                   16051: Side effects: populates trails and allitems hash references.
                   16052: 
                   16053: =cut
                   16054: 
                   16055: sub extract_categories {
1.1321    raeburn  16056:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16057:     if (ref($categories) eq 'HASH') {
                   16058:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16059:         if (ref($cats->[0]) eq 'ARRAY') {
                   16060:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16061:                 my $name = $cats->[0][$i];
                   16062:                 my $item = &escape($name).'::0';
                   16063:                 my $trailstr;
                   16064:                 if ($name eq 'instcode') {
                   16065:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16066:                 } elsif ($name eq 'communities') {
                   16067:                     $trailstr = &mt('Communities');
1.1239    raeburn  16068:                 } elsif ($name eq 'placement') {
                   16069:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16070:                 } else {
                   16071:                     $trailstr = $name;
                   16072:                 }
                   16073:                 if ($allitems->{$item} eq '') {
                   16074:                     push(@{$trails},$trailstr);
                   16075:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16076:                 }
                   16077:                 my @parents = ($name);
                   16078:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16079:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16080:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16081:                         if (ref($subcats) eq 'HASH') {
                   16082:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16083:                         }
1.1321    raeburn  16084:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16085:                     }
                   16086:                 } else {
                   16087:                     if (ref($subcats) eq 'HASH') {
                   16088:                         $subcats->{$item} = [];
1.655     raeburn  16089:                     }
1.1321    raeburn  16090:                     if (ref($maxd) eq 'HASH') {
                   16091:                         $maxd->{$name} = 1;
                   16092:                     }
1.655     raeburn  16093:                 }
                   16094:             }
                   16095:         }
                   16096:     }
                   16097:     return;
                   16098: }
                   16099: 
                   16100: =pod
                   16101: 
1.1162    raeburn  16102: =item * &recurse_categories()
1.655     raeburn  16103: 
                   16104: Recursively used to generate breadcrumb trails for course categories.
                   16105: 
                   16106: Inputs:
1.663     raeburn  16107: 
1.655     raeburn  16108: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16109:       categories and subcategories).
1.663     raeburn  16110: 
1.655     raeburn  16111: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16112: 
                   16113: category (current course category, for which breadcrumb trail is being generated).
                   16114: 
                   16115: trails (reference to array of breadcrumb trails for each category).
                   16116: 
1.655     raeburn  16117: allitems (reference to hash - key is category key
                   16118:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16119: 
1.655     raeburn  16120: parents (array containing containers directories for current category, 
                   16121:          back to top level). 
                   16122: 
                   16123: Returns: nothing
                   16124: 
                   16125: Side effects: populates trails and allitems hash references
                   16126: 
                   16127: =cut
                   16128: 
                   16129: sub recurse_categories {
1.1321    raeburn  16130:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16131:     my $shallower = $depth - 1;
                   16132:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16133:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16134:             my $name = $cats->[$depth]{$category}[$k];
                   16135:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16136:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16137:             if ($allitems->{$item} eq '') {
                   16138:                 push(@{$trails},$trailstr);
                   16139:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16140:             }
                   16141:             my $deeper = $depth+1;
                   16142:             push(@{$parents},$category);
1.665     raeburn  16143:             if (ref($subcats) eq 'HASH') {
                   16144:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16145:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16146:                     my $higher;
                   16147:                     if ($j > 0) {
                   16148:                         $higher = &escape($parents->[$j]).':'.
                   16149:                                   &escape($parents->[$j-1]).':'.$j;
                   16150:                     } else {
                   16151:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16152:                     }
                   16153:                     push(@{$subcats->{$higher}},$subcat);
                   16154:                 }
                   16155:             }
                   16156:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16157:                                 $subcats,$maxd);
1.655     raeburn  16158:             pop(@{$parents});
                   16159:         }
                   16160:     } else {
                   16161:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16162:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16163:         if ($allitems->{$item} eq '') {
                   16164:             push(@{$trails},$trailstr);
                   16165:             $allitems->{$item} = scalar(@{$trails})-1;
                   16166:         }
1.1321    raeburn  16167:         if (ref($maxd) eq 'HASH') {
                   16168:             if ($depth > $maxd->{$parents->[0]}) {
                   16169:                 $maxd->{$parents->[0]} = $depth;
                   16170:             }
                   16171:         }
1.655     raeburn  16172:     }
                   16173:     return;
                   16174: }
                   16175: 
1.663     raeburn  16176: =pod
                   16177: 
1.1162    raeburn  16178: =item * &assign_categories_table()
1.663     raeburn  16179: 
                   16180: Create a datatable for display of hierarchical categories in a domain,
                   16181: with checkboxes to allow a course to be categorized. 
                   16182: 
                   16183: Inputs:
                   16184: 
                   16185: cathash - reference to hash of categories defined for the domain (from
                   16186:           configuration.db)
                   16187: 
                   16188: currcat - scalar with an & separated list of categories assigned to a course. 
                   16189: 
1.919     raeburn  16190: type    - scalar contains course type (Course or Community).
                   16191: 
1.1260    raeburn  16192: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16193:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16194: 
1.663     raeburn  16195: Returns: $output (markup to be displayed) 
                   16196: 
                   16197: =cut
                   16198: 
                   16199: sub assign_categories_table {
1.1259    raeburn  16200:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16201:     my $output;
                   16202:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16203:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16204:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16205:         $maxdepth = scalar(@cats);
                   16206:         if (@cats > 0) {
                   16207:             my $itemcount = 0;
                   16208:             if (ref($cats[0]) eq 'ARRAY') {
                   16209:                 my @currcategories;
                   16210:                 if ($currcat ne '') {
                   16211:                     @currcategories = split('&',$currcat);
                   16212:                 }
1.919     raeburn  16213:                 my $table;
1.663     raeburn  16214:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16215:                     my $parent = $cats[0][$i];
1.919     raeburn  16216:                     next if ($parent eq 'instcode');
                   16217:                     if ($type eq 'Community') {
                   16218:                         next unless ($parent eq 'communities');
1.1239    raeburn  16219:                     } elsif ($type eq 'Placement') {
                   16220:                         next unless ($parent eq 'placement');
1.919     raeburn  16221:                     } else {
1.1239    raeburn  16222:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16223:                     }
1.663     raeburn  16224:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16225:                     my $item = &escape($parent).'::0';
                   16226:                     my $checked = '';
                   16227:                     if (@currcategories > 0) {
                   16228:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16229:                             $checked = ' checked="checked"';
1.663     raeburn  16230:                         }
                   16231:                     }
1.919     raeburn  16232:                     my $parent_title = $parent;
                   16233:                     if ($parent eq 'communities') {
                   16234:                         $parent_title = &mt('Communities');
1.1239    raeburn  16235:                     } elsif ($parent eq 'placement') {
                   16236:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16237:                     }
                   16238:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16239:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16240:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16241:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16242:                     my $depth = 1;
                   16243:                     push(@path,$parent);
1.1259    raeburn  16244:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16245:                     pop(@path);
1.919     raeburn  16246:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16247:                     $itemcount ++;
                   16248:                 }
1.919     raeburn  16249:                 if ($itemcount) {
                   16250:                     $output = &Apache::loncommon::start_data_table().
                   16251:                               $table.
                   16252:                               &Apache::loncommon::end_data_table();
                   16253:                 }
1.663     raeburn  16254:             }
                   16255:         }
                   16256:     }
                   16257:     return $output;
                   16258: }
                   16259: 
                   16260: =pod
                   16261: 
1.1162    raeburn  16262: =item * &assign_category_rows()
1.663     raeburn  16263: 
                   16264: Create a datatable row for display of nested categories in a domain,
                   16265: with checkboxes to allow a course to be categorized,called recursively.
                   16266: 
                   16267: Inputs:
                   16268: 
                   16269: itemcount - track row number for alternating colors
                   16270: 
                   16271: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16272:       categories and subcategories.
                   16273: 
                   16274: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16275: 
                   16276: parent - parent of current category item
                   16277: 
                   16278: path - Array containing all categories back up through the hierarchy from the
                   16279:        current category to the top level.
                   16280: 
                   16281: currcategories - reference to array of current categories assigned to the course
                   16282: 
1.1260    raeburn  16283: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16284:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16285: 
1.663     raeburn  16286: Returns: $output (markup to be displayed).
                   16287: 
                   16288: =cut
                   16289: 
                   16290: sub assign_category_rows {
1.1259    raeburn  16291:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16292:     my ($text,$name,$item,$chgstr);
                   16293:     if (ref($cats) eq 'ARRAY') {
                   16294:         my $maxdepth = scalar(@{$cats});
                   16295:         if (ref($cats->[$depth]) eq 'HASH') {
                   16296:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16297:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16298:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16299:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16300:                 for (my $j=0; $j<$numchildren; $j++) {
                   16301:                     $name = $cats->[$depth]{$parent}[$j];
                   16302:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16303:                     my $deeper = $depth+1;
                   16304:                     my $checked = '';
                   16305:                     if (ref($currcategories) eq 'ARRAY') {
                   16306:                         if (@{$currcategories} > 0) {
                   16307:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16308:                                 $checked = ' checked="checked"';
1.663     raeburn  16309:                             }
                   16310:                         }
                   16311:                     }
1.664     raeburn  16312:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16313:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16314:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16315:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16316:                              '</td><td>';
1.663     raeburn  16317:                     if (ref($path) eq 'ARRAY') {
                   16318:                         push(@{$path},$name);
1.1259    raeburn  16319:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16320:                         pop(@{$path});
                   16321:                     }
                   16322:                     $text .= '</td></tr>';
                   16323:                 }
                   16324:                 $text .= '</table></td>';
                   16325:             }
                   16326:         }
                   16327:     }
                   16328:     return $text;
                   16329: }
                   16330: 
1.1181    raeburn  16331: =pod
                   16332: 
                   16333: =back
                   16334: 
                   16335: =cut
                   16336: 
1.655     raeburn  16337: ############################################################
                   16338: ############################################################
                   16339: 
                   16340: 
1.443     albertel 16341: sub commit_customrole {
1.664     raeburn  16342:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16343:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16344:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16345:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16346:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16347:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16348:                  '</b><br />';
                   16349:     return $output;
                   16350: }
                   16351: 
                   16352: sub commit_standardrole {
1.1116    raeburn  16353:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16354:     my ($output,$logmsg,$linefeed);
                   16355:     if ($context eq 'auto') {
                   16356:         $linefeed = "\n";
                   16357:     } else {
                   16358:         $linefeed = "<br />\n";
                   16359:     }  
1.443     albertel 16360:     if ($three eq 'st') {
1.541     raeburn  16361:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16362:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16363:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16364:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16365:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16366:         } else {
1.541     raeburn  16367:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16368:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16369:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16370:             if ($context eq 'auto') {
                   16371:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16372:             } else {
                   16373:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16374:                &mt('Add to classlist').': <b>ok</b>';
                   16375:             }
                   16376:             $output .= $linefeed;
1.443     albertel 16377:         }
                   16378:     } else {
                   16379:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16380:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16381:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16382:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16383:         if ($context eq 'auto') {
                   16384:             $output .= $result.$linefeed;
                   16385:         } else {
                   16386:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16387:         }
1.443     albertel 16388:     }
                   16389:     return $output;
                   16390: }
                   16391: 
                   16392: sub commit_studentrole {
1.1116    raeburn  16393:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16394:         $credits) = @_;
1.626     raeburn  16395:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16396:     if ($context eq 'auto') {
                   16397:         $linefeed = "\n";
                   16398:     } else {
                   16399:         $linefeed = '<br />'."\n";
                   16400:     }
1.443     albertel 16401:     if (defined($one) && defined($two)) {
                   16402:         my $cid=$one.'_'.$two;
                   16403:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16404:         my $secchange = 0;
                   16405:         my $expire_role_result;
                   16406:         my $modify_section_result;
1.628     raeburn  16407:         if ($oldsec ne '-1') { 
                   16408:             if ($oldsec ne $sec) {
1.443     albertel 16409:                 $secchange = 1;
1.628     raeburn  16410:                 my $now = time;
1.443     albertel 16411:                 my $uurl='/'.$cid;
                   16412:                 $uurl=~s/\_/\//g;
                   16413:                 if ($oldsec) {
                   16414:                     $uurl.='/'.$oldsec;
                   16415:                 }
1.626     raeburn  16416:                 $oldsecurl = $uurl;
1.628     raeburn  16417:                 $expire_role_result = 
1.652     raeburn  16418:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16419:                 if ($env{'request.course.sec'} ne '') { 
                   16420:                     if ($expire_role_result eq 'refused') {
                   16421:                         my @roles = ('st');
                   16422:                         my @statuses = ('previous');
                   16423:                         my @roledoms = ($one);
                   16424:                         my $withsec = 1;
                   16425:                         my %roleshash = 
                   16426:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16427:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16428:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16429:                             my ($oldstart,$oldend) = 
                   16430:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16431:                             if ($oldend > 0 && $oldend <= $now) {
                   16432:                                 $expire_role_result = 'ok';
                   16433:                             }
                   16434:                         }
                   16435:                     }
                   16436:                 }
1.443     albertel 16437:                 $result = $expire_role_result;
                   16438:             }
                   16439:         }
                   16440:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16441:             $modify_section_result = 
                   16442:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16443:                                                            undef,undef,undef,$sec,
                   16444:                                                            $end,$start,'','',$cid,
                   16445:                                                            '',$context,$credits);
1.443     albertel 16446:             if ($modify_section_result =~ /^ok/) {
                   16447:                 if ($secchange == 1) {
1.628     raeburn  16448:                     if ($sec eq '') {
                   16449:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16450:                     } else {
                   16451:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16452:                     }
1.443     albertel 16453:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16454:                     if ($sec eq '') {
                   16455:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16456:                     } else {
                   16457:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16458:                     }
1.443     albertel 16459:                 } else {
1.628     raeburn  16460:                     if ($sec eq '') {
                   16461:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16462:                     } else {
                   16463:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16464:                     }
1.443     albertel 16465:                 }
                   16466:             } else {
1.1115    raeburn  16467:                 if ($secchange) { 
1.628     raeburn  16468:                     $$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;
                   16469:                 } else {
                   16470:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16471:                 }
1.443     albertel 16472:             }
                   16473:             $result = $modify_section_result;
                   16474:         } elsif ($secchange == 1) {
1.628     raeburn  16475:             if ($oldsec eq '') {
1.1103    raeburn  16476:                 $$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  16477:             } else {
                   16478:                 $$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;
                   16479:             }
1.626     raeburn  16480:             if ($expire_role_result eq 'refused') {
                   16481:                 my $newsecurl = '/'.$cid;
                   16482:                 $newsecurl =~ s/\_/\//g;
                   16483:                 if ($sec ne '') {
                   16484:                     $newsecurl.='/'.$sec;
                   16485:                 }
                   16486:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16487:                     if ($sec eq '') {
                   16488:                         $$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;
                   16489:                     } else {
                   16490:                         $$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;
                   16491:                     }
                   16492:                 }
                   16493:             }
1.443     albertel 16494:         }
                   16495:     } else {
1.626     raeburn  16496:         $$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 16497:         $result = "error: incomplete course id\n";
                   16498:     }
                   16499:     return $result;
                   16500: }
                   16501: 
1.1108    raeburn  16502: sub show_role_extent {
                   16503:     my ($scope,$context,$role) = @_;
                   16504:     $scope =~ s{^/}{};
                   16505:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16506:     push(@courseroles,'co');
                   16507:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16508:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16509:         $scope =~ s{/}{_};
                   16510:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16511:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16512:         my ($audom,$auname) = split(/\//,$scope);
                   16513:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16514:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16515:     } else {
                   16516:         $scope =~ s{/$}{};
                   16517:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16518:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16519:     }
                   16520: }
                   16521: 
1.443     albertel 16522: ############################################################
                   16523: ############################################################
                   16524: 
1.566     albertel 16525: sub check_clone {
1.578     raeburn  16526:     my ($args,$linefeed) = @_;
1.566     albertel 16527:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16528:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16529:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16530:     my $clonetitle;
                   16531:     my @clonemsg;
1.566     albertel 16532:     my $can_clone = 0;
1.944     raeburn  16533:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16534:     if ($lctype ne 'community') {
                   16535:         $lctype = 'course';
                   16536:     }
1.566     albertel 16537:     if ($clonehome eq 'no_host') {
1.944     raeburn  16538:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16539:             push(@clonemsg,({
                   16540:                               mt => 'No new community created.',
                   16541:                               args => [],
                   16542:                             },
                   16543:                             {
                   16544:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16545:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16546:                             }));
1.908     raeburn  16547:         } else {
1.1344    raeburn  16548:             push(@clonemsg,({
                   16549:                               mt => 'No new course created.',
                   16550:                               args => [],
                   16551:                             },
                   16552:                             {
                   16553:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16554:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16555:                             }));
                   16556:         }
1.566     albertel 16557:     } else {
                   16558: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16559:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16560:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16561:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16562:                 push(@clonemsg,({
                   16563:                                   mt => 'No new community created.',
                   16564:                                   args => [],
                   16565:                                 },
                   16566:                                 {
                   16567:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16568:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16569:                                 }));
                   16570:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16571:             }
                   16572:         }
1.1262    raeburn  16573: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16574:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16575: 	    $can_clone = 1;
                   16576: 	} else {
1.1221    raeburn  16577: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16578: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16579:             if ($clonehash{'cloners'} eq '') {
                   16580:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16581:                 if ($domdefs{'canclone'}) {
                   16582:                     unless ($domdefs{'canclone'} eq 'none') {
                   16583:                         if ($domdefs{'canclone'} eq 'domain') {
                   16584:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16585:                                 $can_clone = 1;
                   16586:                             }
                   16587:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16588:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16589:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16590:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16591:                                 $can_clone = 1;
                   16592:                             }
                   16593:                         }
                   16594:                     }
                   16595:                 }
1.578     raeburn  16596:             } else {
1.1221    raeburn  16597: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16598:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16599:                     $can_clone = 1;
1.1221    raeburn  16600:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16601:                     $can_clone = 1;
1.1225    raeburn  16602:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16603:                     $can_clone = 1;
1.1221    raeburn  16604:                 }
                   16605:                 unless ($can_clone) {
1.1225    raeburn  16606:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16607:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16608:                         my (%gotdomdefaults,%gotcodedefaults);
                   16609:                         foreach my $cloner (@cloners) {
                   16610:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16611:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16612:                                 my (%codedefaults,@code_order);
                   16613:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16614:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16615:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16616:                                     }
                   16617:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16618:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16619:                                     }
                   16620:                                 } else {
                   16621:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16622:                                                                             \%codedefaults,
                   16623:                                                                             \@code_order);
                   16624:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16625:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16626:                                 }
                   16627:                                 if (@code_order > 0) {
                   16628:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16629:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16630:                                                                                 $args->{'crscode'})) {
                   16631:                                         $can_clone = 1;
                   16632:                                         last;
                   16633:                                     }
                   16634:                                 }
                   16635:                             }
                   16636:                         }
                   16637:                     }
1.1225    raeburn  16638:                 }
                   16639:             }
                   16640:             unless ($can_clone) {
                   16641:                 my $ccrole = 'cc';
                   16642:                 if ($args->{'crstype'} eq 'Community') {
                   16643:                     $ccrole = 'co';
                   16644:                 }
                   16645: 	        my %roleshash =
                   16646: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16647: 					          $args->{'ccdomain'},
                   16648:                                                   'userroles',['active'],[$ccrole],
                   16649: 					          [$args->{'clonedomain'}]);
                   16650: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16651:                     $can_clone = 1;
                   16652:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16653:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16654:                     $can_clone = 1;
1.1221    raeburn  16655:                 }
                   16656:             }
                   16657:             unless ($can_clone) {
                   16658:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16659:                     push(@clonemsg,({
                   16660:                                       mt => 'No new community created.',
                   16661:                                       args => [],
                   16662:                                     },
                   16663:                                     {
                   16664:                                       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]).',
                   16665:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16666:                                     }));
1.942     raeburn  16667:                 } else {
1.1344    raeburn  16668:                     push(@clonemsg,({
                   16669:                                       mt => 'No new course created.',
                   16670:                                       args => [],
                   16671:                                     },
                   16672:                                     {
                   16673:                                       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]).',
                   16674:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16675:                                     }));
1.1221    raeburn  16676:                 }
1.566     albertel 16677: 	    }
1.578     raeburn  16678:         }
1.566     albertel 16679:     }
1.1344    raeburn  16680:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16681: }
                   16682: 
1.444     albertel 16683: sub construct_course {
1.1262    raeburn  16684:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16685:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16686:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16687:     my $linefeed =  '<br />'."\n";
                   16688:     if ($context eq 'auto') {
                   16689:         $linefeed = "\n";
                   16690:     }
1.566     albertel 16691: 
                   16692: #
                   16693: # Are we cloning?
                   16694: #
1.1344    raeburn  16695:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16696:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16697: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16698:         if (!$can_clone) {
1.1344    raeburn  16699: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16700: 	}
                   16701:     }
                   16702: 
1.444     albertel 16703: #
                   16704: # Open course
                   16705: #
1.1239    raeburn  16706:     my $showncrstype;
                   16707:     if ($args->{'crstype'} eq 'Placement') {
                   16708:         $showncrstype = 'placement test'; 
                   16709:     } else {  
                   16710:         $showncrstype = lc($args->{'crstype'});
                   16711:     }
1.444     albertel 16712:     my %cenv=();
                   16713:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16714:                                              $args->{'cdescr'},
                   16715:                                              $args->{'curl'},
                   16716:                                              $args->{'course_home'},
                   16717:                                              $args->{'nonstandard'},
                   16718:                                              $args->{'crscode'},
                   16719:                                              $args->{'ccuname'}.':'.
                   16720:                                              $args->{'ccdomain'},
1.882     raeburn  16721:                                              $args->{'crstype'},
1.1344    raeburn  16722:                                              $cnum,$context,$category,
                   16723:                                              $callercontext);
1.444     albertel 16724: 
                   16725:     # Note: The testing routines depend on this being output; see 
                   16726:     # Utils::Course. This needs to at least be output as a comment
                   16727:     # if anyone ever decides to not show this, and Utils::Course::new
                   16728:     # will need to be suitably modified.
1.1344    raeburn  16729:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16730:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16731:     } else {
                   16732:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16733:     }
1.943     raeburn  16734:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16735:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16736:     }
                   16737: 
1.444     albertel 16738: #
                   16739: # Check if created correctly
                   16740: #
1.479     albertel 16741:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16742:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16743:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16744:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16745:             $outcome .= &mt_user($user_lh,
                   16746:                             'Course creation failed, unrecognized course home server.');
                   16747:         } else {
                   16748:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16749:         }
                   16750:         $outcome .= $linefeed;
                   16751:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16752:     }
1.541     raeburn  16753:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16754: 
1.444     albertel 16755: #
1.566     albertel 16756: # Do the cloning
                   16757: #   
1.1344    raeburn  16758:     my @clonemsg;
1.566     albertel 16759:     if ($can_clone && $cloneid) {
1.1344    raeburn  16760:         push(@clonemsg,
                   16761:                       {
                   16762:                           mt => 'Created [_1] by cloning from [_2]',
                   16763:                           args => [$showncrstype,$clonetitle],
                   16764:                       });
1.566     albertel 16765: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16766: # Copy all files
1.1344    raeburn  16767:         my @info =
                   16768: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16769: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16770:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16771:                                                      $args->{'tinyurls'});
                   16772:         if (@info) {
                   16773:             push(@clonemsg,@info);
                   16774:         }
1.444     albertel 16775: # Restore URL
1.566     albertel 16776: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16777: # Restore title
1.566     albertel 16778: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16779: # Restore creation date, creator and creation context.
                   16780:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16781:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16782:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16783: # Mark as cloned
1.566     albertel 16784: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16785: # Need to clone grading mode
                   16786:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16787:         $cenv{'grading'}=$newenv{'grading'};
                   16788: # Do not clone these environment entries
                   16789:         &Apache::lonnet::del('environment',
                   16790:                   ['default_enrollment_start_date',
                   16791:                    'default_enrollment_end_date',
                   16792:                    'question.email',
                   16793:                    'policy.email',
                   16794:                    'comment.email',
                   16795:                    'pch.users.denied',
1.725     raeburn  16796:                    'plc.users.denied',
                   16797:                    'hidefromcat',
1.1121    raeburn  16798:                    'checkforpriv',
1.1355    raeburn  16799:                    'categories'],
1.638     www      16800:                    $$crsudom,$$crsunum);
1.1170    raeburn  16801:         if ($args->{'textbook'}) {
                   16802:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16803:         }
1.444     albertel 16804:     }
1.566     albertel 16805: 
1.444     albertel 16806: #
                   16807: # Set environment (will override cloned, if existing)
                   16808: #
                   16809:     my @sections = ();
                   16810:     my @xlists = ();
                   16811:     if ($args->{'crstype'}) {
                   16812:         $cenv{'type'}=$args->{'crstype'};
                   16813:     }
1.1371    raeburn  16814:     if ($args->{'lti'}) {
                   16815:         $cenv{'internal.lti'}=$args->{'lti'};
                   16816:     }
1.444     albertel 16817:     if ($args->{'crsid'}) {
                   16818:         $cenv{'courseid'}=$args->{'crsid'};
                   16819:     }
                   16820:     if ($args->{'crscode'}) {
                   16821:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16822:     }
                   16823:     if ($args->{'crsquota'} ne '') {
                   16824:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16825:     } else {
                   16826:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16827:     }
                   16828:     if ($args->{'ccuname'}) {
                   16829:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16830:                                         ':'.$args->{'ccdomain'};
                   16831:     } else {
                   16832:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16833:     }
1.1116    raeburn  16834:     if ($args->{'defaultcredits'}) {
                   16835:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16836:     }
1.444     albertel 16837:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16838:     if ($args->{'crssections'}) {
                   16839:         $cenv{'internal.sectionnums'} = '';
                   16840:         if ($args->{'crssections'} =~ m/,/) {
                   16841:             @sections = split/,/,$args->{'crssections'};
                   16842:         } else {
                   16843:             $sections[0] = $args->{'crssections'};
                   16844:         }
                   16845:         if (@sections > 0) {
                   16846:             foreach my $item (@sections) {
                   16847:                 my ($sec,$gp) = split/:/,$item;
                   16848:                 my $class = $args->{'crscode'}.$sec;
                   16849:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16850:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16851:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16852:                     push(@badclasses,$class);
1.444     albertel 16853:                 }
                   16854:             }
                   16855:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16856:         }
                   16857:     }
                   16858: # do not hide course coordinator from staff listing, 
                   16859: # even if privileged
                   16860:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16861: # add course coordinator's domain to domains to check for privileged users
                   16862: # if different to course domain
                   16863:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16864:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16865:     }
1.444     albertel 16866: # add crosslistings
                   16867:     if ($args->{'crsxlist'}) {
                   16868:         $cenv{'internal.crosslistings'}='';
                   16869:         if ($args->{'crsxlist'} =~ m/,/) {
                   16870:             @xlists = split/,/,$args->{'crsxlist'};
                   16871:         } else {
                   16872:             $xlists[0] = $args->{'crsxlist'};
                   16873:         }
                   16874:         if (@xlists > 0) {
                   16875:             foreach my $item (@xlists) {
                   16876:                 my ($xl,$gp) = split/:/,$item;
                   16877:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16878:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16879:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16880:                     push(@badclasses,$xl);
1.444     albertel 16881:                 }
                   16882:             }
                   16883:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16884:         }
                   16885:     }
                   16886:     if ($args->{'autoadds'}) {
                   16887:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16888:     }
                   16889:     if ($args->{'autodrops'}) {
                   16890:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16891:     }
                   16892: # check for notification of enrollment changes
                   16893:     my @notified = ();
                   16894:     if ($args->{'notify_owner'}) {
                   16895:         if ($args->{'ccuname'} ne '') {
                   16896:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16897:         }
                   16898:     }
                   16899:     if ($args->{'notify_dc'}) {
                   16900:         if ($uname ne '') { 
1.630     raeburn  16901:             push(@notified,$uname.':'.$udom);
1.444     albertel 16902:         }
                   16903:     }
                   16904:     if (@notified > 0) {
                   16905:         my $notifylist;
                   16906:         if (@notified > 1) {
                   16907:             $notifylist = join(',',@notified);
                   16908:         } else {
                   16909:             $notifylist = $notified[0];
                   16910:         }
                   16911:         $cenv{'internal.notifylist'} = $notifylist;
                   16912:     }
                   16913:     if (@badclasses > 0) {
                   16914:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16915:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16916:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16917:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16918:         );
1.1264    raeburn  16919:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16920:                            &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  16921:         if ($context eq 'auto') {
                   16922:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16923:         } else {
1.566     albertel 16924:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16925:         }
                   16926:         foreach my $item (@badclasses) {
1.541     raeburn  16927:             if ($context eq 'auto') {
1.1261    raeburn  16928:                 $outcome .= " - $item\n";
1.541     raeburn  16929:             } else {
1.1261    raeburn  16930:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16931:             }
1.1261    raeburn  16932:         }
                   16933:         if ($context eq 'auto') {
                   16934:             $outcome .= $linefeed;
                   16935:         } else {
                   16936:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16937:         } 
1.444     albertel 16938:     }
                   16939:     if ($args->{'no_end_date'}) {
                   16940:         $args->{'endaccess'} = 0;
                   16941:     }
                   16942:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16943:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16944:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16945:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16946:     if ($args->{'showphotos'}) {
                   16947:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16948:     }
                   16949:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16950:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16951:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16952:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16953:             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'); 
                   16954:             if ($context eq 'auto') {
                   16955:                 $outcome .= $krb_msg;
                   16956:             } else {
1.566     albertel 16957:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16958:             }
                   16959:             $outcome .= $linefeed;
1.444     albertel 16960:         }
                   16961:     }
                   16962:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16963:        if ($args->{'setpolicy'}) {
                   16964:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16965:        }
                   16966:        if ($args->{'setcontent'}) {
                   16967:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16968:        }
1.1251    raeburn  16969:        if ($args->{'setcomment'}) {
                   16970:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16971:        }
1.444     albertel 16972:     }
                   16973:     if ($args->{'reshome'}) {
                   16974: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16975: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16976:     }
                   16977: #
                   16978: # course has keyed access
                   16979: #
                   16980:     if ($args->{'setkeys'}) {
                   16981:        $cenv{'keyaccess'}='yes';
                   16982:     }
                   16983: # if specified, key authority is not course, but user
                   16984: # only active if keyaccess is yes
                   16985:     if ($args->{'keyauth'}) {
1.487     albertel 16986: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16987: 	$user = &LONCAPA::clean_username($user);
                   16988: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16989: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16990: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16991: 	}
                   16992:     }
                   16993: 
1.1166    raeburn  16994: #
1.1167    raeburn  16995: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16996: #
                   16997:     if ($args->{'uniquecode'}) {
                   16998:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16999:         if ($code) {
                   17000:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17001:             my %crsinfo =
                   17002:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17003:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17004:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17005:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17006:             } 
1.1166    raeburn  17007:             if (ref($coderef)) {
                   17008:                 $$coderef = $code;
                   17009:             }
                   17010:         }
                   17011:     }
                   17012: 
1.444     albertel 17013:     if ($args->{'disresdis'}) {
                   17014:         $cenv{'pch.roles.denied'}='st';
                   17015:     }
                   17016:     if ($args->{'disablechat'}) {
                   17017:         $cenv{'plc.roles.denied'}='st';
                   17018:     }
                   17019: 
                   17020:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17021:     # course
                   17022:     $cenv{'course.helper.not.run'} = 1;
                   17023:     #
                   17024:     # Use new Randomseed
                   17025:     #
                   17026:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17027:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17028:     #
                   17029:     # The encryption code and receipt prefix for this course
                   17030:     #
                   17031:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17032:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17033:     #
                   17034:     # By default, use standard grading
                   17035:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17036: 
1.541     raeburn  17037:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17038:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17039: #
                   17040: # Open all assignments
                   17041: #
                   17042:     if ($args->{'openall'}) {
1.1341    raeburn  17043:        my $opendate = time;
                   17044:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17045:            $opendate = $args->{'openallfrom'};
                   17046:        }
1.444     albertel 17047:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17048:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17049:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17050:        $outcome .= &mt('All assignments open starting [_1]',
                   17051:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17052:                    &Apache::lonnet::cput
                   17053:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17054:    }
                   17055: #
                   17056: # Set first page
                   17057: #
                   17058:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17059: 	    || ($cloneid)) {
1.445     albertel 17060: 	use LONCAPA::map;
1.444     albertel 17061: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17062: 
                   17063: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17064:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17065: 
1.444     albertel 17066:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17067:         my $title; my $url;
                   17068:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17069: 	    $title=&mt('Syllabus');
1.444     albertel 17070:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17071:         } else {
1.963     raeburn  17072:             $title=&mt('Table of Contents');
1.444     albertel 17073:             $url='/adm/navmaps';
                   17074:         }
1.445     albertel 17075: 
                   17076:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17077: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17078: 
                   17079: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17080:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17081:     }
1.566     albertel 17082: 
1.1237    raeburn  17083: # 
                   17084: # Set params for Placement Tests
                   17085: #
1.1239    raeburn  17086:     if ($args->{'crstype'} eq 'Placement') {
                   17087:        my %storecontent; 
                   17088:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17089:        my %defaults = (
                   17090:                         buttonshide   => { value => 'yes',
                   17091:                                            type => 'string_yesno',},
                   17092:                         type          => { value => 'randomizetry',
                   17093:                                            type  => 'string_questiontype',},
                   17094:                         maxtries      => { value => 1,
                   17095:                                            type => 'int_pos',},
                   17096:                         problemstatus => { value => 'no',
                   17097:                                            type  => 'string_problemstatus',},
                   17098:                       );
                   17099:        foreach my $key (keys(%defaults)) {
                   17100:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17101:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17102:        }
1.1237    raeburn  17103:        &Apache::lonnet::cput
                   17104:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17105:     }
                   17106: 
1.1344    raeburn  17107:     return (1,$outcome,\@clonemsg);
1.444     albertel 17108: }
                   17109: 
1.1166    raeburn  17110: sub make_unique_code {
                   17111:     my ($cdom,$cnum) = @_;
                   17112:     # get lock on uniquecodes db
                   17113:     my $lockhash = {
                   17114:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17115:                                                   ':'.$env{'user.domain'},
                   17116:                    };
                   17117:     my $tries = 0;
                   17118:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17119:     my ($code,$error);
                   17120:   
                   17121:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17122:         $tries ++;
                   17123:         sleep 1;
                   17124:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17125:     }
                   17126:     if ($gotlock eq 'ok') {
                   17127:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17128:         my $gotcode;
                   17129:         my $attempts = 0;
                   17130:         while ((!$gotcode) && ($attempts < 100)) {
                   17131:             $code = &generate_code();
                   17132:             if (!exists($currcodes{$code})) {
                   17133:                 $gotcode = 1;
                   17134:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17135:                     $error = 'nostore';
                   17136:                 }
                   17137:             }
                   17138:             $attempts ++;
                   17139:         }
                   17140:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17141:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17142:     } else {
                   17143:         $error = 'nolock';
                   17144:     }
                   17145:     return ($code,$error);
                   17146: }
                   17147: 
                   17148: sub generate_code {
                   17149:     my $code;
                   17150:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17151:     for (my $i=0; $i<6; $i++) {
                   17152:         my $lettnum = int (rand 2);
                   17153:         my $item = '';
                   17154:         if ($lettnum) {
                   17155:             $item = $letts[int( rand(18) )];
                   17156:         } else {
                   17157:             $item = 1+int( rand(8) );
                   17158:         }
                   17159:         $code .= $item;
                   17160:     }
                   17161:     return $code;
                   17162: }
                   17163: 
1.444     albertel 17164: ############################################################
                   17165: ############################################################
                   17166: 
1.1237    raeburn  17167: # Community, Course and Placement Test
1.378     raeburn  17168: sub course_type {
                   17169:     my ($cid) = @_;
                   17170:     if (!defined($cid)) {
                   17171:         $cid = $env{'request.course.id'};
                   17172:     }
1.404     albertel 17173:     if (defined($env{'course.'.$cid.'.type'})) {
                   17174:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17175:     } else {
                   17176:         return 'Course';
1.377     raeburn  17177:     }
                   17178: }
1.156     albertel 17179: 
1.406     raeburn  17180: sub group_term {
                   17181:     my $crstype = &course_type();
                   17182:     my %names = (
                   17183:                   'Course' => 'group',
1.865     raeburn  17184:                   'Community' => 'group',
1.1237    raeburn  17185:                   'Placement' => 'group',
1.406     raeburn  17186:                 );
                   17187:     return $names{$crstype};
                   17188: }
                   17189: 
1.902     raeburn  17190: sub course_types {
1.1310    raeburn  17191:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17192:     my %typename = (
                   17193:                          official   => 'Official course',
                   17194:                          unofficial => 'Unofficial course',
                   17195:                          community  => 'Community',
1.1165    raeburn  17196:                          textbook   => 'Textbook course',
1.1237    raeburn  17197:                          placement  => 'Placement test',
1.1310    raeburn  17198:                          lti        => 'LTI provider',
1.902     raeburn  17199:                    );
                   17200:     return (\@types,\%typename);
                   17201: }
                   17202: 
1.156     albertel 17203: sub icon {
                   17204:     my ($file)=@_;
1.505     albertel 17205:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17206:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17207:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17208:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17209: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17210: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17211: 	            $curfext.".gif") {
                   17212: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17213: 		$curfext.".gif";
                   17214: 	}
                   17215:     }
1.249     albertel 17216:     return &lonhttpdurl($iconname);
1.154     albertel 17217: } 
1.84      albertel 17218: 
1.575     albertel 17219: sub lonhttpdurl {
1.692     www      17220: #
                   17221: # Had been used for "small fry" static images on separate port 8080.
                   17222: # Modify here if lightweight http functionality desired again.
                   17223: # Currently eliminated due to increasing firewall issues.
                   17224: #
1.575     albertel 17225:     my ($url)=@_;
1.692     www      17226:     return $url;
1.215     albertel 17227: }
                   17228: 
1.213     albertel 17229: sub connection_aborted {
                   17230:     my ($r)=@_;
                   17231:     $r->print(" ");$r->rflush();
                   17232:     my $c = $r->connection;
                   17233:     return $c->aborted();
                   17234: }
                   17235: 
1.221     foxr     17236: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17237: #    strings as 'strings'.
                   17238: sub escape_single {
1.221     foxr     17239:     my ($input) = @_;
1.223     albertel 17240:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17241:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17242:     return $input;
                   17243: }
1.223     albertel 17244: 
1.222     foxr     17245: #  Same as escape_single, but escape's "'s  This 
                   17246: #  can be used for  "strings"
                   17247: sub escape_double {
                   17248:     my ($input) = @_;
                   17249:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17250:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17251:     return $input;
                   17252: }
1.223     albertel 17253:  
1.222     foxr     17254: #   Escapes the last element of a full URL.
                   17255: sub escape_url {
                   17256:     my ($url)   = @_;
1.238     raeburn  17257:     my @urlslices = split(/\//, $url,-1);
1.369     www      17258:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17259:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17260: }
1.462     albertel 17261: 
1.820     raeburn  17262: sub compare_arrays {
                   17263:     my ($arrayref1,$arrayref2) = @_;
                   17264:     my (@difference,%count);
                   17265:     @difference = ();
                   17266:     %count = ();
                   17267:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17268:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17269:         foreach my $element (keys(%count)) {
                   17270:             if ($count{$element} == 1) {
                   17271:                 push(@difference,$element);
                   17272:             }
                   17273:         }
                   17274:     }
                   17275:     return @difference;
                   17276: }
                   17277: 
1.1322    raeburn  17278: sub lon_status_items {
                   17279:     my %defaults = (
                   17280:                      E         => 100,
                   17281:                      W         => 4,
                   17282:                      N         => 1,
1.1324    raeburn  17283:                      U         => 5,
1.1322    raeburn  17284:                      threshold => 200,
                   17285:                      sysmail   => 2500,
                   17286:                    );
                   17287:     my %names = (
                   17288:                    E => 'Errors',
                   17289:                    W => 'Warnings',
                   17290:                    N => 'Notices',
1.1324    raeburn  17291:                    U => 'Unsent',
1.1322    raeburn  17292:                 );
                   17293:     return (\%defaults,\%names);
                   17294: }
                   17295: 
1.817     bisitz   17296: # -------------------------------------------------------- Initialize user login
1.462     albertel 17297: sub init_user_environment {
1.463     albertel 17298:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17299:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17300: 
                   17301:     my $public=($username eq 'public' && $domain eq 'public');
                   17302: 
1.1062    raeburn  17303:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17304:     my $now=time;
                   17305: 
                   17306:     if ($public) {
                   17307: 	my $max_public=100;
                   17308: 	my $oldest;
                   17309: 	my $oldest_time=0;
                   17310: 	for(my $next=1;$next<=$max_public;$next++) {
                   17311: 	    if (-e $lonids."/publicuser_$next.id") {
                   17312: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17313: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17314: 		    $oldest_time=$mtime;
                   17315: 		    $oldest=$next;
                   17316: 		}
                   17317: 	    } else {
                   17318: 		$cookie="publicuser_$next";
                   17319: 		last;
                   17320: 	    }
                   17321: 	}
                   17322: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17323:     } else {
1.1275    raeburn  17324: 	# See if old ID present, if so, remove if this isn't a robot,
                   17325: 	# killing any existing non-robot sessions
1.463     albertel 17326: 	if (!$args->{'robot'}) {
                   17327: 	    opendir(DIR,$lonids);
                   17328: 	    while ($filename=readdir(DIR)) {
                   17329: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17330:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17331:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17332:                         my $linkedfile;
1.1320    raeburn  17333:                         if (exists($oldenv{'user.linkedenv'})) {
                   17334:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17335:                         }
1.1320    raeburn  17336:                         untie(%oldenv);
                   17337:                         if (unlink("$lonids/$filename")) {
                   17338:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17339:                                 if (-l "$lonids/$linkedfile.id") {
                   17340:                                     unlink("$lonids/$linkedfile.id");
                   17341:                                 }
1.1295    raeburn  17342:                             }
                   17343:                         }
                   17344:                     } else {
                   17345:                         unlink($lonids.'/'.$filename);
                   17346:                     }
1.463     albertel 17347: 		}
1.462     albertel 17348: 	    }
1.463     albertel 17349: 	    closedir(DIR);
1.1204    raeburn  17350: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17351:             my $namespace = 'nohist_courseeditor';
                   17352:             my $lockingkey = 'paste'."\0".'locked_num';
                   17353:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17354:                                                 $domain,$username);
                   17355:             if (exists($lockhash{$lockingkey})) {
                   17356:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17357:                 unless ($delresult eq 'ok') {
                   17358:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17359:                 }
                   17360:             }
1.462     albertel 17361: 	}
                   17362: # Give them a new cookie
1.463     albertel 17363: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17364: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17365: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17366:     
                   17367: # Initialize roles
                   17368: 
1.1062    raeburn  17369: 	($userroles,$firstaccenv,$timerintenv) = 
                   17370:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17371:     }
                   17372: # ------------------------------------ Check browser type and MathML capability
                   17373: 
1.1194    raeburn  17374:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17375:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17376: 
                   17377: # ------------------------------------------------------------- Get environment
                   17378: 
                   17379:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17380:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17381:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17382: 	undef(%userenv);
                   17383:     }
                   17384:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17385: 	$form->{'interface'}=$userenv{'interface'};
                   17386:     }
                   17387:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17388: 
                   17389: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17390:     foreach my $option ('interface','localpath','localres') {
                   17391:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17392:     }
                   17393: # --------------------------------------------------------- Write first profile
                   17394: 
                   17395:     {
1.1350    raeburn  17396:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17397: 	my %initial_env = 
                   17398: 	    ("user.name"          => $username,
                   17399: 	     "user.domain"        => $domain,
                   17400: 	     "user.home"          => $authhost,
                   17401: 	     "browser.type"       => $clientbrowser,
                   17402: 	     "browser.version"    => $clientversion,
                   17403: 	     "browser.mathml"     => $clientmathml,
                   17404: 	     "browser.unicode"    => $clientunicode,
                   17405: 	     "browser.os"         => $clientos,
1.1137    raeburn  17406:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17407:              "browser.info"       => $clientinfo,
1.1194    raeburn  17408:              "browser.osversion"  => $clientosversion,
1.462     albertel 17409: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17410: 	     "request.course.fn"  => '',
                   17411: 	     "request.course.uri" => '',
                   17412: 	     "request.course.sec" => '',
                   17413: 	     "request.role"       => 'cm',
                   17414: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17415: 	     "request.host"       => $ip,);
1.462     albertel 17416: 
                   17417:         if ($form->{'localpath'}) {
                   17418: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17419: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17420:         }
                   17421: 	
                   17422: 	if ($form->{'interface'}) {
                   17423: 	    $form->{'interface'}=~s/\W//gs;
                   17424: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17425: 	    $env{'browser.interface'}=$form->{'interface'};
                   17426: 	}
                   17427: 
1.1157    raeburn  17428:         if ($form->{'iptoken'}) {
                   17429:             my $lonhost = $r->dir_config('lonHostID');
                   17430:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17431:             $env{'user.noloadbalance'} = $lonhost;
                   17432:         }
                   17433: 
1.1268    raeburn  17434:         if ($form->{'noloadbalance'}) {
                   17435:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17436:             my $hosthere = $form->{'noloadbalance'};
                   17437:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17438:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17439:                 $env{'user.noloadbalance'} = $hosthere;
                   17440:             }
                   17441:         }
                   17442: 
1.1016    raeburn  17443:         unless ($domain eq 'public') {
1.1273    raeburn  17444:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17445:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17446: 
1.1387  ! raeburn  17447:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1273    raeburn  17448:                 $userenv{'availabletools.'.$tool} = 
                   17449:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17450:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17451:             }
1.980     raeburn  17452: 
1.1311    raeburn  17453:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17454:                 $userenv{'canrequest.'.$crstype} =
                   17455:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17456:                                                       'reload','requestcourses',
                   17457:                                                       \%userenv,\%domdef,\%is_adv);
                   17458:             }
1.724     raeburn  17459: 
1.1273    raeburn  17460:             $userenv{'canrequest.author'} =
                   17461:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17462:                                                   'reload','requestauthor',
1.980     raeburn  17463:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17464:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17465:                                                  $domain,$username);
                   17466:             my $reqstatus = $reqauthor{'author_status'};
                   17467:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17468:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17469:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17470:                                                       $reqauthor{'author'}{'timestamp'};
                   17471:                 }
1.1092    raeburn  17472:             }
1.1287    raeburn  17473:             my ($types,$typename) = &course_types();
                   17474:             if (ref($types) eq 'ARRAY') {
                   17475:                 my @options = ('approval','validate','autolimit');
                   17476:                 my $optregex = join('|',@options);
                   17477:                 my (%willtrust,%trustchecked);
                   17478:                 foreach my $type (@{$types}) {
                   17479:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17480:                     if ($dom_str ne '') {
                   17481:                         my $updatedstr = '';
                   17482:                         my @possdomains = split(',',$dom_str);
                   17483:                         foreach my $entry (@possdomains) {
                   17484:                             my ($extdom,$extopt) = split(':',$entry);
                   17485:                             unless ($trustchecked{$extdom}) {
                   17486:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17487:                                 $trustchecked{$extdom} = 1;
                   17488:                             }
                   17489:                             if ($willtrust{$extdom}) {
                   17490:                                 $updatedstr .= $entry.',';
                   17491:                             }
                   17492:                         }
                   17493:                         $updatedstr =~ s/,$//;
                   17494:                         if ($updatedstr) {
                   17495:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17496:                         } else {
                   17497:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17498:                         }
                   17499:                     }
                   17500:                 }
                   17501:             }
1.1092    raeburn  17502:         }
1.462     albertel 17503: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17504: 
1.462     albertel 17505: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17506: 		 &GDBM_WRCREAT(),0640)) {
                   17507: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17508: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17509: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17510:             if (ref($firstaccenv) eq 'HASH') {
                   17511:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17512:             }
                   17513:             if (ref($timerintenv) eq 'HASH') {
                   17514:                 &_add_to_env(\%disk_env,$timerintenv);
                   17515:             }
1.463     albertel 17516: 	    if (ref($args->{'extra_env'})) {
                   17517: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17518: 	    }
1.462     albertel 17519: 	    untie(%disk_env);
                   17520: 	} else {
1.705     tempelho 17521: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17522: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17523: 	    return 'error: '.$!;
                   17524: 	}
                   17525:     }
                   17526:     $env{'request.role'}='cm';
                   17527:     $env{'request.role.adv'}=$env{'user.adv'};
                   17528:     $env{'browser.type'}=$clientbrowser;
                   17529: 
                   17530:     return $cookie;
                   17531: 
                   17532: }
                   17533: 
                   17534: sub _add_to_env {
                   17535:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17536:     if (ref($env_data) eq 'HASH') {
                   17537:         while (my ($key,$value) = each(%$env_data)) {
                   17538: 	    $idf->{$prefix.$key} = $value;
                   17539: 	    $env{$prefix.$key}   = $value;
                   17540:         }
1.462     albertel 17541:     }
                   17542: }
                   17543: 
1.685     tempelho 17544: # --- Get the symbolic name of a problem and the url
                   17545: sub get_symb {
                   17546:     my ($request,$silent) = @_;
1.726     raeburn  17547:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17548:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17549:     if ($symb eq '') {
                   17550:         if (!$silent) {
1.1071    raeburn  17551:             if (ref($request)) { 
                   17552:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17553:             }
1.685     tempelho 17554:             return ();
                   17555:         }
                   17556:     }
                   17557:     &Apache::lonenc::check_decrypt(\$symb);
                   17558:     return ($symb);
                   17559: }
                   17560: 
                   17561: # --------------------------------------------------------------Get annotation
                   17562: 
                   17563: sub get_annotation {
                   17564:     my ($symb,$enc) = @_;
                   17565: 
                   17566:     my $key = $symb;
                   17567:     if (!$enc) {
                   17568:         $key =
                   17569:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17570:     }
                   17571:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17572:     return $annotation{$key};
                   17573: }
                   17574: 
                   17575: sub clean_symb {
1.731     raeburn  17576:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17577: 
                   17578:     &Apache::lonenc::check_decrypt(\$symb);
                   17579:     my $enc = $env{'request.enc'};
1.731     raeburn  17580:     if ($delete_enc) {
1.730     raeburn  17581:         delete($env{'request.enc'});
                   17582:     }
1.685     tempelho 17583: 
                   17584:     return ($symb,$enc);
                   17585: }
1.462     albertel 17586: 
1.1181    raeburn  17587: ############################################################
                   17588: ############################################################
                   17589: 
                   17590: =pod
                   17591: 
                   17592: =head1 Routines for building display used to search for courses
                   17593: 
                   17594: 
                   17595: =over 4
                   17596: 
                   17597: =item * &build_filters()
                   17598: 
                   17599: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17600: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17601: and quotacheck.pl
                   17602: 
1.1181    raeburn  17603: 
                   17604: Inputs:
                   17605: 
                   17606: filterlist - anonymous array of fields to include as potential filters 
                   17607: 
                   17608: crstype - course type
                   17609: 
                   17610: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17611:               to pop-open a course selector (will contain "extra element"). 
                   17612: 
                   17613: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17614: 
                   17615: filter - anonymous hash of criteria and their values
                   17616: 
                   17617: action - form action
                   17618: 
                   17619: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17620: 
1.1182    raeburn  17621: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17622: 
                   17623: cloneruname - username of owner of new course who wants to clone
                   17624: 
                   17625: clonerudom - domain of owner of new course who wants to clone
                   17626: 
                   17627: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17628: 
                   17629: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17630: 
                   17631: codedom - domain
                   17632: 
                   17633: formname - value of form element named "form". 
                   17634: 
                   17635: fixeddom - domain, if fixed.
                   17636: 
                   17637: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17638: 
                   17639: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17640: 
                   17641: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17642: 
                   17643: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17644: 
                   17645: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17646: 
                   17647: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17648: 
                   17649: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17650: 
1.1182    raeburn  17651: 
1.1181    raeburn  17652: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17653: 
1.1182    raeburn  17654: 
1.1181    raeburn  17655: Side Effects: None
                   17656: 
                   17657: =cut
                   17658: 
                   17659: # ---------------------------------------------- search for courses based on last activity etc.
                   17660: 
                   17661: sub build_filters {
                   17662:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17663:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17664:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17665:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17666:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17667:     my ($list,$jscript);
1.1181    raeburn  17668:     my $onchange = 'javascript:updateFilters(this)';
                   17669:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17670:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17671:         $typeselectform,$instcodetitle);
                   17672:     if ($formname eq '') {
                   17673:         $formname = $caller;
                   17674:     }
                   17675:     foreach my $item (@{$filterlist}) {
                   17676:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17677:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17678:             if ($item eq 'domainfilter') {
                   17679:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17680:             } elsif ($item eq 'coursefilter') {
                   17681:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17682:             } elsif ($item eq 'ownerfilter') {
                   17683:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17684:             } elsif ($item eq 'ownerdomfilter') {
                   17685:                 $filter->{'ownerdomfilter'} =
                   17686:                     &LONCAPA::clean_domain($filter->{$item});
                   17687:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17688:                                                        'ownerdomfilter',1);
                   17689:             } elsif ($item eq 'personfilter') {
                   17690:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17691:             } elsif ($item eq 'persondomfilter') {
                   17692:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17693:                                                         'persondomfilter',1);
                   17694:             } else {
                   17695:                 $filter->{$item} =~ s/\W//g;
                   17696:             }
                   17697:             if (!$filter->{$item}) {
                   17698:                 $filter->{$item} = '';
                   17699:             }
                   17700:         }
                   17701:         if ($item eq 'domainfilter') {
                   17702:             my $allow_blank = 1;
                   17703:             if ($formname eq 'portform') {
                   17704:                 $allow_blank=0;
                   17705:             } elsif ($formname eq 'studentform') {
                   17706:                 $allow_blank=0;
                   17707:             }
                   17708:             if ($fixeddom) {
                   17709:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17710:                                     ' value="'.$codedom.'" />'.
                   17711:                                     &Apache::lonnet::domain($codedom,'description');
                   17712:             } else {
                   17713:                 $domainselectform = &select_dom_form($filter->{$item},
                   17714:                                                      'domainfilter',
                   17715:                                                       $allow_blank,'',$onchange);
                   17716:             }
                   17717:         } else {
                   17718:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17719:         }
                   17720:     }
                   17721: 
                   17722:     # last course activity filter and selection
                   17723:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17724: 
                   17725:     # course created filter and selection
                   17726:     if (exists($filter->{'createdfilter'})) {
                   17727:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17728:     }
                   17729: 
1.1239    raeburn  17730:     my $prefix = $crstype;
                   17731:     if ($crstype eq 'Placement') {
                   17732:         $prefix = 'Placement Test'
                   17733:     }
1.1181    raeburn  17734:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17735:                 'cac' => "$prefix Activity",
                   17736:                 'ccr' => "$prefix Created",
                   17737:                 'cde' => "$prefix Title",
                   17738:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17739:                 'ins' => 'Institutional Code',
                   17740:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17741:                 'cow' => "$prefix Owner/Co-owner",
                   17742:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17743:                 'cog' => 'Type',
                   17744:              );
                   17745: 
                   17746:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17747:         my $typeval = 'Course';
                   17748:         if ($crstype eq 'Community') {
                   17749:             $typeval = 'Community';
1.1239    raeburn  17750:         } elsif ($crstype eq 'Placement') {
                   17751:             $typeval = 'Placement';
1.1181    raeburn  17752:         }
                   17753:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17754:     } else {
                   17755:         $typeselectform =  '<select name="type" size="1"';
                   17756:         if ($onchange) {
                   17757:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17758:         }
                   17759:         $typeselectform .= '>'."\n";
1.1237    raeburn  17760:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17761:             my $shown;
                   17762:             if ($posstype eq 'Placement') {
                   17763:                 $shown = &mt('Placement Test');
                   17764:             } else {
                   17765:                 $shown = &mt($posstype);
                   17766:             }
1.1181    raeburn  17767:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17768:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17769:         }
                   17770:         $typeselectform.="</select>";
                   17771:     }
                   17772: 
                   17773:     my ($cloneableonlyform,$cloneabletitle);
                   17774:     if (exists($filter->{'cloneableonly'})) {
                   17775:         my $cloneableon = '';
                   17776:         my $cloneableoff = ' checked="checked"';
                   17777:         if ($filter->{'cloneableonly'}) {
                   17778:             $cloneableon = $cloneableoff;
                   17779:             $cloneableoff = '';
                   17780:         }
                   17781:         $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>';
                   17782:         if ($formname eq 'ccrs') {
1.1187    bisitz   17783:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17784:         } else {
                   17785:             $cloneabletitle = &mt('Cloneable by you');
                   17786:         }
                   17787:     }
                   17788:     my $officialjs;
                   17789:     if ($crstype eq 'Course') {
                   17790:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17791: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17792: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17793:             if ($codedom) { 
1.1181    raeburn  17794:                 $officialjs = 1;
                   17795:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17796:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17797:                                                                   $officialjs,$codetitlesref);
                   17798:                 if ($jscript) {
1.1182    raeburn  17799:                     $jscript = '<script type="text/javascript">'."\n".
                   17800:                                '// <![CDATA['."\n".
                   17801:                                $jscript."\n".
                   17802:                                '// ]]>'."\n".
                   17803:                                '</script>'."\n";
1.1181    raeburn  17804:                 }
                   17805:             }
                   17806:             if ($instcodeform eq '') {
                   17807:                 $instcodeform =
                   17808:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17809:                     $list->{'instcodefilter'}.'" />';
                   17810:                 $instcodetitle = $lt{'ins'};
                   17811:             } else {
                   17812:                 $instcodetitle = $lt{'inc'};
                   17813:             }
                   17814:             if ($fixeddom) {
                   17815:                 $instcodetitle .= '<br />('.$codedom.')';
                   17816:             }
                   17817:         }
                   17818:     }
                   17819:     my $output = qq|
                   17820: <form method="post" name="filterpicker" action="$action">
                   17821: <input type="hidden" name="form" value="$formname" />
                   17822: |;
                   17823:     if ($formname eq 'modifycourse') {
                   17824:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17825:                    '<input type="hidden" name="prevphase" value="'.
                   17826:                    $prevphase.'" />'."\n";
1.1198    musolffc 17827:     } elsif ($formname eq 'quotacheck') {
                   17828:         $output .= qq|
                   17829: <input type="hidden" name="sortby" value="" />
                   17830: <input type="hidden" name="sortorder" value="" />
                   17831: |;
                   17832:     } else {
1.1181    raeburn  17833:         my $name_input;
                   17834:         if ($cnameelement ne '') {
                   17835:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17836:                           $cnameelement.'" />';
                   17837:         }
                   17838:         $output .= qq|
1.1182    raeburn  17839: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17840: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17841: $name_input
                   17842: $roleelement
                   17843: $multelement
                   17844: $typeelement
                   17845: |;
                   17846:         if ($formname eq 'portform') {
                   17847:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17848:         }
                   17849:     }
                   17850:     if ($fixeddom) {
                   17851:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17852:     }
                   17853:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17854:     if ($sincefilterform) {
                   17855:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17856:                   .$sincefilterform
                   17857:                   .&Apache::lonhtmlcommon::row_closure();
                   17858:     }
                   17859:     if ($createdfilterform) {
                   17860:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17861:                   .$createdfilterform
                   17862:                   .&Apache::lonhtmlcommon::row_closure();
                   17863:     }
                   17864:     if ($domainselectform) {
                   17865:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17866:                   .$domainselectform
                   17867:                   .&Apache::lonhtmlcommon::row_closure();
                   17868:     }
                   17869:     if ($typeselectform) {
                   17870:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17871:             $output .= $typeselectform;
                   17872:         } else {
                   17873:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17874:                       .$typeselectform
                   17875:                       .&Apache::lonhtmlcommon::row_closure();
                   17876:         }
                   17877:     }
                   17878:     if ($instcodeform) {
                   17879:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17880:                   .$instcodeform
                   17881:                   .&Apache::lonhtmlcommon::row_closure();
                   17882:     }
                   17883:     if (exists($filter->{'ownerfilter'})) {
                   17884:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17885:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17886:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17887:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17888:                    $ownerdomselectform.'</td></tr></table>'.
                   17889:                    &Apache::lonhtmlcommon::row_closure();
                   17890:     }
                   17891:     if (exists($filter->{'personfilter'})) {
                   17892:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17893:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17894:                    '<input type="text" name="personfilter" size="20" value="'.
                   17895:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17896:                    $persondomselectform.'</td></tr></table>'.
                   17897:                    &Apache::lonhtmlcommon::row_closure();
                   17898:     }
                   17899:     if (exists($filter->{'coursefilter'})) {
                   17900:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17901:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17902:                   .$list->{'coursefilter'}.'" />'
                   17903:                   .&Apache::lonhtmlcommon::row_closure();
                   17904:     }
                   17905:     if ($cloneableonlyform) {
                   17906:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17907:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17908:     }
                   17909:     if (exists($filter->{'descriptfilter'})) {
                   17910:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17911:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17912:                   .$list->{'descriptfilter'}.'" />'
                   17913:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17914:     }
                   17915:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17916:                '<input type="hidden" name="updater" value="" />'."\n".
                   17917:                '<input type="submit" name="gosearch" value="'.
                   17918:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17919:     return $jscript.$clonewarning.$output;
                   17920: }
                   17921: 
                   17922: =pod 
                   17923: 
                   17924: =item * &timebased_select_form()
                   17925: 
1.1182    raeburn  17926: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17927: filter e.g., Course Activity, Course Created, when searching for courses
                   17928: or communities
                   17929: 
                   17930: Inputs:
                   17931: 
                   17932: item - name of form element (sincefilter or createdfilter)
                   17933: 
                   17934: filter - anonymous hash of criteria and their values
                   17935: 
                   17936: Returns: HTML for a select box contained a blank, then six time selections,
                   17937:          with value set in incoming form variables currently selected. 
                   17938: 
                   17939: Side Effects: None
                   17940: 
                   17941: =cut
                   17942: 
                   17943: sub timebased_select_form {
                   17944:     my ($item,$filter) = @_;
                   17945:     if (ref($filter) eq 'HASH') {
                   17946:         $filter->{$item} =~ s/[^\d-]//g;
                   17947:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17948:         return &select_form(
                   17949:                             $filter->{$item},
                   17950:                             $item,
                   17951:                             {      '-1' => '',
                   17952:                                 '86400' => &mt('today'),
                   17953:                                '604800' => &mt('last week'),
                   17954:                               '2592000' => &mt('last month'),
                   17955:                               '7776000' => &mt('last three months'),
                   17956:                              '15552000' => &mt('last six months'),
                   17957:                              '31104000' => &mt('last year'),
                   17958:                     'select_form_order' =>
                   17959:                            ['-1','86400','604800','2592000','7776000',
                   17960:                             '15552000','31104000']});
                   17961:     }
                   17962: }
                   17963: 
                   17964: =pod
                   17965: 
                   17966: =item * &js_changer()
                   17967: 
                   17968: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17969: when course type or domain is changed, and also to hide 'Searching ...' on
                   17970: page load completion for page showing search result.
1.1181    raeburn  17971: 
                   17972: Inputs: None
                   17973: 
1.1183    raeburn  17974: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17975: 
                   17976: Side Effects: None
                   17977: 
                   17978: =cut
                   17979: 
                   17980: sub js_changer {
                   17981:     return <<ENDJS;
                   17982: <script type="text/javascript">
                   17983: // <![CDATA[
                   17984: function updateFilters(caller) {
                   17985:     if (typeof(caller) != "undefined") {
                   17986:         document.filterpicker.updater.value = caller.name;
                   17987:     }
                   17988:     document.filterpicker.submit();
                   17989: }
1.1183    raeburn  17990: 
                   17991: function hideSearching() {
                   17992:     if (document.getElementById('searching')) {
                   17993:         document.getElementById('searching').style.display = 'none';
                   17994:     }
                   17995:     return;
                   17996: }
                   17997: 
1.1181    raeburn  17998: // ]]>
                   17999: </script>
                   18000: 
                   18001: ENDJS
                   18002: }
                   18003: 
                   18004: =pod
                   18005: 
1.1182    raeburn  18006: =item * &search_courses()
                   18007: 
                   18008: Process selected filters form course search form and pass to lonnet::courseiddump
                   18009: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18010: 
                   18011: Inputs:
                   18012: 
                   18013: dom - domain being searched 
                   18014: 
                   18015: type - course type ('Course' or 'Community' or '.' if any).
                   18016: 
                   18017: filter - anonymous hash of criteria and their values
                   18018: 
                   18019: numtitles - for institutional codes - number of categories
                   18020: 
                   18021: cloneruname - optional username of new course owner
                   18022: 
                   18023: clonerudom - optional domain of new course owner
                   18024: 
1.1221    raeburn  18025: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18026:             (used when DC is using course creation form)
                   18027: 
                   18028: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18029: 
1.1221    raeburn  18030: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18031:            (and so can clone automatically)
                   18032: 
                   18033: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18034: 
                   18035: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18036:               courses to clone 
1.1182    raeburn  18037: 
                   18038: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18039: 
                   18040: 
                   18041: Side Effects: None
                   18042: 
                   18043: =cut
                   18044: 
                   18045: 
                   18046: sub search_courses {
1.1221    raeburn  18047:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18048:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18049:     my (%courses,%showcourses,$cloner);
                   18050:     if (($filter->{'ownerfilter'} ne '') ||
                   18051:         ($filter->{'ownerdomfilter'} ne '')) {
                   18052:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18053:                                        $filter->{'ownerdomfilter'};
                   18054:     }
                   18055:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18056:         if (!$filter->{$item}) {
                   18057:             $filter->{$item}='.';
                   18058:         }
                   18059:     }
                   18060:     my $now = time;
                   18061:     my $timefilter =
                   18062:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18063:     my ($createdbefore,$createdafter);
                   18064:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18065:         $createdbefore = $now;
                   18066:         $createdafter = $now-$filter->{'createdfilter'};
                   18067:     }
                   18068:     my ($instcodefilter,$regexpok);
                   18069:     if ($numtitles) {
                   18070:         if ($env{'form.official'} eq 'on') {
                   18071:             $instcodefilter =
                   18072:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18073:             $regexpok = 1;
                   18074:         } elsif ($env{'form.official'} eq 'off') {
                   18075:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18076:             unless ($instcodefilter eq '') {
                   18077:                 $regexpok = -1;
                   18078:             }
                   18079:         }
                   18080:     } else {
                   18081:         $instcodefilter = $filter->{'instcodefilter'};
                   18082:     }
                   18083:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18084:     if ($type eq '') { $type = '.'; }
                   18085: 
                   18086:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18087:         $cloner = $cloneruname.':'.$clonerudom;
                   18088:     }
                   18089:     %courses = &Apache::lonnet::courseiddump($dom,
                   18090:                                              $filter->{'descriptfilter'},
                   18091:                                              $timefilter,
                   18092:                                              $instcodefilter,
                   18093:                                              $filter->{'combownerfilter'},
                   18094:                                              $filter->{'coursefilter'},
                   18095:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18096:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18097:                                              $filter->{'cloneableonly'},
                   18098:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18099:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18100:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18101:         my $ccrole;
                   18102:         if ($type eq 'Community') {
                   18103:             $ccrole = 'co';
                   18104:         } else {
                   18105:             $ccrole = 'cc';
                   18106:         }
                   18107:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18108:                                                      $filter->{'persondomfilter'},
                   18109:                                                      'userroles',undef,
                   18110:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18111:                                                      $dom);
                   18112:         foreach my $role (keys(%rolehash)) {
                   18113:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18114:             my $cid = $cdom.'_'.$cnum;
                   18115:             if (exists($courses{$cid})) {
                   18116:                 if (ref($courses{$cid}) eq 'HASH') {
                   18117:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18118:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18119:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18120:                         }
                   18121:                     } else {
                   18122:                         $courses{$cid}{roles} = [$courserole];
                   18123:                     }
                   18124:                     $showcourses{$cid} = $courses{$cid};
                   18125:                 }
                   18126:             }
                   18127:         }
                   18128:         %courses = %showcourses;
                   18129:     }
                   18130:     return %courses;
                   18131: }
                   18132: 
                   18133: =pod
                   18134: 
1.1181    raeburn  18135: =back
                   18136: 
1.1207    raeburn  18137: =head1 Routines for version requirements for current course.
                   18138: 
                   18139: =over 4
                   18140: 
                   18141: =item * &check_release_required()
                   18142: 
                   18143: Compares required LON-CAPA version with version on server, and
                   18144: if required version is newer looks for a server with the required version.
                   18145: 
                   18146: Looks first at servers in user's owen domain; if none suitable, looks at
                   18147: servers in course's domain are permitted to host sessions for user's domain.
                   18148: 
                   18149: Inputs:
                   18150: 
                   18151: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18152: 
                   18153: $courseid - Course ID of current course
                   18154: 
                   18155: $rolecode - User's current role in course (for switchserver query string).
                   18156: 
                   18157: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18158: 
                   18159: 
                   18160: Returns:
                   18161: 
                   18162: $switchserver - query string tp append to /adm/switchserver call (if 
                   18163:                 current server's LON-CAPA version is too old. 
                   18164: 
                   18165: $warning - Message is displayed if no suitable server could be found.
                   18166: 
                   18167: =cut
                   18168: 
                   18169: sub check_release_required {
                   18170:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18171:     my ($switchserver,$warning);
                   18172:     if ($required ne '') {
                   18173:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18174:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18175:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18176:             my $otherserver;
                   18177:             if (($major eq '' && $minor eq '') ||
                   18178:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18179:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18180:                 my $switchlcrev =
                   18181:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18182:                                                            $userdomserver);
                   18183:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18184:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18185:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18186:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18187:                     if ($cdom ne $env{'user.domain'}) {
                   18188:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18189:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18190:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18191:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18192:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18193:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18194:                         my $canhost =
                   18195:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18196:                                                               $coursedomserver,
                   18197:                                                               $remoterev,
                   18198:                                                               $udomdefaults{'remotesessions'},
                   18199:                                                               $defdomdefaults{'hostedsessions'});
                   18200: 
                   18201:                         if ($canhost) {
                   18202:                             $otherserver = $coursedomserver;
                   18203:                         } else {
                   18204:                             $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.");
                   18205:                         }
                   18206:                     } else {
                   18207:                         $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).");
                   18208:                     }
                   18209:                 } else {
                   18210:                     $otherserver = $userdomserver;
                   18211:                 }
                   18212:             }
                   18213:             if ($otherserver ne '') {
                   18214:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18215:             }
                   18216:         }
                   18217:     }
                   18218:     return ($switchserver,$warning);
                   18219: }
                   18220: 
                   18221: =pod
                   18222: 
                   18223: =item * &check_release_result()
                   18224: 
                   18225: Inputs:
                   18226: 
                   18227: $switchwarning - Warning message if no suitable server found to host session.
                   18228: 
                   18229: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18230:                 and current role.
                   18231: 
                   18232: Returns: HTML to display with information about requirement to switch server.
                   18233:          Either displaying warning with link to Roles/Courses screen or
                   18234:          display link to switchserver.
                   18235: 
1.1181    raeburn  18236: =cut
                   18237: 
1.1207    raeburn  18238: sub check_release_result {
                   18239:     my ($switchwarning,$switchserver) = @_;
                   18240:     my $output = &start_page('Selected course unavailable on this server').
                   18241:                  '<p class="LC_warning">';
                   18242:     if ($switchwarning) {
                   18243:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18244:         if (&show_course()) {
                   18245:             $output .= &mt('Display courses');
                   18246:         } else {
                   18247:             $output .= &mt('Display roles');
                   18248:         }
                   18249:         $output .= '</a>';
                   18250:     } elsif ($switchserver) {
                   18251:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18252:                    '<br />'.
                   18253:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18254:                    &mt('Switch Server').
                   18255:                    '</a>';
                   18256:     }
                   18257:     $output .= '</p>'.&end_page();
                   18258:     return $output;
                   18259: }
                   18260: 
                   18261: =pod
                   18262: 
                   18263: =item * &needs_coursereinit()
                   18264: 
                   18265: Determine if course contents stored for user's session needs to be
                   18266: refreshed, because content has changed since "Big Hash" last tied.
                   18267: 
                   18268: Check for change is made if time last checked is more than 10 minutes ago
                   18269: (by default).
                   18270: 
                   18271: Inputs:
                   18272: 
                   18273: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18274: 
                   18275: $interval (optional) - Time which may elapse (in s) between last check for content
                   18276:                        change in current course. (default: 600 s).  
                   18277: 
                   18278: Returns: an array; first element is:
                   18279: 
                   18280: =over 4
                   18281: 
                   18282: 'switch' - if content updates mean user's session
                   18283:            needs to be switched to a server running a newer LON-CAPA version
                   18284:  
                   18285: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18286:            on current server hosting user's session                
                   18287: 
                   18288: ''       - if no action required.
                   18289: 
                   18290: =back
                   18291: 
                   18292: If first item element is 'switch':
                   18293: 
                   18294: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18295: 
                   18296: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18297:                               and current role. 
                   18298: 
                   18299: otherwise: no other elements returned.
                   18300: 
                   18301: =back
                   18302: 
                   18303: =cut
                   18304: 
                   18305: sub needs_coursereinit {
                   18306:     my ($loncaparev,$interval) = @_;
                   18307:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18308:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18309:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18310:     my $now = time;
                   18311:     if ($interval eq '') {
                   18312:         $interval = 600;
                   18313:     }
                   18314:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18315:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18316:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18317:         if ($blocked) {
                   18318:             return ();
                   18319:         }
1.1207    raeburn  18320:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18321:         if ($lastchange > $env{'request.course.tied'}) {
                   18322:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18323:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18324:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18325:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18326:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18327:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   18328:                     my ($switchserver,$switchwarning) =
                   18329:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18330:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   18331:                     if ($switchwarning ne '' || $switchserver ne '') {
                   18332:                         return ('switch',$switchwarning,$switchserver);
                   18333:                     }
                   18334:                 }
                   18335:             }
                   18336:             return ('update');
                   18337:         }
                   18338:     }
                   18339:     return ();
                   18340: }
1.1181    raeburn  18341: 
1.1083    raeburn  18342: sub update_content_constraints {
1.1326    raeburn  18343:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  18344:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18345:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18346:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18347:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18348:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18349:         if ($item eq 'resourcetag') {
                   18350:             if ($name eq 'responsetype') {
                   18351:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18352:             }
1.1307    raeburn  18353:         } elsif ($item eq 'course') {
                   18354:             if ($name eq 'courserestype') {
                   18355:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18356:             }
1.1083    raeburn  18357:         }
                   18358:     }
                   18359:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18360:     if (defined($navmap)) {
1.1307    raeburn  18361:         my (%allresponses,%allcrsrestypes);
                   18362:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18363:             if ($res->is_tool()) {
                   18364:                 if ($allcrsrestypes{'exttool'}) {
                   18365:                     $allcrsrestypes{'exttool'} ++;
                   18366:                 } else {
                   18367:                     $allcrsrestypes{'exttool'} = 1;
                   18368:                 }
                   18369:                 next;
                   18370:             }
1.1083    raeburn  18371:             my %responses = $res->responseTypes();
                   18372:             foreach my $key (keys(%responses)) {
                   18373:                 next unless(exists($checkresponsetypes{$key}));
                   18374:                 $allresponses{$key} += $responses{$key};
                   18375:             }
                   18376:         }
                   18377:         foreach my $key (keys(%allresponses)) {
                   18378:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18379:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18380:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18381:             }
                   18382:         }
1.1307    raeburn  18383:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18384:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18385:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18386:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18387:             }
                   18388:         }
1.1083    raeburn  18389:         undef($navmap);
                   18390:     }
1.1326    raeburn  18391:     my (@resources,@order,@resparms,@zombies);
                   18392:     if ($keeporder) {
                   18393:         use LONCAPA::map;
                   18394:         @resources = @LONCAPA::map::resources;
                   18395:         @order = @LONCAPA::map::order;
                   18396:         @resparms = @LONCAPA::map::resparms;
                   18397:         @zombies = @LONCAPA::map::zombies;
                   18398:     }
1.1308    raeburn  18399:     my $suppmap = 'supplemental.sequence';
                   18400:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18401:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18402:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18403:     if ($keeporder) {
                   18404:         @LONCAPA::map::resources = @resources;
                   18405:         @LONCAPA::map::order = @order;
                   18406:         @LONCAPA::map::resparms = @resparms;
                   18407:         @LONCAPA::map::zombies = @zombies;
                   18408:     }
1.1308    raeburn  18409:     if ($supptools) {
                   18410:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18411:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18412:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18413:         }
                   18414:     }
1.1083    raeburn  18415:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18416:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18417:     }
                   18418:     return;
                   18419: }
                   18420: 
1.1110    raeburn  18421: sub allmaps_incourse {
                   18422:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18423:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18424:         $cid = $env{'request.course.id'};
                   18425:         $cdom = $env{'course.'.$cid.'.domain'};
                   18426:         $cnum = $env{'course.'.$cid.'.num'};
                   18427:         $chome = $env{'course.'.$cid.'.home'};
                   18428:     }
                   18429:     my %allmaps = ();
                   18430:     my $lastchange =
                   18431:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18432:     if ($lastchange > $env{'request.course.tied'}) {
                   18433:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18434:         unless ($ferr) {
1.1326    raeburn  18435:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18436:         }
                   18437:     }
                   18438:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18439:     if (defined($navmap)) {
                   18440:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18441:             $allmaps{$res->src()} = 1;
                   18442:         }
                   18443:     }
                   18444:     return \%allmaps;
                   18445: }
                   18446: 
1.1083    raeburn  18447: sub parse_supplemental_title {
                   18448:     my ($title) = @_;
                   18449: 
                   18450:     my ($foldertitle,$renametitle);
                   18451:     if ($title =~ /&amp;&amp;&amp;/) {
                   18452:         $title = &HTML::Entites::decode($title);
                   18453:     }
                   18454:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18455:         $renametitle=$4;
                   18456:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18457:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18458:         my $name =  &plainname($uname,$udom);
                   18459:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18460:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18461:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18462:             $name.': <br />'.$foldertitle;
                   18463:     }
                   18464:     if (wantarray) {
                   18465:         return ($title,$foldertitle,$renametitle);
                   18466:     }
                   18467:     return $title;
                   18468: }
                   18469: 
1.1143    raeburn  18470: sub recurse_supplemental {
1.1308    raeburn  18471:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18472:     if ($suppmap) {
                   18473:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18474:         if ($fatal) {
                   18475:             $errors ++;
                   18476:         } else {
                   18477:             if ($#LONCAPA::map::resources > 0) {
                   18478:                 foreach my $res (@LONCAPA::map::resources) {
                   18479:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18480:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18481:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18482:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18483:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18484:                         } else {
1.1308    raeburn  18485:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18486:                                 $numexttools ++;
                   18487:                             }
1.1143    raeburn  18488:                             $numfiles ++;
                   18489:                         }
                   18490:                     }
                   18491:                 }
                   18492:             }
                   18493:         }
                   18494:     }
1.1308    raeburn  18495:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18496: }
                   18497: 
1.1101    raeburn  18498: sub symb_to_docspath {
1.1267    raeburn  18499:     my ($symb,$navmapref) = @_;
                   18500:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18501:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18502:     if ($resurl=~/\.(sequence|page)$/) {
                   18503:         $mapurl=$resurl;
                   18504:     } elsif ($resurl eq 'adm/navmaps') {
                   18505:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18506:     }
                   18507:     my $mapresobj;
1.1267    raeburn  18508:     unless (ref($$navmapref)) {
                   18509:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18510:     }
                   18511:     if (ref($$navmapref)) {
                   18512:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18513:     }
                   18514:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18515:     my $type=$2;
                   18516:     my $path;
                   18517:     if (ref($mapresobj)) {
                   18518:         my $pcslist = $mapresobj->map_hierarchy();
                   18519:         if ($pcslist ne '') {
                   18520:             foreach my $pc (split(/,/,$pcslist)) {
                   18521:                 next if ($pc <= 1);
1.1267    raeburn  18522:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18523:                 if (ref($res)) {
                   18524:                     my $thisurl = $res->src();
                   18525:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18526:                     my $thistitle = $res->title();
                   18527:                     $path .= '&'.
                   18528:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18529:                              &escape($thistitle).
1.1101    raeburn  18530:                              ':'.$res->randompick().
                   18531:                              ':'.$res->randomout().
                   18532:                              ':'.$res->encrypted().
                   18533:                              ':'.$res->randomorder().
                   18534:                              ':'.$res->is_page();
                   18535:                 }
                   18536:             }
                   18537:         }
                   18538:         $path =~ s/^\&//;
                   18539:         my $maptitle = $mapresobj->title();
                   18540:         if ($mapurl eq 'default') {
1.1129    raeburn  18541:             $maptitle = 'Main Content';
1.1101    raeburn  18542:         }
                   18543:         $path .= (($path ne '')? '&' : '').
                   18544:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18545:                  &escape($maptitle).
1.1101    raeburn  18546:                  ':'.$mapresobj->randompick().
                   18547:                  ':'.$mapresobj->randomout().
                   18548:                  ':'.$mapresobj->encrypted().
                   18549:                  ':'.$mapresobj->randomorder().
                   18550:                  ':'.$mapresobj->is_page();
                   18551:     } else {
                   18552:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18553:         my $ispage = (($type eq 'page')? 1 : '');
                   18554:         if ($mapurl eq 'default') {
1.1129    raeburn  18555:             $maptitle = 'Main Content';
1.1101    raeburn  18556:         }
                   18557:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18558:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18559:     }
                   18560:     unless ($mapurl eq 'default') {
                   18561:         $path = 'default&'.
1.1146    raeburn  18562:                 &escape('Main Content').
1.1101    raeburn  18563:                 ':::::&'.$path;
                   18564:     }
                   18565:     return $path;
                   18566: }
                   18567: 
1.1094    raeburn  18568: sub captcha_display {
1.1327    raeburn  18569:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18570:     my ($output,$error);
1.1234    raeburn  18571:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18572:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18573:     if ($captcha eq 'original') {
1.1094    raeburn  18574:         $output = &create_captcha();
                   18575:         unless ($output) {
1.1172    raeburn  18576:             $error = 'captcha';
1.1094    raeburn  18577:         }
                   18578:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18579:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18580:         unless ($output) {
1.1172    raeburn  18581:             $error = 'recaptcha';
1.1094    raeburn  18582:         }
                   18583:     }
1.1234    raeburn  18584:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18585: }
                   18586: 
                   18587: sub captcha_response {
1.1327    raeburn  18588:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18589:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18590:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18591:     if ($captcha eq 'original') {
1.1094    raeburn  18592:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18593:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18594:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18595:     } else {
                   18596:         $captcha_chk = 1;
                   18597:     }
                   18598:     return ($captcha_chk,$captcha_error);
                   18599: }
                   18600: 
                   18601: sub get_captcha_config {
1.1327    raeburn  18602:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18603:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18604:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18605:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18606:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18607:     if ($context eq 'usercreation') {
                   18608:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18609:         if (ref($domconfig{$context}) eq 'HASH') {
                   18610:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18611:             if (ref($hashtocheck) eq 'HASH') {
                   18612:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18613:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18614:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18615:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18616:                     }
                   18617:                     if ($privkey && $pubkey) {
                   18618:                         $captcha = 'recaptcha';
1.1234    raeburn  18619:                         $version = $hashtocheck->{'recaptchaversion'};
                   18620:                         if ($version ne '2') {
                   18621:                             $version = 1;
                   18622:                         }
1.1095    raeburn  18623:                     } else {
                   18624:                         $captcha = 'original';
                   18625:                     }
                   18626:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18627:                     $captcha = 'original';
                   18628:                 }
1.1094    raeburn  18629:             }
1.1095    raeburn  18630:         } else {
                   18631:             $captcha = 'captcha';
                   18632:         }
                   18633:     } elsif ($context eq 'login') {
                   18634:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18635:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18636:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18637:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18638:             if ($privkey && $pubkey) {
                   18639:                 $captcha = 'recaptcha';
1.1234    raeburn  18640:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18641:                 if ($version ne '2') {
                   18642:                     $version = 1; 
                   18643:                 }
1.1095    raeburn  18644:             } else {
                   18645:                 $captcha = 'original';
1.1094    raeburn  18646:             }
1.1095    raeburn  18647:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18648:             $captcha = 'original';
1.1094    raeburn  18649:         }
1.1327    raeburn  18650:     } elsif ($context eq 'passwords') {
                   18651:         if ($dom_in_effect) {
                   18652:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18653:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18654:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18655:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18656:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18657:                 }
                   18658:                 if ($privkey && $pubkey) {
                   18659:                     $captcha = 'recaptcha';
                   18660:                     $version = $passwdconf{'recaptchaversion'};
                   18661:                     if ($version ne '2') {
                   18662:                         $version = 1;
                   18663:                     }
                   18664:                 } else {
                   18665:                     $captcha = 'original';
                   18666:                 }
                   18667:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18668:                 $captcha = 'original';
                   18669:             }
                   18670:         }
                   18671:     } 
1.1234    raeburn  18672:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18673: }
                   18674: 
                   18675: sub create_captcha {
                   18676:     my %captcha_params = &captcha_settings();
                   18677:     my ($output,$maxtries,$tries) = ('',10,0);
                   18678:     while ($tries < $maxtries) {
                   18679:         $tries ++;
                   18680:         my $captcha = Authen::Captcha->new (
                   18681:                                            output_folder => $captcha_params{'output_dir'},
                   18682:                                            data_folder   => $captcha_params{'db_dir'},
                   18683:                                           );
                   18684:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18685: 
                   18686:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18687:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18688:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18689:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18690:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18691:                       '</span><br />'.
1.1176    raeburn  18692:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18693:             last;
                   18694:         }
                   18695:     }
1.1323    raeburn  18696:     if ($output eq '') {
                   18697:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18698:     }
1.1094    raeburn  18699:     return $output;
                   18700: }
                   18701: 
                   18702: sub captcha_settings {
                   18703:     my %captcha_params = (
                   18704:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18705:                            www_output_dir => "/captchaspool",
                   18706:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18707:                            numchars       => '5',
                   18708:                          );
                   18709:     return %captcha_params;
                   18710: }
                   18711: 
                   18712: sub check_captcha {
                   18713:     my ($captcha_chk,$captcha_error);
                   18714:     my $code = $env{'form.code'};
                   18715:     my $md5sum = $env{'form.crypt'};
                   18716:     my %captcha_params = &captcha_settings();
                   18717:     my $captcha = Authen::Captcha->new(
                   18718:                       output_folder => $captcha_params{'output_dir'},
                   18719:                       data_folder   => $captcha_params{'db_dir'},
                   18720:                   );
1.1109    raeburn  18721:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18722:     my %captcha_hash = (
                   18723:                         0       => 'Code not checked (file error)',
                   18724:                        -1      => 'Failed: code expired',
                   18725:                        -2      => 'Failed: invalid code (not in database)',
                   18726:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18727:     );
                   18728:     if ($captcha_chk != 1) {
                   18729:         $captcha_error = $captcha_hash{$captcha_chk}
                   18730:     }
                   18731:     return ($captcha_chk,$captcha_error);
                   18732: }
                   18733: 
                   18734: sub create_recaptcha {
1.1234    raeburn  18735:     my ($pubkey,$version) = @_;
                   18736:     if ($version >= 2) {
1.1367    raeburn  18737:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18738:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18739:     } else {
                   18740:         my $use_ssl;
                   18741:         if ($ENV{'SERVER_PORT'} == 443) {
                   18742:             $use_ssl = 1;
                   18743:         }
                   18744:         my $captcha = Captcha::reCAPTCHA->new;
                   18745:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18746:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18747:                &mt('If the text is hard to read, [_1] will replace them.',
                   18748:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18749:                '<br /><br />';
                   18750:     }
1.1094    raeburn  18751: }
                   18752: 
                   18753: sub check_recaptcha {
1.1234    raeburn  18754:     my ($privkey,$version) = @_;
1.1094    raeburn  18755:     my $captcha_chk;
1.1350    raeburn  18756:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18757:     if ($version >= 2) {
                   18758:         my %info = (
                   18759:                      secret   => $privkey, 
                   18760:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18761:                      remoteip => $ip,
1.1234    raeburn  18762:                    );
1.1280    raeburn  18763:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18764:         $request->content(join('&',map {
                   18765:                          my $name = escape($_);
                   18766:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18767:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18768:                          : &escape($info{$_}) );
                   18769:         } keys(%info)));
                   18770:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18771:         if ($response->is_success)  {
                   18772:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18773:             if (ref($data) eq 'HASH') {
                   18774:                 if ($data->{'success'}) {
                   18775:                     $captcha_chk = 1;
                   18776:                 }
                   18777:             }
                   18778:         }
                   18779:     } else {
                   18780:         my $captcha = Captcha::reCAPTCHA->new;
                   18781:         my $captcha_result =
                   18782:             $captcha->check_answer(
                   18783:                                     $privkey,
1.1350    raeburn  18784:                                     $ip,
1.1234    raeburn  18785:                                     $env{'form.recaptcha_challenge_field'},
                   18786:                                     $env{'form.recaptcha_response_field'},
                   18787:                                   );
                   18788:         if ($captcha_result->{is_valid}) {
                   18789:             $captcha_chk = 1;
                   18790:         }
1.1094    raeburn  18791:     }
                   18792:     return $captcha_chk;
                   18793: }
                   18794: 
1.1174    raeburn  18795: sub emailusername_info {
1.1244    raeburn  18796:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18797:     my %titles = &Apache::lonlocal::texthash (
                   18798:                      lastname      => 'Last Name',
                   18799:                      firstname     => 'First Name',
                   18800:                      institution   => 'School/college/university',
                   18801:                      location      => "School's city, state/province, country",
                   18802:                      web           => "School's web address",
                   18803:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18804:                      id            => 'Student/Employee ID',
1.1174    raeburn  18805:                  );
                   18806:     return (\@fields,\%titles);
                   18807: }
                   18808: 
1.1161    raeburn  18809: sub cleanup_html {
                   18810:     my ($incoming) = @_;
                   18811:     my $outgoing;
                   18812:     if ($incoming ne '') {
                   18813:         $outgoing = $incoming;
                   18814:         $outgoing =~ s/;/&#059;/g;
                   18815:         $outgoing =~ s/\#/&#035;/g;
                   18816:         $outgoing =~ s/\&/&#038;/g;
                   18817:         $outgoing =~ s/</&#060;/g;
                   18818:         $outgoing =~ s/>/&#062;/g;
                   18819:         $outgoing =~ s/\(/&#040/g;
                   18820:         $outgoing =~ s/\)/&#041;/g;
                   18821:         $outgoing =~ s/"/&#034;/g;
                   18822:         $outgoing =~ s/'/&#039;/g;
                   18823:         $outgoing =~ s/\$/&#036;/g;
                   18824:         $outgoing =~ s{/}{&#047;}g;
                   18825:         $outgoing =~ s/=/&#061;/g;
                   18826:         $outgoing =~ s/\\/&#092;/g
                   18827:     }
                   18828:     return $outgoing;
                   18829: }
                   18830: 
1.1190    musolffc 18831: # Checks for critical messages and returns a redirect url if one exists.
                   18832: # $interval indicates how often to check for messages.
1.1282    raeburn  18833: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18834: sub critical_redirect {
1.1282    raeburn  18835:     my ($interval,$context) = @_;
1.1356    raeburn  18836:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18837:         return ();
                   18838:     }
1.1190    musolffc 18839:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18840:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18841:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18842:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  18843:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18844:             if ($blocked) {
                   18845:                 my $checkrole = "cm./$cdom/$cnum";
                   18846:                 if ($env{'request.course.sec'} ne '') {
                   18847:                     $checkrole .= "/$env{'request.course.sec'}";
                   18848:                 }
                   18849:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18850:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18851:                     return;
                   18852:                 }
                   18853:             }
                   18854:         }
1.1190    musolffc 18855:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18856:                                         $env{'user.name'});
                   18857:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18858:         my $redirecturl;
1.1190    musolffc 18859:         if ($what[0]) {
1.1356    raeburn  18860: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18861: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18862: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18863:                 return (1, $url);
1.1190    musolffc 18864:             }
1.1191    raeburn  18865:         }
                   18866:     } 
                   18867:     return ();
1.1190    musolffc 18868: }
                   18869: 
1.1174    raeburn  18870: # Use:
                   18871: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18872: #
                   18873: ##################################################
                   18874: #          password associated functions         #
                   18875: ##################################################
                   18876: sub des_keys {
                   18877:     # Make a new key for DES encryption.
                   18878:     # Each key has two parts which are returned separately.
                   18879:     # Please note:  Each key must be passed through the &hex function
                   18880:     # before it is output to the web browser.  The hex versions cannot
                   18881:     # be used to decrypt.
                   18882:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18883:                 '8','9','a','b','c','d','e','f');
                   18884:     my $lkey='';
                   18885:     for (0..7) {
                   18886:         $lkey.=$hexstr[rand(15)];
                   18887:     }
                   18888:     my $ukey='';
                   18889:     for (0..7) {
                   18890:         $ukey.=$hexstr[rand(15)];
                   18891:     }
                   18892:     return ($lkey,$ukey);
                   18893: }
                   18894: 
                   18895: sub des_decrypt {
                   18896:     my ($key,$cyphertext) = @_;
                   18897:     my $keybin=pack("H16",$key);
                   18898:     my $cypher;
                   18899:     if ($Crypt::DES::VERSION>=2.03) {
                   18900:         $cypher=new Crypt::DES $keybin;
                   18901:     } else {
                   18902:         $cypher=new DES $keybin;
                   18903:     }
1.1233    raeburn  18904:     my $plaintext='';
                   18905:     my $cypherlength = length($cyphertext);
                   18906:     my $numchunks = int($cypherlength/32);
                   18907:     for (my $j=0; $j<$numchunks; $j++) {
                   18908:         my $start = $j*32;
                   18909:         my $cypherblock = substr($cyphertext,$start,32);
                   18910:         my $chunk =
                   18911:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18912:         $chunk .=
                   18913:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18914:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18915:         $plaintext .= $chunk;
                   18916:     }
1.1174    raeburn  18917:     return $plaintext;
                   18918: }
                   18919: 
1.1344    raeburn  18920: sub get_requested_shorturls {
1.1309    raeburn  18921:     my ($cdom,$cnum,$navmap) = @_;
                   18922:     return unless (ref($navmap));
1.1344    raeburn  18923:     my ($numnew,$errors);
1.1309    raeburn  18924:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18925:     if (@toshorten) {
                   18926:         my (%maps,%resources,%titles);
                   18927:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18928:                                                                'shorturls',$cdom,$cnum);
                   18929:         if (keys(%resources)) {
1.1344    raeburn  18930:             my %tocreate;
1.1309    raeburn  18931:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18932:                 my $symb = $resources{$item};
                   18933:                 if ($symb) {
                   18934:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18935:                 }
                   18936:             }
1.1344    raeburn  18937:             if (keys(%tocreate)) {
                   18938:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18939:                                                       \%tocreate);
                   18940:             }
1.1309    raeburn  18941:         }
1.1344    raeburn  18942:     }
                   18943:     return ($numnew,$errors);
                   18944: }
                   18945: 
                   18946: sub make_short_symbs {
                   18947:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18948:     my ($numnew,@errors);
                   18949:     if (ref($tocreateref) eq 'HASH') {
                   18950:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18951:         if (keys(%tocreate)) {
                   18952:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18953:             my $su = Short::URL->new(no_vowels => 1);
                   18954:             my $init = '';
                   18955:             my (%newunique,%addcourse,%courseonly,%failed);
                   18956:             # get lock on tiny db
                   18957:             my $now = time;
1.1344    raeburn  18958:             if ($lockuser eq '') {
                   18959:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18960:             }
1.1309    raeburn  18961:             my $lockhash = {
1.1344    raeburn  18962:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18963:                             };
                   18964:             my $tries = 0;
                   18965:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18966:             my ($code,$error);
                   18967:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18968:                 $tries ++;
                   18969:                 sleep 1;
1.1319    raeburn  18970:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18971:             }
                   18972:             if ($gotlock eq 'ok') {
                   18973:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18974:                                        \%addcourse,\%courseonly,\%failed);
                   18975:                 if (keys(%failed)) {
                   18976:                     my $numfailed = scalar(keys(%failed));
                   18977:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18978:                 }
                   18979:                 if (keys(%newunique)) {
                   18980:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18981:                     if ($putres eq 'ok') {
                   18982:                         $numnew = scalar(keys(%newunique));
                   18983:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18984:                         unless ($newputres eq 'ok') {
                   18985:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18986:                         }
                   18987:                     } else {
                   18988:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18989:                     }
                   18990:                 }
                   18991:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18992:                 unless ($dellockres eq 'ok') {
                   18993:                     push(@errors,&mt('error: could not release lockfile'));
                   18994:                 }
                   18995:             } else {
                   18996:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18997:             }
                   18998:             if (keys(%courseonly)) {
                   18999:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19000:                 if ($result ne 'ok') {
                   19001:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19002:                 }
                   19003:             }
                   19004:         }
                   19005:     }
                   19006:     return ($numnew,\@errors);
                   19007: }
                   19008: 
                   19009: sub shorten_symbs {
                   19010:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19011:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19012:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19013:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19014:     my (%possibles,%collisions);
                   19015:     foreach my $key (keys(%{$tocreate})) {
                   19016:         my $num = String::CRC32::crc32($key);
                   19017:         my $tiny = $su->encode($num,$init);
                   19018:         if ($tiny) {
                   19019:             $possibles{$tiny} = $key;
                   19020:         }
                   19021:     }
                   19022:     if (!$init) {
                   19023:         $init = 1;
                   19024:     } else {
                   19025:         $init ++;
                   19026:     }
                   19027:     if (keys(%possibles)) {
                   19028:         my @posstiny = keys(%possibles);
                   19029:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19030:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19031:         if (keys(%currtiny)) {
                   19032:             foreach my $key (keys(%currtiny)) {
                   19033:                 next if ($currtiny{$key} eq '');
                   19034:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19035:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19036:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19037:                         $courseonly->{$tsymb} = $key;
                   19038:                     }
                   19039:                 } else {
                   19040:                     $collisions{$possibles{$key}} = 1;
                   19041:                 }
                   19042:                 delete($possibles{$key});
                   19043:             }
                   19044:         }
                   19045:         foreach my $key (keys(%possibles)) {
                   19046:             $newunique->{$key} = $possibles{$key};
                   19047:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19048:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19049:                 $addcourse->{$tsymb} = $key;
                   19050:             }
                   19051:         }
                   19052:     }
                   19053:     if (keys(%collisions)) {
                   19054:         if ($init <5) {
                   19055:             if (!$init) {
                   19056:                 $init = 1;
                   19057:             } else {
                   19058:                 $init ++;
                   19059:             }
                   19060:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19061:                                    $newunique,$addcourse,$courseonly,$failed);
                   19062:         } else {
                   19063:             foreach my $key (keys(%collisions)) {
                   19064:                 $failed->{$key} = 1;
                   19065:             }
                   19066:         }
                   19067:     }
                   19068:     return $init;
                   19069: }
                   19070: 
1.1328    raeburn  19071: sub is_nonframeable {
1.1329    raeburn  19072:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19073:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19074:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19075: 
                   19076:     $remprotocol = lc($remprotocol);
                   19077:     $remhost = lc($remhost);
                   19078:     my $remport = 80;
                   19079:     if ($remprotocol eq 'https') {
                   19080:         $remport = 443;
                   19081:     }
1.1330    raeburn  19082:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19083:     if ($cached) {
                   19084:         unless ($nocache) {
                   19085:             if ($result) {
                   19086:                 return 1;
                   19087:             } else {
                   19088:                 return 0;
                   19089:             }
                   19090:         }
                   19091:     }
1.1328    raeburn  19092:     my $uselink;
                   19093:     my $request = new HTTP::Request('HEAD',$url);
                   19094:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19095:     if ($response->is_success()) {
                   19096:         my $secpolicy = lc($response->header('content-security-policy'));
                   19097:         my $xframeop = lc($response->header('x-frame-options'));
                   19098:         $secpolicy =~ s/^\s+|\s+$//g;
                   19099:         $xframeop =~ s/^\s+|\s+$//g;
                   19100:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19101:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19102:             my ($origin,$protocol,$port);
                   19103:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19104:                 $port = $ENV{'SERVER_PORT'};
                   19105:             } else {
                   19106:                 $port = 80;
                   19107:             }
                   19108:             if ($absolute eq '') {
                   19109:                 $protocol = 'http:';
                   19110:                 if ($port == 443) {
                   19111:                     $protocol = 'https:';
                   19112:                 }
                   19113:                 $origin = $protocol.'//'.lc($hostname);
                   19114:             } else {
                   19115:                 $origin = lc($absolute);
                   19116:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19117:             }
                   19118:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19119:                 my $framepolicy = $1;
                   19120:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19121:                 my @policies = split(/\s+/,$framepolicy);
                   19122:                 if (@policies) {
                   19123:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19124:                         $uselink = 1;
                   19125:                     } else {
                   19126:                         $uselink = 1;
                   19127:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19128:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19129:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19130:                             undef($uselink);
                   19131:                         }
                   19132:                         if ($uselink) {
                   19133:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19134:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19135:                                     undef($uselink);
                   19136:                                 }
                   19137:                             }
                   19138:                         }
                   19139:                         if ($uselink) {
                   19140:                             my @possok;
                   19141:                             if ($ip ne '') {
                   19142:                                 push(@possok,$ip);
                   19143:                             }
                   19144:                             my $hoststr = '';
                   19145:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19146:                                 if ($hoststr eq '') {
                   19147:                                     $hoststr = $part;
                   19148:                                 } else {
                   19149:                                     $hoststr = "$part.$hoststr";
                   19150:                                 }
                   19151:                                 if ($hoststr eq $hostname) {
                   19152:                                     push(@possok,$hostname);
                   19153:                                 } else {
                   19154:                                     push(@possok,"*.$hoststr");
                   19155:                                 }
                   19156:                             }
                   19157:                             if (@possok) {
                   19158:                                 foreach my $poss (@possok) {
                   19159:                                     last if (!$uselink);
                   19160:                                     foreach my $policy (@policies) {
                   19161:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19162:                                             undef($uselink);
                   19163:                                             last;
                   19164:                                         }
                   19165:                                     }
                   19166:                                 }
                   19167:                             }
                   19168:                         }
                   19169:                     }
                   19170:                 }
                   19171:             } elsif ($xframeop ne '') {
                   19172:                 $uselink = 1;
                   19173:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19174:                 if (@policies) {
                   19175:                     unless (grep(/^deny$/,@policies)) {
                   19176:                         if ($origin ne '') {
                   19177:                             if (grep(/^sameorigin$/,@policies)) {
                   19178:                                 if ($remotehost eq $origin) {
                   19179:                                     undef($uselink);
                   19180:                                 }
                   19181:                             }
                   19182:                             if ($uselink) {
                   19183:                                 foreach my $policy (@policies) {
                   19184:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19185:                                         my $allowfrom = $1;
                   19186:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19187:                                             undef($uselink);
                   19188:                                             last;
                   19189:                                         }
                   19190:                                     }
                   19191:                                 }
                   19192:                             }
                   19193:                         }
                   19194:                     }
                   19195:                 }
                   19196:             }
                   19197:         }
                   19198:     }
1.1329    raeburn  19199:     if ($nocache) {
                   19200:         if ($cached) {
                   19201:             my $devalidate;
                   19202:             if ($uselink && !$result) {
                   19203:                 $devalidate = 1;
                   19204:             } elsif (!$uselink && $result) {
                   19205:                 $devalidate = 1;
                   19206:             }
                   19207:             if ($devalidate) {
                   19208:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19209:             }
                   19210:         }
                   19211:     } else {
                   19212:         if ($uselink) {
                   19213:             $result = 1;
                   19214:         } else {
                   19215:             $result = 0;
                   19216:         }
                   19217:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19218:     }
1.1328    raeburn  19219:     return $uselink;
                   19220: }
                   19221: 
1.1359    raeburn  19222: sub page_menu {
                   19223:     my ($menucolls,$menunum) = @_;
                   19224:     my %menu;
                   19225:     foreach my $item (split(/;/,$menucolls)) {
                   19226:         my ($num,$value) = split(/\%/,$item);
                   19227:         if ($num eq $menunum) {
                   19228:             my @entries = split(/\&/,$value);
                   19229:             foreach my $entry (@entries) {
                   19230:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19231:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19232:                     $menu{$name} = $fields;
                   19233:                 } else {
                   19234:                     my @shown;
                   19235:                     if ($fields =~ /,/) {
                   19236:                         @shown = split(/,/,$fields);
                   19237:                     } else {
                   19238:                         @shown = ($fields);
                   19239:                     }
                   19240:                     if (@shown) {
                   19241:                         foreach my $field (@shown) {
                   19242:                             next if ($field eq '');
                   19243:                             $menu{$field} = 1;
                   19244:                         }
                   19245:                     }
                   19246:                 }
                   19247:             }
                   19248:         }
                   19249:     }
                   19250:     return %menu;
                   19251: }
                   19252: 
1.112     bowersj2 19253: 1;
                   19254: __END__;
1.41      ng       19255: 

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