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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1384  ! raeburn     4: # $Id: loncommon.pm,v 1.1383 2022/05/31 22:07:15 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.1256    raeburn   960:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    961:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   962:    if ($includeempty) {
                    963:        $output .= '<option value=""';
                    964:        if (($selected eq '') || ($selected eq 'local')) {
                    965:            $output .= ' selected="selected" ';
                    966:        }
                    967:        $output .= '> </option>';
                    968:    }
1.657     raeburn   969:    my @timezones = DateTime::TimeZone->all_names;
                    970:    foreach my $tzone (@timezones) {
                    971:        $output.= '<option value="'.$tzone.'"';
                    972:        if ($tzone eq $selected) {
                    973:            $output.=' selected="selected"';
                    974:        }
                    975:        $output.=">$tzone</option>\n";
1.656     www       976:    }
                    977:    $output.="</select>";
                    978:    return $output;
                    979: }
1.273     raeburn   980: 
1.687     raeburn   981: sub select_datelocale {
1.1256    raeburn   982:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    983:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   984:     if ($includeempty) {
                    985:         $output .= '<option value=""';
                    986:         if ($selected eq '') {
                    987:             $output .= ' selected="selected" ';
                    988:         }
                    989:         $output .= '> </option>';
                    990:     }
1.1241    raeburn   991:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   992:     my (@possibles,%locale_names);
1.1241    raeburn   993:     my @locales = DateTime::Locale->ids();
                    994:     foreach my $id (@locales) {
                    995:         if ($id ne '') {
                    996:             my ($en_terr,$native_terr);
                    997:             my $loc = DateTime::Locale->load($id);
                    998:             if (ref($loc)) {
                    999:                 $en_terr = $loc->name();
                   1000:                 $native_terr = $loc->native_name();
1.687     raeburn  1001:                 if (grep(/^en$/,@languages) || !@languages) {
                   1002:                     if ($en_terr ne '') {
                   1003:                         $locale_names{$id} = '('.$en_terr.')';
                   1004:                     } elsif ($native_terr ne '') {
                   1005:                         $locale_names{$id} = $native_terr;
                   1006:                     }
                   1007:                 } else {
                   1008:                     if ($native_terr ne '') {
                   1009:                         $locale_names{$id} = $native_terr.' ';
                   1010:                     } elsif ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     }
                   1013:                 }
1.1220    raeburn  1014:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1015:                 push(@possibles,$id);
                   1016:             } 
1.687     raeburn  1017:         }
                   1018:     }
                   1019:     foreach my $item (sort(@possibles)) {
                   1020:         $output.= '<option value="'.$item.'"';
                   1021:         if ($item eq $selected) {
                   1022:             $output.=' selected="selected"';
                   1023:         }
                   1024:         $output.=">$item";
                   1025:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1026:             $output.='  '.$locale_names{$item};
1.687     raeburn  1027:         }
                   1028:         $output.="</option>\n";
                   1029:     }
                   1030:     $output.="</select>";
                   1031:     return $output;
                   1032: }
                   1033: 
1.792     raeburn  1034: sub select_language {
1.1256    raeburn  1035:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1036:     my %langchoices;
                   1037:     if ($includeempty) {
1.1117    raeburn  1038:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1039:     }
                   1040:     foreach my $id (&languageids()) {
                   1041:         my $code = &supportedlanguagecode($id);
                   1042:         if ($code) {
                   1043:             $langchoices{$code} = &plainlanguagedescription($id);
                   1044:         }
                   1045:     }
1.1117    raeburn  1046:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1047:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1048: }
                   1049: 
1.42      matthew  1050: =pod
1.36      matthew  1051: 
1.1088    foxr     1052: 
                   1053: =item * &list_languages()
                   1054: 
                   1055: Returns an array reference that is suitable for use in language prompters.
                   1056: Each array element is itself a two element array.  The first element
                   1057: is the language code.  The second element a descsriptiuon of the 
                   1058: language itself.  This is suitable for use in e.g.
                   1059: &Apache::edit::select_arg (once dereferenced that is).
                   1060: 
                   1061: =cut 
                   1062: 
                   1063: sub list_languages {
                   1064:     my @lang_choices;
                   1065: 
                   1066:     foreach my $id (&languageids()) {
                   1067: 	my $code = &supportedlanguagecode($id);
                   1068: 	if ($code) {
                   1069: 	    my $selector    = $supported_codes{$id};
                   1070: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1071: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1072: 	}
                   1073:     }
                   1074:     return \@lang_choices;
                   1075: }
                   1076: 
                   1077: =pod
                   1078: 
1.648     raeburn  1079: =item * &linked_select_forms(...)
1.36      matthew  1080: 
                   1081: linked_select_forms returns a string containing a <script></script> block
                   1082: and html for two <select> menus.  The select menus will be linked in that
                   1083: changing the value of the first menu will result in new values being placed
                   1084: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1085: order unless a defined order is provided.
1.36      matthew  1086: 
                   1087: linked_select_forms takes the following ordered inputs:
                   1088: 
                   1089: =over 4
                   1090: 
1.112     bowersj2 1091: =item * $formname, the name of the <form> tag
1.36      matthew  1092: 
1.112     bowersj2 1093: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1094: 
1.112     bowersj2 1095: =item * $firstdefault, the default value for the first menu
1.36      matthew  1096: 
1.112     bowersj2 1097: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1098: 
1.112     bowersj2 1099: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1102: 
1.609     raeburn  1103: =item * $menuorder, the order of values in the first menu
                   1104: 
1.1115    raeburn  1105: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1106:         event for the first <select> tag
                   1107: 
                   1108: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1109:         event for the second <select> tag
                   1110: 
1.1245    raeburn  1111: =item * $suffix, to differentiate separate uses of select2data javascript
                   1112:         objects in a page.
                   1113: 
1.41      ng       1114: =back 
                   1115: 
1.36      matthew  1116: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1117: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1118: values for the first select menu.  The text that coincides with the 
1.41      ng       1119: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1120: and text for the second menu are given in the hash pointed to by 
                   1121: $menu{$choice1}->{'select2'}.  
                   1122: 
1.112     bowersj2 1123:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1124:                        default => "B3",
                   1125:                        select2 => { 
                   1126:                            B1 => "Choice B1",
                   1127:                            B2 => "Choice B2",
                   1128:                            B3 => "Choice B3",
                   1129:                            B4 => "Choice B4"
1.609     raeburn  1130:                            },
                   1131:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1132:                    },
                   1133:                A2 => { text =>"Choice A2" ,
                   1134:                        default => "C2",
                   1135:                        select2 => { 
                   1136:                            C1 => "Choice C1",
                   1137:                            C2 => "Choice C2",
                   1138:                            C3 => "Choice C3"
1.609     raeburn  1139:                            },
                   1140:                        order => ['C2','C1','C3'],
1.112     bowersj2 1141:                    },
                   1142:                A3 => { text =>"Choice A3" ,
                   1143:                        default => "D6",
                   1144:                        select2 => { 
                   1145:                            D1 => "Choice D1",
                   1146:                            D2 => "Choice D2",
                   1147:                            D3 => "Choice D3",
                   1148:                            D4 => "Choice D4",
                   1149:                            D5 => "Choice D5",
                   1150:                            D6 => "Choice D6",
                   1151:                            D7 => "Choice D7"
1.609     raeburn  1152:                            },
                   1153:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1154:                    }
                   1155:                );
1.36      matthew  1156: 
                   1157: =cut
                   1158: 
                   1159: sub linked_select_forms {
                   1160:     my ($formname,
                   1161:         $middletext,
                   1162:         $firstdefault,
                   1163:         $firstselectname,
                   1164:         $secondselectname, 
1.609     raeburn  1165:         $hashref,
                   1166:         $menuorder,
1.1115    raeburn  1167:         $onchangefirst,
1.1245    raeburn  1168:         $onchangesecond,
                   1169:         $suffix
1.36      matthew  1170:         ) = @_;
                   1171:     my $second = "document.$formname.$secondselectname";
                   1172:     my $first = "document.$formname.$firstselectname";
                   1173:     # output the javascript to do the changing
                   1174:     my $result = '';
1.776     bisitz   1175:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1176:     $result.="// <![CDATA[\n";
1.1245    raeburn  1177:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1178:     $" = '","';
                   1179:     my $debug = '';
                   1180:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1181:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1182:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1183:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1184:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1185:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1186:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1187:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1188:         }
1.36      matthew  1189:         $result.="\"@s2values\");\n";
1.1245    raeburn  1190:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1191:         my @s2texts;
                   1192:         foreach my $value (@s2values) {
1.1263    raeburn  1193:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1194:         }
                   1195:         $result.="\"@s2texts\");\n";
                   1196:     }
                   1197:     $"=' ';
                   1198:     $result.= <<"END";
                   1199: 
1.1245    raeburn  1200: function select1${suffix}_changed() {
1.36      matthew  1201:     // Determine new choice
1.1245    raeburn  1202:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1203:     // update select2
1.1245    raeburn  1204:     var values     = select2data${suffix}[newvalue].values;
                   1205:     var texts      = select2data${suffix}[newvalue].texts;
                   1206:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1207:     var i;
                   1208:     // out with the old
1.1245    raeburn  1209:     $second.options.length = 0;
                   1210:     // in with the new
1.36      matthew  1211:     for (i=0;i<values.length; i++) {
                   1212:         $second.options[i] = new Option(values[i]);
1.143     matthew  1213:         $second.options[i].value = values[i];
1.36      matthew  1214:         $second.options[i].text = texts[i];
                   1215:         if (values[i] == select2def) {
                   1216:             $second.options[i].selected = true;
                   1217:         }
                   1218:     }
                   1219: }
1.824     bisitz   1220: // ]]>
1.36      matthew  1221: </script>
                   1222: END
                   1223:     # output the initial values for the selection lists
1.1245    raeburn  1224:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1225:     my @order = sort(keys(%{$hashref}));
                   1226:     if (ref($menuorder) eq 'ARRAY') {
                   1227:         @order = @{$menuorder};
                   1228:     }
                   1229:     foreach my $value (@order) {
1.36      matthew  1230:         $result.="    <option value=\"$value\" ";
1.253     albertel 1231:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1232:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1233:     }
                   1234:     $result .= "</select>\n";
                   1235:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1236:     $result .= $middletext;
1.1115    raeburn  1237:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1238:     if ($onchangesecond) {
                   1239:         $result .= ' onchange="'.$onchangesecond.'"';
                   1240:     }
                   1241:     $result .= ">\n";
1.36      matthew  1242:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1243:     
                   1244:     my @secondorder = sort(keys(%select2));
                   1245:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1246:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1247:     }
                   1248:     foreach my $value (@secondorder) {
1.36      matthew  1249:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1250:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1251:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1252:     }
                   1253:     $result .= "</select>\n";
                   1254:     #    return $debug;
                   1255:     return $result;
                   1256: }   #  end of sub linked_select_forms {
                   1257: 
1.45      matthew  1258: =pod
1.44      bowersj2 1259: 
1.1381    raeburn  1260: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1261: 
1.112     bowersj2 1262: Returns a string corresponding to an HTML link to the given help
                   1263: $topic, where $topic corresponds to the name of a .tex file in
                   1264: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1265: spaces. 
                   1266: 
                   1267: $text will optionally be linked to the same topic, allowing you to
                   1268: link text in addition to the graphic. If you do not want to link
                   1269: text, but wish to specify one of the later parameters, pass an
                   1270: empty string. 
                   1271: 
                   1272: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1273: the link will not open a new window. If false, the link will open
                   1274: a new window using Javascript. (Default is false.) 
                   1275: 
                   1276: $width and $height are optional numerical parameters that will
                   1277: override the width and height of the popped up window, which may
1.973     raeburn  1278: be useful for certain help topics with big pictures included.
                   1279: 
                   1280: $imgid is the id of the img tag used for the help icon. This may be
                   1281: used in a javascript call to switch the image src.  See 
                   1282: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1283: 
1.1381    raeburn  1284: $links_target will optionally be set to a target (_top, _parent or _self).
                   1285: 
1.44      bowersj2 1286: =cut
                   1287: 
                   1288: sub help_open_topic {
1.1381    raeburn  1289:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1290:     $text = "" if (not defined $text);
1.44      bowersj2 1291:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1292:     $width = 500 if (not defined $width);
1.44      bowersj2 1293:     $height = 400 if (not defined $height);
                   1294:     my $filename = $topic;
                   1295:     $filename =~ s/ /_/g;
                   1296: 
1.48      bowersj2 1297:     my $template = "";
                   1298:     my $link;
1.572     banghart 1299:     
1.159     www      1300:     $topic=~s/\W/\_/g;
1.44      bowersj2 1301: 
1.572     banghart 1302:     if (!$stayOnPage) {
1.1033    www      1303: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1304:     } elsif ($stayOnPage eq 'popup') {
                   1305:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1306:     } else {
1.48      bowersj2 1307: 	$link = "/adm/help/${filename}.hlp";
                   1308:     }
                   1309: 
                   1310:     # Add the text
1.1314    raeburn  1311:     my $target = ' target="_top"';
1.1381    raeburn  1312:     if ($links_target) {
                   1313:         $target = ' target="'.$links_target.'"';
                   1314:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1315:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1316:         $target = '';
1.1378    raeburn  1317:     }
1.1380    raeburn  1318:     if ($text ne "") {
1.763     bisitz   1319: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1320:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1321:                   .$text.'</a>';
1.48      bowersj2 1322:     }
                   1323: 
1.763     bisitz   1324:     # (Always) Add the graphic
1.179     matthew  1325:     my $title = &mt('Online Help');
1.667     raeburn  1326:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1327:     if ($imgid ne '') {
                   1328:         $imgid = ' id="'.$imgid.'"';
                   1329:     }
1.1314    raeburn  1330:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1331:               .'<img src="'.$helpicon.'" border="0"'
                   1332:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1333:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1334:               .' /></a>';
                   1335:     if ($text ne "") {	
                   1336:         $template.='</span>';
                   1337:     }
1.44      bowersj2 1338:     return $template;
                   1339: 
1.106     bowersj2 1340: }
                   1341: 
                   1342: # This is a quicky function for Latex cheatsheet editing, since it 
                   1343: # appears in at least four places
                   1344: sub helpLatexCheatsheet {
1.1037    www      1345:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1346:     my $out;
1.106     bowersj2 1347:     my $addOther = '';
1.732     raeburn  1348:     if ($topic) {
1.1037    www      1349: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1350:     }
                   1351:     $out = '<span>' # Start cheatsheet
                   1352: 	  .$addOther
                   1353:           .'<span>'
1.1037    www      1354: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1355: 	  .'</span> <span>'
1.1037    www      1356: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1357: 	  .'</span>';
1.732     raeburn  1358:     unless ($not_author) {
1.1186    kruse    1359:         $out .= '<span>'
                   1360:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1361:                .'</span> <span>'
                   1362:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1363: 	       .'</span>';
1.732     raeburn  1364:     }
1.763     bisitz   1365:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1366:     return $out;
1.172     www      1367: }
                   1368: 
1.430     albertel 1369: sub general_help {
                   1370:     my $helptopic='Student_Intro';
                   1371:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1372: 	$helptopic='Authoring_Intro';
1.907     raeburn  1373:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1374: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1375:     } elsif ($env{'request.role'}=~/^dc/) {
                   1376:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1377:     }
                   1378:     return $helptopic;
                   1379: }
                   1380: 
                   1381: sub update_help_link {
                   1382:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1383:     my $origurl = $ENV{'REQUEST_URI'};
                   1384:     $origurl=~s|^/~|/priv/|;
                   1385:     my $timestamp = time;
                   1386:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1387:         $$datum = &escape($$datum);
                   1388:     }
                   1389: 
                   1390:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1391:     my $output .= <<"ENDOUTPUT";
                   1392: <script type="text/javascript">
1.824     bisitz   1393: // <![CDATA[
1.430     albertel 1394: banner_link = '$banner_link';
1.824     bisitz   1395: // ]]>
1.430     albertel 1396: </script>
                   1397: ENDOUTPUT
                   1398:     return $output;
                   1399: }
                   1400: 
                   1401: # now just updates the help link and generates a blue icon
1.193     raeburn  1402: sub help_open_menu {
1.1381    raeburn  1403:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1404: 	= @_;    
1.949     droeschl 1405:     $stayOnPage = 1;
1.430     albertel 1406:     my $output;
                   1407:     if ($component_help) {
                   1408: 	if (!$text) {
                   1409: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1410: 				       $width,$height,'',$links_target);
1.430     albertel 1411: 	} else {
                   1412: 	    my $help_text;
                   1413: 	    $help_text=&unescape($topic);
                   1414: 	    $output='<table><tr><td>'.
                   1415: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1416: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1417: 	}
                   1418:     }
                   1419:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1420:     return $output.$banner_link;
                   1421: }
                   1422: 
                   1423: sub top_nav_help {
1.1369    raeburn  1424:     my ($text,$linkattr) = @_;
1.436     albertel 1425:     $text = &mt($text);
1.949     droeschl 1426:     my $stay_on_page = 1;
                   1427: 
1.1168    raeburn  1428:     my ($link,$banner_link);
                   1429:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1430:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1431: 	                         : "javascript:helpMenu('open')";
                   1432:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1433:     }
1.201     raeburn  1434:     my $title = &mt('Get help');
1.1168    raeburn  1435:     if ($link) {
                   1436:         return <<"END";
1.436     albertel 1437: $banner_link
1.1369    raeburn  1438: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1439: END
1.1168    raeburn  1440:     } else {
                   1441:         return '&nbsp;'.$text.'&nbsp;';
                   1442:     }
1.436     albertel 1443: }
                   1444: 
                   1445: sub help_menu_js {
1.1154    raeburn  1446:     my ($httphost) = @_;
1.949     droeschl 1447:     my $stayOnPage = 1;
1.436     albertel 1448:     my $width = 620;
                   1449:     my $height = 600;
1.430     albertel 1450:     my $helptopic=&general_help();
1.1154    raeburn  1451:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1452:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1453:     my $start_page =
                   1454:         &Apache::loncommon::start_page('Help Menu', undef,
                   1455: 				       {'frameset'    => 1,
                   1456: 					'js_ready'    => 1,
1.1154    raeburn  1457:                                         'use_absolute' => $httphost,
1.331     albertel 1458: 					'add_entries' => {
1.1168    raeburn  1459: 					    'border' => '0', 
1.579     raeburn  1460: 					    'rows'   => "110,*",},});
1.331     albertel 1461:     my $end_page =
                   1462:         &Apache::loncommon::end_page({'frameset' => 1,
                   1463: 				      'js_ready' => 1,});
                   1464: 
1.436     albertel 1465:     my $template .= <<"ENDTEMPLATE";
                   1466: <script type="text/javascript">
1.877     bisitz   1467: // <![CDATA[
1.253     albertel 1468: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1469: var banner_link = '';
1.243     raeburn  1470: function helpMenu(target) {
                   1471:     var caller = this;
                   1472:     if (target == 'open') {
                   1473:         var newWindow = null;
                   1474:         try {
1.262     albertel 1475:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1476:         }
                   1477:         catch(error) {
                   1478:             writeHelp(caller);
                   1479:             return;
                   1480:         }
                   1481:         if (newWindow) {
                   1482:             caller = newWindow;
                   1483:         }
1.193     raeburn  1484:     }
1.243     raeburn  1485:     writeHelp(caller);
                   1486:     return;
                   1487: }
                   1488: function writeHelp(caller) {
1.1168    raeburn  1489:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1490:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1491:     caller.document.close();
                   1492:     caller.focus();
1.193     raeburn  1493: }
1.877     bisitz   1494: // END LON-CAPA Internal -->
1.253     albertel 1495: // ]]>
1.436     albertel 1496: </script>
1.193     raeburn  1497: ENDTEMPLATE
                   1498:     return $template;
                   1499: }
                   1500: 
1.172     www      1501: sub help_open_bug {
                   1502:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1503:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1504:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1505:     $text = "" if (not defined $text);
                   1506: 	$stayOnPage=1;
1.184     albertel 1507:     $width = 600 if (not defined $width);
                   1508:     $height = 600 if (not defined $height);
1.172     www      1509: 
                   1510:     $topic=~s/\W+/\+/g;
                   1511:     my $link='';
                   1512:     my $template='';
1.379     albertel 1513:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1514: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1515:     if (!$stayOnPage)
                   1516:     {
                   1517: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1518:     }
                   1519:     else
                   1520:     {
                   1521: 	$link = $url;
                   1522:     }
1.1314    raeburn  1523: 
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;
                   6001:                                         foreach my $item ('text','img','alt','url','title','notsso') {
                   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.112     bowersj2 6380: =back
                   6381: 
1.60      matthew  6382: Returns: A uniform header for LON-CAPA web pages.  
                   6383: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6384: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6385: other decorations will be returned.
                   6386: 
                   6387: =cut
                   6388: 
1.54      www      6389: sub bodytag {
1.831     bisitz   6390:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6391:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
                   6392:         $ltimenu,$menucoll,$menuref)=@_;
1.339     albertel 6393: 
1.954     raeburn  6394:     my $public;
                   6395:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6396:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6397:         $public = 1;
                   6398:     }
1.460     albertel 6399:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6400:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6401:     my $hostname = $args->{'hostname'};
1.339     albertel 6402: 
1.183     matthew  6403:     $function = &get_users_function() if (!$function);
1.339     albertel 6404:     my $img =    &designparm($function.'.img',$domain);
                   6405:     my $font =   &designparm($function.'.font',$domain);
                   6406:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6407: 
1.803     bisitz   6408:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6409: 		   'bgcolor' => $pgbg,
1.339     albertel 6410: 		   'text'    => $font,
                   6411:                    'alink'   => &designparm($function.'.alink',$domain),
                   6412: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6413: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6414:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6415: 
1.63      www      6416:  # role and realm
1.1178    raeburn  6417:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6418:     if ($realm) {
                   6419:         $realm = '/'.$realm;
                   6420:     }
1.1357    raeburn  6421:     if ($role eq 'ca') {
1.479     albertel 6422:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6423:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6424:     } 
1.55      www      6425: # realm
1.1357    raeburn  6426:     my ($cid,$sec);
1.258     albertel 6427:     if ($env{'request.course.id'}) {
1.1357    raeburn  6428:         $cid = $env{'request.course.id'};
                   6429:         if ($env{'request.course.sec'}) {
                   6430:             $sec = $env{'request.course.sec'};
                   6431:         }
                   6432:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6433:         if (&Apache::lonnet::is_course($1,$2)) {
                   6434:             $cid = $1.'_'.$2;
                   6435:             $sec = $3;
                   6436:         }
                   6437:     }
                   6438:     if ($cid) {
1.378     raeburn  6439:         if ($env{'request.role'} !~ /^cr/) {
                   6440:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6441:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6442:             if ($env{'request.role.desc'}) {
                   6443:                 $role = $env{'request.role.desc'};
                   6444:             } else {
                   6445:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6446:             }
1.1257    raeburn  6447:         } else {
                   6448:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6449:         }
1.1357    raeburn  6450:         if ($sec) {
                   6451:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6452:         }   
1.1357    raeburn  6453: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6454:     } else {
                   6455:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6456:     }
1.433     albertel 6457: 
1.359     albertel 6458:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6459: 
1.438     albertel 6460:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6461: 
1.101     www      6462: # construct main body tag
1.359     albertel 6463:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6464: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6465: 
1.1131    raeburn  6466:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6467: 
1.1130    raeburn  6468:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6469:         return $bodytag;
1.1130    raeburn  6470:     }
1.359     albertel 6471: 
1.954     raeburn  6472:     if ($public) {
1.433     albertel 6473: 	undef($role);
                   6474:     }
1.1318    raeburn  6475: 
1.1359    raeburn  6476:     my $showcrstitle = 1;
1.1357    raeburn  6477:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6478:         if (ref($ltimenu) eq 'HASH') {
                   6479:             unless ($ltimenu->{'role'}) {
                   6480:                 undef($role);
                   6481:             }
                   6482:             unless ($ltimenu->{'coursetitle'}) {
                   6483:                 $realm='&nbsp;';
1.1359    raeburn  6484:                 $showcrstitle = 0;
                   6485:             }
                   6486:         }
                   6487:     } elsif (($cid) && ($menucoll)) {
                   6488:         if (ref($menuref) eq 'HASH') {
                   6489:             unless ($menuref->{'role'}) {
                   6490:                 undef($role);
                   6491:             }
                   6492:             unless ($menuref->{'crs'}) {
                   6493:                 $realm='&nbsp;';
                   6494:                 $showcrstitle = 0;
1.1318    raeburn  6495:             }
                   6496:         }
                   6497:     }
                   6498: 
1.762     bisitz   6499:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6500:     #
                   6501:     # Extra info if you are the DC
                   6502:     my $dc_info = '';
1.1359    raeburn  6503:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6504:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6505:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6506:         $dc_info =~ s/\s+$//;
1.359     albertel 6507:     }
                   6508: 
1.1237    raeburn  6509:     my $crstype;
1.1357    raeburn  6510:     if ($cid) {
                   6511:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6512:     } elsif ($args->{'crstype'}) {
                   6513:         $crstype = $args->{'crstype'};
                   6514:     }
                   6515:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6516:         undef($role);
                   6517:     } else {
1.1242    raeburn  6518:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6519:     }
1.853     droeschl 6520: 
1.903     droeschl 6521:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6522: 
                   6523:         #    if ($env{'request.state'} eq 'construct') {
                   6524:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6525:         #    }
                   6526: 
1.1130    raeburn  6527:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6528:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6529: 
1.1318    raeburn  6530:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6531:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6532:                                                               $args->{'links_disabled'},
                   6533:                                                               $args->{'links_target'});
1.359     albertel 6534: 
1.1318    raeburn  6535:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6536:                 if ($dc_info) {
                   6537:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6538:                 }
                   6539:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6540:                                <em>$realm</em> $dc_info</div>|;
                   6541:                 return $bodytag;
                   6542:             }
1.894     droeschl 6543: 
1.1318    raeburn  6544:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6545:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6546:             }
1.916     droeschl 6547: 
1.1318    raeburn  6548:             $bodytag .= $right;
1.852     droeschl 6549: 
1.1318    raeburn  6550:             if ($dc_info) {
                   6551:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6552:             }
                   6553:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6554:         }
1.916     droeschl 6555: 
1.1169    raeburn  6556:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6557:         if ($args->{'no_secondary_menu'}) {
                   6558:             return $bodytag;
                   6559:         }
1.1169    raeburn  6560:         #don't show menus for public users
1.954     raeburn  6561:         if (!$public){
1.1318    raeburn  6562:             unless ($args->{'no_inline_menu'}) {
                   6563:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6564:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6565:                                                             $menucoll,$menuref,
1.1380    raeburn  6566:                                                             $args->{'links_disabled'},
                   6567:                                                             $args->{'links_target'});
1.1318    raeburn  6568:             }
1.903     droeschl 6569:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6570:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6571:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6572:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1316    raeburn  6573:                                 $args->{'bread_crumbs'},'','',$hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6574:             } elsif ($forcereg) {
                   6575:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1258    raeburn  6576:                                                             $args->{'group'},
1.1274    raeburn  6577:                                                             $args->{'hide_buttons'},
1.1316    raeburn  6578:                                                             $hostname,$ltiscope,$ltiuri);
1.1096    raeburn  6579:             } else {
                   6580:                 $bodytag .= 
                   6581:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6582:                                                         $forcereg,$args->{'group'},
                   6583:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6584:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6585:             }
1.903     droeschl 6586:         }else{
                   6587:             # this is to seperate menu from content when there's no secondary
                   6588:             # menu. Especially needed for public accessible ressources.
                   6589:             $bodytag .= '<hr style="clear:both" />';
                   6590:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6591:         }
1.903     droeschl 6592: 
1.235     raeburn  6593:         return $bodytag;
1.182     matthew  6594: }
                   6595: 
1.917     raeburn  6596: sub dc_courseid_toggle {
                   6597:     my ($dc_info) = @_;
1.980     raeburn  6598:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6599:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6600:            &mt('(More ...)').'</a></span>'.
                   6601:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6602: }
                   6603: 
1.330     albertel 6604: sub make_attr_string {
                   6605:     my ($register,$attr_ref) = @_;
                   6606: 
                   6607:     if ($attr_ref && !ref($attr_ref)) {
                   6608: 	die("addentries Must be a hash ref ".
                   6609: 	    join(':',caller(1))." ".
                   6610: 	    join(':',caller(0))." ");
                   6611:     }
                   6612: 
                   6613:     if ($register) {
1.339     albertel 6614: 	my ($on_load,$on_unload);
                   6615: 	foreach my $key (keys(%{$attr_ref})) {
                   6616: 	    if      (lc($key) eq 'onload') {
                   6617: 		$on_load.=$attr_ref->{$key}.';';
                   6618: 		delete($attr_ref->{$key});
                   6619: 
                   6620: 	    } elsif (lc($key) eq 'onunload') {
                   6621: 		$on_unload.=$attr_ref->{$key}.';';
                   6622: 		delete($attr_ref->{$key});
                   6623: 	    }
                   6624: 	}
1.953     droeschl 6625: 	$attr_ref->{'onload'}  = $on_load;
                   6626: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 6627:     }
1.339     albertel 6628: 
1.330     albertel 6629:     my $attr_string;
1.1159    raeburn  6630:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6631: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6632:     }
                   6633:     return $attr_string;
                   6634: }
                   6635: 
                   6636: 
1.182     matthew  6637: ###############################################
1.251     albertel 6638: ###############################################
                   6639: 
                   6640: =pod
                   6641: 
                   6642: =item * &endbodytag()
                   6643: 
                   6644: Returns a uniform footer for LON-CAPA web pages.
                   6645: 
1.635     raeburn  6646: Inputs: 1 - optional reference to an args hash
                   6647: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6648: a 'Continue' link is not displayed if the page contains an
                   6649: internal redirect in the <head></head> section,
                   6650: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6651: 
                   6652: =cut
                   6653: 
                   6654: sub endbodytag {
1.635     raeburn  6655:     my ($args) = @_;
1.1080    raeburn  6656:     my $endbodytag;
                   6657:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6658:         $endbodytag='</body>';
                   6659:     }
1.315     albertel 6660:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6661:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   6662: 	    $endbodytag=
                   6663: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   6664: 	        &mt('Continue').'</a>'.
                   6665: 	        $endbodytag;
                   6666:         }
1.315     albertel 6667:     }
1.251     albertel 6668:     return $endbodytag;
                   6669: }
                   6670: 
1.352     albertel 6671: =pod
                   6672: 
                   6673: =item * &standard_css()
                   6674: 
                   6675: Returns a style sheet
                   6676: 
                   6677: Inputs: (all optional)
                   6678:             domain         -> force to color decorate a page for a specific
                   6679:                                domain
                   6680:             function       -> force usage of a specific rolish color scheme
                   6681:             bgcolor        -> override the default page bgcolor
                   6682: 
                   6683: =cut
                   6684: 
1.343     albertel 6685: sub standard_css {
1.345     albertel 6686:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6687:     $function  = &get_users_function() if (!$function);
                   6688:     my $img    = &designparm($function.'.img',   $domain);
                   6689:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6690:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6691:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6692: #second colour for later usage
1.345     albertel 6693:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6694:     my $pgbg_or_bgcolor =
                   6695: 	         $bgcolor ||
1.352     albertel 6696: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6697:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6698:     my $alink  = &designparm($function.'.alink', $domain);
                   6699:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6700:     my $link   = &designparm($function.'.link',  $domain);
                   6701: 
1.602     albertel 6702:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6703:     my $mono                 = 'monospace';
1.850     bisitz   6704:     my $data_table_head      = $sidebg;
                   6705:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6706:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6707:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6708:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6709:     my $mail_new             = '#FFBB77';
                   6710:     my $mail_new_hover       = '#DD9955';
                   6711:     my $mail_read            = '#BBBB77';
                   6712:     my $mail_read_hover      = '#999944';
                   6713:     my $mail_replied         = '#AAAA88';
                   6714:     my $mail_replied_hover   = '#888855';
                   6715:     my $mail_other           = '#99BBBB';
                   6716:     my $mail_other_hover     = '#669999';
1.391     albertel 6717:     my $table_header         = '#DDDDDD';
1.489     raeburn  6718:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6719:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6720:     my $button_hover         = '#BF2317';
1.392     albertel 6721: 
1.608     albertel 6722:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6723:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6724:                                              : '0 3px 0 4px';
1.448     albertel 6725: 
1.523     albertel 6726: 
1.343     albertel 6727:     return <<END;
1.947     droeschl 6728: 
                   6729: /* needed for iframe to allow 100% height in FF */
                   6730: body, html { 
                   6731:     margin: 0;
                   6732:     padding: 0 0.5%;
                   6733:     height: 99%; /* to avoid scrollbars */
                   6734: }
                   6735: 
1.795     www      6736: body {
1.911     bisitz   6737:   font-family: $sans;
                   6738:   line-height:130%;
                   6739:   font-size:0.83em;
                   6740:   color:$font;
1.795     www      6741: }
                   6742: 
1.959     onken    6743: a:focus,
                   6744: a:focus img {
1.795     www      6745:   color: red;
                   6746: }
1.698     harmsja  6747: 
1.911     bisitz   6748: form, .inline {
                   6749:   display: inline;
1.795     www      6750: }
1.721     harmsja  6751: 
1.795     www      6752: .LC_right {
1.911     bisitz   6753:   text-align:right;
1.795     www      6754: }
                   6755: 
                   6756: .LC_middle {
1.911     bisitz   6757:   vertical-align:middle;
1.795     www      6758: }
1.721     harmsja  6759: 
1.1130    raeburn  6760: .LC_floatleft {
                   6761:   float: left;
                   6762: }
                   6763: 
                   6764: .LC_floatright {
                   6765:   float: right;
                   6766: }
                   6767: 
1.911     bisitz   6768: .LC_400Box {
                   6769:   width:400px;
                   6770: }
1.721     harmsja  6771: 
1.947     droeschl 6772: .LC_iframecontainer {
                   6773:     width: 98%;
                   6774:     margin: 0;
                   6775:     position: fixed;
                   6776:     top: 8.5em;
                   6777:     bottom: 0;
                   6778: }
                   6779: 
                   6780: .LC_iframecontainer iframe{
                   6781:     border: none;
                   6782:     width: 100%;
                   6783:     height: 100%;
                   6784: }
                   6785: 
1.778     bisitz   6786: .LC_filename {
                   6787:   font-family: $mono;
                   6788:   white-space:pre;
1.921     bisitz   6789:   font-size: 120%;
1.778     bisitz   6790: }
                   6791: 
                   6792: .LC_fileicon {
                   6793:   border: none;
                   6794:   height: 1.3em;
                   6795:   vertical-align: text-bottom;
                   6796:   margin-right: 0.3em;
                   6797:   text-decoration:none;
                   6798: }
                   6799: 
1.1008    www      6800: .LC_setting {
                   6801:   text-decoration:underline;
                   6802: }
                   6803: 
1.350     albertel 6804: .LC_error {
                   6805:   color: red;
                   6806: }
1.795     www      6807: 
1.1097    bisitz   6808: .LC_warning {
                   6809:   color: darkorange;
                   6810: }
                   6811: 
1.457     albertel 6812: .LC_diff_removed {
1.733     bisitz   6813:   color: red;
1.394     albertel 6814: }
1.532     albertel 6815: 
                   6816: .LC_info,
1.457     albertel 6817: .LC_success,
                   6818: .LC_diff_added {
1.350     albertel 6819:   color: green;
                   6820: }
1.795     www      6821: 
1.802     bisitz   6822: div.LC_confirm_box {
                   6823:   background-color: #FAFAFA;
                   6824:   border: 1px solid $lg_border_color;
                   6825:   margin-right: 0;
                   6826:   padding: 5px;
                   6827: }
                   6828: 
                   6829: div.LC_confirm_box .LC_error img,
                   6830: div.LC_confirm_box .LC_success img {
                   6831:   vertical-align: middle;
                   6832: }
                   6833: 
1.1242    raeburn  6834: .LC_maxwidth {
                   6835:   max-width: 100%;
                   6836:   height: auto;
                   6837: }
                   6838: 
1.1243    raeburn  6839: .LC_textsize_mobile {
                   6840:   \@media only screen and (max-device-width: 480px) {
                   6841:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6842:   }
                   6843: }
                   6844: 
1.440     albertel 6845: .LC_icon {
1.771     droeschl 6846:   border: none;
1.790     droeschl 6847:   vertical-align: middle;
1.771     droeschl 6848: }
                   6849: 
1.543     albertel 6850: .LC_docs_spacer {
                   6851:   width: 25px;
                   6852:   height: 1px;
1.771     droeschl 6853:   border: none;
1.543     albertel 6854: }
1.346     albertel 6855: 
1.532     albertel 6856: .LC_internal_info {
1.735     bisitz   6857:   color: #999999;
1.532     albertel 6858: }
                   6859: 
1.794     www      6860: .LC_discussion {
1.1050    www      6861:   background: $data_table_dark;
1.911     bisitz   6862:   border: 1px solid black;
                   6863:   margin: 2px;
1.794     www      6864: }
                   6865: 
                   6866: .LC_disc_action_left {
1.1050    www      6867:   background: $sidebg;
1.911     bisitz   6868:   text-align: left;
1.1050    www      6869:   padding: 4px;
                   6870:   margin: 2px;
1.794     www      6871: }
                   6872: 
                   6873: .LC_disc_action_right {
1.1050    www      6874:   background: $sidebg;
1.911     bisitz   6875:   text-align: right;
1.1050    www      6876:   padding: 4px;
                   6877:   margin: 2px;
1.794     www      6878: }
                   6879: 
                   6880: .LC_disc_new_item {
1.911     bisitz   6881:   background: white;
                   6882:   border: 2px solid red;
1.1050    www      6883:   margin: 4px;
                   6884:   padding: 4px;
1.794     www      6885: }
                   6886: 
                   6887: .LC_disc_old_item {
1.911     bisitz   6888:   background: white;
1.1050    www      6889:   margin: 4px;
                   6890:   padding: 4px;
1.794     www      6891: }
                   6892: 
1.458     albertel 6893: table.LC_pastsubmission {
                   6894:   border: 1px solid black;
                   6895:   margin: 2px;
                   6896: }
                   6897: 
1.924     bisitz   6898: table#LC_menubuttons {
1.345     albertel 6899:   width: 100%;
                   6900:   background: $pgbg;
1.392     albertel 6901:   border: 2px;
1.402     albertel 6902:   border-collapse: separate;
1.803     bisitz   6903:   padding: 0;
1.345     albertel 6904: }
1.392     albertel 6905: 
1.801     tempelho 6906: table#LC_title_bar a {
                   6907:   color: $fontmenu;
                   6908: }
1.836     bisitz   6909: 
1.807     droeschl 6910: table#LC_title_bar {
1.819     tempelho 6911:   clear: both;
1.836     bisitz   6912:   display: none;
1.807     droeschl 6913: }
                   6914: 
1.795     www      6915: table#LC_title_bar,
1.933     droeschl 6916: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6917: table#LC_title_bar.LC_with_remote {
1.359     albertel 6918:   width: 100%;
1.392     albertel 6919:   border-color: $pgbg;
                   6920:   border-style: solid;
                   6921:   border-width: $border;
1.379     albertel 6922:   background: $pgbg;
1.801     tempelho 6923:   color: $fontmenu;
1.392     albertel 6924:   border-collapse: collapse;
1.803     bisitz   6925:   padding: 0;
1.819     tempelho 6926:   margin: 0;
1.359     albertel 6927: }
1.795     www      6928: 
1.933     droeschl 6929: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6930:     margin: 0;
                   6931:     padding: 0;
1.933     droeschl 6932:     position: relative;
                   6933:     list-style: none;
1.913     droeschl 6934: }
1.933     droeschl 6935: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6936:     display: inline;
                   6937: }
1.933     droeschl 6938: 
                   6939: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6940:     padding: 0;
1.933     droeschl 6941:     margin: 0;
                   6942:     float: left;
1.913     droeschl 6943: }
1.933     droeschl 6944: .LC_breadcrumb_tools_tools {
                   6945:     padding: 0;
                   6946:     margin: 0;
1.913     droeschl 6947:     float: right;
                   6948: }
                   6949: 
1.1240    raeburn  6950: .LC_placement_prog {
                   6951:     padding-right: 20px;
                   6952:     font-weight: bold;
                   6953:     font-size: 90%;
                   6954: }
                   6955: 
1.359     albertel 6956: table#LC_title_bar td {
                   6957:   background: $tabbg;
                   6958: }
1.795     www      6959: 
1.911     bisitz   6960: table#LC_menubuttons img {
1.803     bisitz   6961:   border: none;
1.346     albertel 6962: }
1.795     www      6963: 
1.842     droeschl 6964: .LC_breadcrumbs_component {
1.911     bisitz   6965:   float: right;
                   6966:   margin: 0 1em;
1.357     albertel 6967: }
1.842     droeschl 6968: .LC_breadcrumbs_component img {
1.911     bisitz   6969:   vertical-align: middle;
1.777     tempelho 6970: }
1.795     www      6971: 
1.1243    raeburn  6972: .LC_breadcrumbs_hoverable {
                   6973:   background: $sidebg;
                   6974: }
                   6975: 
1.383     albertel 6976: td.LC_table_cell_checkbox {
                   6977:   text-align: center;
                   6978: }
1.795     www      6979: 
                   6980: .LC_fontsize_small {
1.911     bisitz   6981:   font-size: 70%;
1.705     tempelho 6982: }
                   6983: 
1.844     bisitz   6984: #LC_breadcrumbs {
1.911     bisitz   6985:   clear:both;
                   6986:   background: $sidebg;
                   6987:   border-bottom: 1px solid $lg_border_color;
                   6988:   line-height: 2.5em;
1.933     droeschl 6989:   overflow: hidden;
1.911     bisitz   6990:   margin: 0;
                   6991:   padding: 0;
1.995     raeburn  6992:   text-align: left;
1.819     tempelho 6993: }
1.862     bisitz   6994: 
1.1098    bisitz   6995: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6996:   clear:both;
                   6997:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6998:   border: 1px solid $sidebg;
1.1098    bisitz   6999:   margin: 0 0 10px 0;
1.966     bisitz   7000:   padding: 3px;
1.995     raeburn  7001:   text-align: left;
1.822     bisitz   7002: }
                   7003: 
1.795     www      7004: .LC_fontsize_medium {
1.911     bisitz   7005:   font-size: 85%;
1.705     tempelho 7006: }
                   7007: 
1.795     www      7008: .LC_fontsize_large {
1.911     bisitz   7009:   font-size: 120%;
1.705     tempelho 7010: }
                   7011: 
1.346     albertel 7012: .LC_menubuttons_inline_text {
                   7013:   color: $font;
1.698     harmsja  7014:   font-size: 90%;
1.701     harmsja  7015:   padding-left:3px;
1.346     albertel 7016: }
                   7017: 
1.934     droeschl 7018: .LC_menubuttons_inline_text img{
                   7019:   vertical-align: middle;
                   7020: }
                   7021: 
1.1051    www      7022: li.LC_menubuttons_inline_text img {
1.951     onken    7023:   cursor:pointer;
1.1002    droeschl 7024:   text-decoration: none;
1.951     onken    7025: }
                   7026: 
1.526     www      7027: .LC_menubuttons_link {
                   7028:   text-decoration: none;
                   7029: }
1.795     www      7030: 
1.522     albertel 7031: .LC_menubuttons_category {
1.521     www      7032:   color: $font;
1.526     www      7033:   background: $pgbg;
1.521     www      7034:   font-size: larger;
                   7035:   font-weight: bold;
                   7036: }
                   7037: 
1.346     albertel 7038: td.LC_menubuttons_text {
1.911     bisitz   7039:   color: $font;
1.346     albertel 7040: }
1.706     harmsja  7041: 
1.346     albertel 7042: .LC_current_location {
                   7043:   background: $tabbg;
                   7044: }
1.795     www      7045: 
1.1286    raeburn  7046: td.LC_zero_height {
                   7047:   line-height: 0; 
                   7048:   cellpadding: 0;
                   7049: }
                   7050: 
1.938     bisitz   7051: table.LC_data_table {
1.347     albertel 7052:   border: 1px solid #000000;
1.402     albertel 7053:   border-collapse: separate;
1.426     albertel 7054:   border-spacing: 1px;
1.610     albertel 7055:   background: $pgbg;
1.347     albertel 7056: }
1.795     www      7057: 
1.422     albertel 7058: .LC_data_table_dense {
                   7059:   font-size: small;
                   7060: }
1.795     www      7061: 
1.507     raeburn  7062: table.LC_nested_outer {
                   7063:   border: 1px solid #000000;
1.589     raeburn  7064:   border-collapse: collapse;
1.803     bisitz   7065:   border-spacing: 0;
1.507     raeburn  7066:   width: 100%;
                   7067: }
1.795     www      7068: 
1.879     raeburn  7069: table.LC_innerpickbox,
1.507     raeburn  7070: table.LC_nested {
1.803     bisitz   7071:   border: none;
1.589     raeburn  7072:   border-collapse: collapse;
1.803     bisitz   7073:   border-spacing: 0;
1.507     raeburn  7074:   width: 100%;
                   7075: }
1.795     www      7076: 
1.911     bisitz   7077: table.LC_data_table tr th,
                   7078: table.LC_calendar tr th,
1.879     raeburn  7079: table.LC_prior_tries tr th,
                   7080: table.LC_innerpickbox tr th {
1.349     albertel 7081:   font-weight: bold;
                   7082:   background-color: $data_table_head;
1.801     tempelho 7083:   color:$fontmenu;
1.701     harmsja  7084:   font-size:90%;
1.347     albertel 7085: }
1.795     www      7086: 
1.879     raeburn  7087: table.LC_innerpickbox tr th,
                   7088: table.LC_innerpickbox tr td {
                   7089:   vertical-align: top;
                   7090: }
                   7091: 
1.711     raeburn  7092: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7093:   background-color: #CCCCCC;
1.711     raeburn  7094:   font-weight: bold;
                   7095:   text-align: left;
                   7096: }
1.795     www      7097: 
1.912     bisitz   7098: table.LC_data_table tr.LC_odd_row > td {
                   7099:   background-color: $data_table_light;
                   7100:   padding: 2px;
                   7101:   vertical-align: top;
                   7102: }
                   7103: 
1.809     bisitz   7104: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7105:   background-color: $data_table_light;
1.912     bisitz   7106:   vertical-align: top;
                   7107: }
                   7108: 
                   7109: table.LC_data_table tr.LC_even_row > td {
                   7110:   background-color: $data_table_dark;
1.425     albertel 7111:   padding: 2px;
1.900     bisitz   7112:   vertical-align: top;
1.347     albertel 7113: }
1.795     www      7114: 
1.809     bisitz   7115: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7116:   background-color: $data_table_dark;
1.900     bisitz   7117:   vertical-align: top;
1.347     albertel 7118: }
1.795     www      7119: 
1.425     albertel 7120: table.LC_data_table tr.LC_data_table_highlight td {
                   7121:   background-color: $data_table_darker;
                   7122: }
1.795     www      7123: 
1.639     raeburn  7124: table.LC_data_table tr td.LC_leftcol_header {
                   7125:   background-color: $data_table_head;
                   7126:   font-weight: bold;
                   7127: }
1.795     www      7128: 
1.451     albertel 7129: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7130: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7131:   font-weight: bold;
                   7132:   font-style: italic;
                   7133:   text-align: center;
                   7134:   padding: 8px;
1.347     albertel 7135: }
1.795     www      7136: 
1.1114    raeburn  7137: table.LC_data_table tr.LC_empty_row td,
                   7138: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7139:   background-color: $sidebg;
                   7140: }
                   7141: 
                   7142: table.LC_nested tr.LC_empty_row td {
                   7143:   background-color: #FFFFFF;
                   7144: }
                   7145: 
1.890     droeschl 7146: table.LC_caption {
                   7147: }
                   7148: 
1.507     raeburn  7149: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7150:   padding: 4ex
                   7151: }
1.795     www      7152: 
1.507     raeburn  7153: table.LC_nested_outer tr th {
                   7154:   font-weight: bold;
1.801     tempelho 7155:   color:$fontmenu;
1.507     raeburn  7156:   background-color: $data_table_head;
1.701     harmsja  7157:   font-size: small;
1.507     raeburn  7158:   border-bottom: 1px solid #000000;
                   7159: }
1.795     www      7160: 
1.507     raeburn  7161: table.LC_nested_outer tr td.LC_subheader {
                   7162:   background-color: $data_table_head;
                   7163:   font-weight: bold;
                   7164:   font-size: small;
                   7165:   border-bottom: 1px solid #000000;
                   7166:   text-align: right;
1.451     albertel 7167: }
1.795     www      7168: 
1.507     raeburn  7169: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7170:   background-color: #CCCCCC;
1.451     albertel 7171:   font-weight: bold;
                   7172:   font-size: small;
1.507     raeburn  7173:   text-align: center;
                   7174: }
1.795     www      7175: 
1.589     raeburn  7176: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7177: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7178:   text-align: left;
1.451     albertel 7179: }
1.795     www      7180: 
1.507     raeburn  7181: table.LC_nested td {
1.735     bisitz   7182:   background-color: #FFFFFF;
1.451     albertel 7183:   font-size: small;
1.507     raeburn  7184: }
1.795     www      7185: 
1.507     raeburn  7186: table.LC_nested_outer tr th.LC_right_item,
                   7187: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7188: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7189: table.LC_nested tr td.LC_right_item {
1.451     albertel 7190:   text-align: right;
                   7191: }
                   7192: 
1.507     raeburn  7193: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7194:   background-color: #EEEEEE;
1.451     albertel 7195: }
                   7196: 
1.473     raeburn  7197: table.LC_createuser {
                   7198: }
                   7199: 
                   7200: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7201:   font-size: small;
1.473     raeburn  7202: }
                   7203: 
                   7204: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7205:   background-color: #CCCCCC;
1.473     raeburn  7206:   font-weight: bold;
                   7207:   text-align: center;
                   7208: }
                   7209: 
1.349     albertel 7210: table.LC_calendar {
                   7211:   border: 1px solid #000000;
                   7212:   border-collapse: collapse;
1.917     raeburn  7213:   width: 98%;
1.349     albertel 7214: }
1.795     www      7215: 
1.349     albertel 7216: table.LC_calendar_pickdate {
                   7217:   font-size: xx-small;
                   7218: }
1.795     www      7219: 
1.349     albertel 7220: table.LC_calendar tr td {
                   7221:   border: 1px solid #000000;
                   7222:   vertical-align: top;
1.917     raeburn  7223:   width: 14%;
1.349     albertel 7224: }
1.795     www      7225: 
1.349     albertel 7226: table.LC_calendar tr td.LC_calendar_day_empty {
                   7227:   background-color: $data_table_dark;
                   7228: }
1.795     www      7229: 
1.779     bisitz   7230: table.LC_calendar tr td.LC_calendar_day_current {
                   7231:   background-color: $data_table_highlight;
1.777     tempelho 7232: }
1.795     www      7233: 
1.938     bisitz   7234: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7235:   background-color: $mail_new;
                   7236: }
1.795     www      7237: 
1.938     bisitz   7238: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7239:   background-color: $mail_new_hover;
                   7240: }
1.795     www      7241: 
1.938     bisitz   7242: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7243:   background-color: $mail_read;
                   7244: }
1.795     www      7245: 
1.938     bisitz   7246: /*
                   7247: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7248:   background-color: $mail_read_hover;
                   7249: }
1.938     bisitz   7250: */
1.795     www      7251: 
1.938     bisitz   7252: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7253:   background-color: $mail_replied;
                   7254: }
1.795     www      7255: 
1.938     bisitz   7256: /*
                   7257: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7258:   background-color: $mail_replied_hover;
                   7259: }
1.938     bisitz   7260: */
1.795     www      7261: 
1.938     bisitz   7262: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7263:   background-color: $mail_other;
                   7264: }
1.795     www      7265: 
1.938     bisitz   7266: /*
                   7267: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7268:   background-color: $mail_other_hover;
                   7269: }
1.938     bisitz   7270: */
1.494     raeburn  7271: 
1.777     tempelho 7272: table.LC_data_table tr > td.LC_browser_file,
                   7273: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7274:   background: #AAEE77;
1.389     albertel 7275: }
1.795     www      7276: 
1.777     tempelho 7277: table.LC_data_table tr > td.LC_browser_file_locked,
                   7278: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7279:   background: #FFAA99;
1.387     albertel 7280: }
1.795     www      7281: 
1.777     tempelho 7282: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7283:   background: #888888;
1.779     bisitz   7284: }
1.795     www      7285: 
1.777     tempelho 7286: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7287: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7288:   background: #F8F866;
1.777     tempelho 7289: }
1.795     www      7290: 
1.696     bisitz   7291: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7292:   background: #E0E8FF;
1.387     albertel 7293: }
1.696     bisitz   7294: 
1.707     bisitz   7295: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7296:   /* background: #77FF77; */
1.707     bisitz   7297: }
1.795     www      7298: 
1.707     bisitz   7299: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7300:   border-right: 8px solid #FFFF77;
1.707     bisitz   7301: }
1.795     www      7302: 
1.707     bisitz   7303: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7304:   border-right: 8px solid #FFAA77;
1.707     bisitz   7305: }
1.795     www      7306: 
1.707     bisitz   7307: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7308:   border-right: 8px solid #FF7777;
1.707     bisitz   7309: }
1.795     www      7310: 
1.707     bisitz   7311: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7312:   border-right: 8px solid #AAFF77;
1.707     bisitz   7313: }
1.795     www      7314: 
1.707     bisitz   7315: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7316:   border-right: 8px solid #11CC55;
1.707     bisitz   7317: }
                   7318: 
1.388     albertel 7319: span.LC_current_location {
1.701     harmsja  7320:   font-size:larger;
1.388     albertel 7321:   background: $pgbg;
                   7322: }
1.387     albertel 7323: 
1.1029    www      7324: span.LC_current_nav_location {
                   7325:   font-weight:bold;
                   7326:   background: $sidebg;
                   7327: }
                   7328: 
1.395     albertel 7329: span.LC_parm_menu_item {
                   7330:   font-size: larger;
                   7331: }
1.795     www      7332: 
1.395     albertel 7333: span.LC_parm_scope_all {
                   7334:   color: red;
                   7335: }
1.795     www      7336: 
1.395     albertel 7337: span.LC_parm_scope_folder {
                   7338:   color: green;
                   7339: }
1.795     www      7340: 
1.395     albertel 7341: span.LC_parm_scope_resource {
                   7342:   color: orange;
                   7343: }
1.795     www      7344: 
1.395     albertel 7345: span.LC_parm_part {
                   7346:   color: blue;
                   7347: }
1.795     www      7348: 
1.911     bisitz   7349: span.LC_parm_folder,
                   7350: span.LC_parm_symb {
1.395     albertel 7351:   font-size: x-small;
                   7352:   font-family: $mono;
                   7353:   color: #AAAAAA;
                   7354: }
                   7355: 
1.977     bisitz   7356: ul.LC_parm_parmlist li {
                   7357:   display: inline-block;
                   7358:   padding: 0.3em 0.8em;
                   7359:   vertical-align: top;
                   7360:   width: 150px;
                   7361:   border-top:1px solid $lg_border_color;
                   7362: }
                   7363: 
1.795     www      7364: td.LC_parm_overview_level_menu,
                   7365: td.LC_parm_overview_map_menu,
                   7366: td.LC_parm_overview_parm_selectors,
                   7367: td.LC_parm_overview_restrictions  {
1.396     albertel 7368:   border: 1px solid black;
                   7369:   border-collapse: collapse;
                   7370: }
1.795     www      7371: 
1.1285    raeburn  7372: span.LC_parm_recursive,
                   7373: td.LC_parm_recursive {
                   7374:   font-weight: bold;
                   7375:   font-size: smaller;
                   7376: }
                   7377: 
1.396     albertel 7378: table.LC_parm_overview_restrictions td {
                   7379:   border-width: 1px 4px 1px 4px;
                   7380:   border-style: solid;
                   7381:   border-color: $pgbg;
                   7382:   text-align: center;
                   7383: }
1.795     www      7384: 
1.396     albertel 7385: table.LC_parm_overview_restrictions th {
                   7386:   background: $tabbg;
                   7387:   border-width: 1px 4px 1px 4px;
                   7388:   border-style: solid;
                   7389:   border-color: $pgbg;
                   7390: }
1.795     www      7391: 
1.398     albertel 7392: table#LC_helpmenu {
1.803     bisitz   7393:   border: none;
1.398     albertel 7394:   height: 55px;
1.803     bisitz   7395:   border-spacing: 0;
1.398     albertel 7396: }
                   7397: 
                   7398: table#LC_helpmenu fieldset legend {
                   7399:   font-size: larger;
                   7400: }
1.795     www      7401: 
1.397     albertel 7402: table#LC_helpmenu_links {
                   7403:   width: 100%;
                   7404:   border: 1px solid black;
                   7405:   background: $pgbg;
1.803     bisitz   7406:   padding: 0;
1.397     albertel 7407:   border-spacing: 1px;
                   7408: }
1.795     www      7409: 
1.397     albertel 7410: table#LC_helpmenu_links tr td {
                   7411:   padding: 1px;
                   7412:   background: $tabbg;
1.399     albertel 7413:   text-align: center;
                   7414:   font-weight: bold;
1.397     albertel 7415: }
1.396     albertel 7416: 
1.795     www      7417: table#LC_helpmenu_links a:link,
                   7418: table#LC_helpmenu_links a:visited,
1.397     albertel 7419: table#LC_helpmenu_links a:active {
                   7420:   text-decoration: none;
                   7421:   color: $font;
                   7422: }
1.795     www      7423: 
1.397     albertel 7424: table#LC_helpmenu_links a:hover {
                   7425:   text-decoration: underline;
                   7426:   color: $vlink;
                   7427: }
1.396     albertel 7428: 
1.417     albertel 7429: .LC_chrt_popup_exists {
                   7430:   border: 1px solid #339933;
                   7431:   margin: -1px;
                   7432: }
1.795     www      7433: 
1.417     albertel 7434: .LC_chrt_popup_up {
                   7435:   border: 1px solid yellow;
                   7436:   margin: -1px;
                   7437: }
1.795     www      7438: 
1.417     albertel 7439: .LC_chrt_popup {
                   7440:   border: 1px solid #8888FF;
                   7441:   background: #CCCCFF;
                   7442: }
1.795     www      7443: 
1.421     albertel 7444: table.LC_pick_box {
                   7445:   border-collapse: separate;
                   7446:   background: white;
                   7447:   border: 1px solid black;
                   7448:   border-spacing: 1px;
                   7449: }
1.795     www      7450: 
1.421     albertel 7451: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7452:   background: $sidebg;
1.421     albertel 7453:   font-weight: bold;
1.900     bisitz   7454:   text-align: left;
1.740     bisitz   7455:   vertical-align: top;
1.421     albertel 7456:   width: 184px;
                   7457:   padding: 8px;
                   7458: }
1.795     www      7459: 
1.579     raeburn  7460: table.LC_pick_box td.LC_pick_box_value {
                   7461:   text-align: left;
                   7462:   padding: 8px;
                   7463: }
1.795     www      7464: 
1.579     raeburn  7465: table.LC_pick_box td.LC_pick_box_select {
                   7466:   text-align: left;
                   7467:   padding: 8px;
                   7468: }
1.795     www      7469: 
1.424     albertel 7470: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7471:   padding: 0;
1.421     albertel 7472:   height: 1px;
                   7473:   background: black;
                   7474: }
1.795     www      7475: 
1.421     albertel 7476: table.LC_pick_box td.LC_pick_box_submit {
                   7477:   text-align: right;
                   7478: }
1.795     www      7479: 
1.579     raeburn  7480: table.LC_pick_box td.LC_evenrow_value {
                   7481:   text-align: left;
                   7482:   padding: 8px;
                   7483:   background-color: $data_table_light;
                   7484: }
1.795     www      7485: 
1.579     raeburn  7486: table.LC_pick_box td.LC_oddrow_value {
                   7487:   text-align: left;
                   7488:   padding: 8px;
                   7489:   background-color: $data_table_light;
                   7490: }
1.795     www      7491: 
1.579     raeburn  7492: span.LC_helpform_receipt_cat {
                   7493:   font-weight: bold;
                   7494: }
1.795     www      7495: 
1.424     albertel 7496: table.LC_group_priv_box {
                   7497:   background: white;
                   7498:   border: 1px solid black;
                   7499:   border-spacing: 1px;
                   7500: }
1.795     www      7501: 
1.424     albertel 7502: table.LC_group_priv_box td.LC_pick_box_title {
                   7503:   background: $tabbg;
                   7504:   font-weight: bold;
                   7505:   text-align: right;
                   7506:   width: 184px;
                   7507: }
1.795     www      7508: 
1.424     albertel 7509: table.LC_group_priv_box td.LC_groups_fixed {
                   7510:   background: $data_table_light;
                   7511:   text-align: center;
                   7512: }
1.795     www      7513: 
1.424     albertel 7514: table.LC_group_priv_box td.LC_groups_optional {
                   7515:   background: $data_table_dark;
                   7516:   text-align: center;
                   7517: }
1.795     www      7518: 
1.424     albertel 7519: table.LC_group_priv_box td.LC_groups_functionality {
                   7520:   background: $data_table_darker;
                   7521:   text-align: center;
                   7522:   font-weight: bold;
                   7523: }
1.795     www      7524: 
1.424     albertel 7525: table.LC_group_priv td {
                   7526:   text-align: left;
1.803     bisitz   7527:   padding: 0;
1.424     albertel 7528: }
                   7529: 
                   7530: .LC_navbuttons {
                   7531:   margin: 2ex 0ex 2ex 0ex;
                   7532: }
1.795     www      7533: 
1.423     albertel 7534: .LC_topic_bar {
                   7535:   font-weight: bold;
                   7536:   background: $tabbg;
1.918     wenzelju 7537:   margin: 1em 0em 1em 2em;
1.805     bisitz   7538:   padding: 3px;
1.918     wenzelju 7539:   font-size: 1.2em;
1.423     albertel 7540: }
1.795     www      7541: 
1.423     albertel 7542: .LC_topic_bar span {
1.918     wenzelju 7543:   left: 0.5em;
                   7544:   position: absolute;
1.423     albertel 7545:   vertical-align: middle;
1.918     wenzelju 7546:   font-size: 1.2em;
1.423     albertel 7547: }
1.795     www      7548: 
1.423     albertel 7549: table.LC_course_group_status {
                   7550:   margin: 20px;
                   7551: }
1.795     www      7552: 
1.423     albertel 7553: table.LC_status_selector td {
                   7554:   vertical-align: top;
                   7555:   text-align: center;
1.424     albertel 7556:   padding: 4px;
                   7557: }
1.795     www      7558: 
1.599     albertel 7559: div.LC_feedback_link {
1.616     albertel 7560:   clear: both;
1.829     kalberla 7561:   background: $sidebg;
1.779     bisitz   7562:   width: 100%;
1.829     kalberla 7563:   padding-bottom: 10px;
                   7564:   border: 1px $tabbg solid;
1.833     kalberla 7565:   height: 22px;
                   7566:   line-height: 22px;
                   7567:   padding-top: 5px;
                   7568: }
                   7569: 
                   7570: div.LC_feedback_link img {
                   7571:   height: 22px;
1.867     kalberla 7572:   vertical-align:middle;
1.829     kalberla 7573: }
                   7574: 
1.911     bisitz   7575: div.LC_feedback_link a {
1.829     kalberla 7576:   text-decoration: none;
1.489     raeburn  7577: }
1.795     www      7578: 
1.867     kalberla 7579: div.LC_comblock {
1.911     bisitz   7580:   display:inline;
1.867     kalberla 7581:   color:$font;
                   7582:   font-size:90%;
                   7583: }
                   7584: 
                   7585: div.LC_feedback_link div.LC_comblock {
                   7586:   padding-left:5px;
                   7587: }
                   7588: 
                   7589: div.LC_feedback_link div.LC_comblock a {
                   7590:   color:$font;
                   7591: }
                   7592: 
1.489     raeburn  7593: span.LC_feedback_link {
1.858     bisitz   7594:   /* background: $feedback_link_bg; */
1.599     albertel 7595:   font-size: larger;
                   7596: }
1.795     www      7597: 
1.599     albertel 7598: span.LC_message_link {
1.858     bisitz   7599:   /* background: $feedback_link_bg; */
1.599     albertel 7600:   font-size: larger;
                   7601:   position: absolute;
                   7602:   right: 1em;
1.489     raeburn  7603: }
1.421     albertel 7604: 
1.515     albertel 7605: table.LC_prior_tries {
1.524     albertel 7606:   border: 1px solid #000000;
                   7607:   border-collapse: separate;
                   7608:   border-spacing: 1px;
1.515     albertel 7609: }
1.523     albertel 7610: 
1.515     albertel 7611: table.LC_prior_tries td {
1.524     albertel 7612:   padding: 2px;
1.515     albertel 7613: }
1.523     albertel 7614: 
                   7615: .LC_answer_correct {
1.795     www      7616:   background: lightgreen;
                   7617:   color: darkgreen;
                   7618:   padding: 6px;
1.523     albertel 7619: }
1.795     www      7620: 
1.523     albertel 7621: .LC_answer_charged_try {
1.797     www      7622:   background: #FFAAAA;
1.795     www      7623:   color: darkred;
                   7624:   padding: 6px;
1.523     albertel 7625: }
1.795     www      7626: 
1.779     bisitz   7627: .LC_answer_not_charged_try,
1.523     albertel 7628: .LC_answer_no_grade,
                   7629: .LC_answer_late {
1.795     www      7630:   background: lightyellow;
1.523     albertel 7631:   color: black;
1.795     www      7632:   padding: 6px;
1.523     albertel 7633: }
1.795     www      7634: 
1.523     albertel 7635: .LC_answer_previous {
1.795     www      7636:   background: lightblue;
                   7637:   color: darkblue;
                   7638:   padding: 6px;
1.523     albertel 7639: }
1.795     www      7640: 
1.779     bisitz   7641: .LC_answer_no_message {
1.777     tempelho 7642:   background: #FFFFFF;
                   7643:   color: black;
1.795     www      7644:   padding: 6px;
1.779     bisitz   7645: }
1.795     www      7646: 
1.1334    raeburn  7647: .LC_answer_unknown,
                   7648: .LC_answer_warning {
1.779     bisitz   7649:   background: orange;
                   7650:   color: black;
1.795     www      7651:   padding: 6px;
1.777     tempelho 7652: }
1.795     www      7653: 
1.529     albertel 7654: span.LC_prior_numerical,
                   7655: span.LC_prior_string,
                   7656: span.LC_prior_custom,
                   7657: span.LC_prior_reaction,
                   7658: span.LC_prior_math {
1.925     bisitz   7659:   font-family: $mono;
1.523     albertel 7660:   white-space: pre;
                   7661: }
                   7662: 
1.525     albertel 7663: span.LC_prior_string {
1.925     bisitz   7664:   font-family: $mono;
1.525     albertel 7665:   white-space: pre;
                   7666: }
                   7667: 
1.523     albertel 7668: table.LC_prior_option {
                   7669:   width: 100%;
                   7670:   border-collapse: collapse;
                   7671: }
1.795     www      7672: 
1.911     bisitz   7673: table.LC_prior_rank,
1.795     www      7674: table.LC_prior_match {
1.528     albertel 7675:   border-collapse: collapse;
                   7676: }
1.795     www      7677: 
1.528     albertel 7678: table.LC_prior_option tr td,
                   7679: table.LC_prior_rank tr td,
                   7680: table.LC_prior_match tr td {
1.524     albertel 7681:   border: 1px solid #000000;
1.515     albertel 7682: }
                   7683: 
1.855     bisitz   7684: .LC_nobreak {
1.544     albertel 7685:   white-space: nowrap;
1.519     raeburn  7686: }
                   7687: 
1.576     raeburn  7688: span.LC_cusr_emph {
                   7689:   font-style: italic;
                   7690: }
                   7691: 
1.633     raeburn  7692: span.LC_cusr_subheading {
                   7693:   font-weight: normal;
                   7694:   font-size: 85%;
                   7695: }
                   7696: 
1.861     bisitz   7697: div.LC_docs_entry_move {
1.859     bisitz   7698:   border: 1px solid #BBBBBB;
1.545     albertel 7699:   background: #DDDDDD;
1.861     bisitz   7700:   width: 22px;
1.859     bisitz   7701:   padding: 1px;
                   7702:   margin: 0;
1.545     albertel 7703: }
                   7704: 
1.861     bisitz   7705: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7706: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7707:   font-size: x-small;
                   7708: }
1.795     www      7709: 
1.861     bisitz   7710: .LC_docs_entry_parameter {
                   7711:   white-space: nowrap;
                   7712: }
                   7713: 
1.544     albertel 7714: .LC_docs_copy {
1.545     albertel 7715:   color: #000099;
1.544     albertel 7716: }
1.795     www      7717: 
1.544     albertel 7718: .LC_docs_cut {
1.545     albertel 7719:   color: #550044;
1.544     albertel 7720: }
1.795     www      7721: 
1.544     albertel 7722: .LC_docs_rename {
1.545     albertel 7723:   color: #009900;
1.544     albertel 7724: }
1.795     www      7725: 
1.544     albertel 7726: .LC_docs_remove {
1.545     albertel 7727:   color: #990000;
                   7728: }
                   7729: 
1.1284    raeburn  7730: .LC_docs_alias {
                   7731:   color: #440055;  
                   7732: }
                   7733: 
1.1286    raeburn  7734: .LC_domprefs_email,
1.1284    raeburn  7735: .LC_docs_alias_name,
1.547     albertel 7736: .LC_docs_reinit_warn,
                   7737: .LC_docs_ext_edit {
                   7738:   font-size: x-small;
                   7739: }
                   7740: 
1.545     albertel 7741: table.LC_docs_adddocs td,
                   7742: table.LC_docs_adddocs th {
                   7743:   border: 1px solid #BBBBBB;
                   7744:   padding: 4px;
                   7745:   background: #DDDDDD;
1.543     albertel 7746: }
                   7747: 
1.584     albertel 7748: table.LC_sty_begin {
                   7749:   background: #BBFFBB;
                   7750: }
1.795     www      7751: 
1.584     albertel 7752: table.LC_sty_end {
                   7753:   background: #FFBBBB;
                   7754: }
                   7755: 
1.589     raeburn  7756: table.LC_double_column {
1.803     bisitz   7757:   border-width: 0;
1.589     raeburn  7758:   border-collapse: collapse;
                   7759:   width: 100%;
                   7760:   padding: 2px;
                   7761: }
                   7762: 
                   7763: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7764:   top: 2px;
1.589     raeburn  7765:   left: 2px;
                   7766:   width: 47%;
                   7767:   vertical-align: top;
                   7768: }
                   7769: 
                   7770: table.LC_double_column tr td.LC_right_col {
                   7771:   top: 2px;
1.779     bisitz   7772:   right: 2px;
1.589     raeburn  7773:   width: 47%;
                   7774:   vertical-align: top;
                   7775: }
                   7776: 
1.591     raeburn  7777: div.LC_left_float {
                   7778:   float: left;
                   7779:   padding-right: 5%;
1.597     albertel 7780:   padding-bottom: 4px;
1.591     raeburn  7781: }
                   7782: 
                   7783: div.LC_clear_float_header {
1.597     albertel 7784:   padding-bottom: 2px;
1.591     raeburn  7785: }
                   7786: 
                   7787: div.LC_clear_float_footer {
1.597     albertel 7788:   padding-top: 10px;
1.591     raeburn  7789:   clear: both;
                   7790: }
                   7791: 
1.597     albertel 7792: div.LC_grade_show_user {
1.941     bisitz   7793: /*  border-left: 5px solid $sidebg; */
                   7794:   border-top: 5px solid #000000;
                   7795:   margin: 50px 0 0 0;
1.936     bisitz   7796:   padding: 15px 0 5px 10px;
1.597     albertel 7797: }
1.795     www      7798: 
1.936     bisitz   7799: div.LC_grade_show_user_odd_row {
1.941     bisitz   7800: /*  border-left: 5px solid #000000; */
                   7801: }
                   7802: 
                   7803: div.LC_grade_show_user div.LC_Box {
                   7804:   margin-right: 50px;
1.597     albertel 7805: }
                   7806: 
                   7807: div.LC_grade_submissions,
                   7808: div.LC_grade_message_center,
1.936     bisitz   7809: div.LC_grade_info_links {
1.597     albertel 7810:   margin: 5px;
                   7811:   width: 99%;
                   7812:   background: #FFFFFF;
                   7813: }
1.795     www      7814: 
1.597     albertel 7815: div.LC_grade_submissions_header,
1.936     bisitz   7816: div.LC_grade_message_center_header {
1.705     tempelho 7817:   font-weight: bold;
                   7818:   font-size: large;
1.597     albertel 7819: }
1.795     www      7820: 
1.597     albertel 7821: div.LC_grade_submissions_body,
1.936     bisitz   7822: div.LC_grade_message_center_body {
1.597     albertel 7823:   border: 1px solid black;
                   7824:   width: 99%;
                   7825:   background: #FFFFFF;
                   7826: }
1.795     www      7827: 
1.613     albertel 7828: table.LC_scantron_action {
                   7829:   width: 100%;
                   7830: }
1.795     www      7831: 
1.613     albertel 7832: table.LC_scantron_action tr th {
1.698     harmsja  7833:   font-weight:bold;
                   7834:   font-style:normal;
1.613     albertel 7835: }
1.795     www      7836: 
1.779     bisitz   7837: .LC_edit_problem_header,
1.614     albertel 7838: div.LC_edit_problem_footer {
1.705     tempelho 7839:   font-weight: normal;
                   7840:   font-size:  medium;
1.602     albertel 7841:   margin: 2px;
1.1060    bisitz   7842:   background-color: $sidebg;
1.600     albertel 7843: }
1.795     www      7844: 
1.600     albertel 7845: div.LC_edit_problem_header,
1.602     albertel 7846: div.LC_edit_problem_header div,
1.614     albertel 7847: div.LC_edit_problem_footer,
                   7848: div.LC_edit_problem_footer div,
1.602     albertel 7849: div.LC_edit_problem_editxml_header,
                   7850: div.LC_edit_problem_editxml_header div {
1.1205    golterma 7851:   z-index: 100;
1.600     albertel 7852: }
1.795     www      7853: 
1.600     albertel 7854: div.LC_edit_problem_header_title {
1.705     tempelho 7855:   font-weight: bold;
                   7856:   font-size: larger;
1.602     albertel 7857:   background: $tabbg;
                   7858:   padding: 3px;
1.1060    bisitz   7859:   margin: 0 0 5px 0;
1.602     albertel 7860: }
1.795     www      7861: 
1.602     albertel 7862: table.LC_edit_problem_header_title {
                   7863:   width: 100%;
1.600     albertel 7864:   background: $tabbg;
1.602     albertel 7865: }
                   7866: 
1.1205    golterma 7867: div.LC_edit_actionbar {
                   7868:     background-color: $sidebg;
1.1218    droeschl 7869:     margin: 0;
                   7870:     padding: 0;
                   7871:     line-height: 200%;
1.602     albertel 7872: }
1.795     www      7873: 
1.1218    droeschl 7874: div.LC_edit_actionbar div{
                   7875:     padding: 0;
                   7876:     margin: 0;
                   7877:     display: inline-block;
1.600     albertel 7878: }
1.795     www      7879: 
1.1124    bisitz   7880: .LC_edit_opt {
                   7881:   padding-left: 1em;
                   7882:   white-space: nowrap;
                   7883: }
                   7884: 
1.1152    golterma 7885: .LC_edit_problem_latexhelper{
                   7886:     text-align: right;
                   7887: }
                   7888: 
                   7889: #LC_edit_problem_colorful div{
                   7890:     margin-left: 40px;
                   7891: }
                   7892: 
1.1205    golterma 7893: #LC_edit_problem_codemirror div{
                   7894:     margin-left: 0px;
                   7895: }
                   7896: 
1.911     bisitz   7897: img.stift {
1.803     bisitz   7898:   border-width: 0;
                   7899:   vertical-align: middle;
1.677     riegler  7900: }
1.680     riegler  7901: 
1.923     bisitz   7902: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7903:   vertical-align: top;
1.777     tempelho 7904: }
1.795     www      7905: 
1.716     raeburn  7906: div.LC_createcourse {
1.911     bisitz   7907:   margin: 10px 10px 10px 10px;
1.716     raeburn  7908: }
                   7909: 
1.917     raeburn  7910: .LC_dccid {
1.1130    raeburn  7911:   float: right;
1.917     raeburn  7912:   margin: 0.2em 0 0 0;
                   7913:   padding: 0;
                   7914:   font-size: 90%;
                   7915:   display:none;
                   7916: }
                   7917: 
1.897     wenzelju 7918: ol.LC_primary_menu a:hover,
1.721     harmsja  7919: ol#LC_MenuBreadcrumbs a:hover,
                   7920: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7921: ul#LC_secondary_menu a:hover,
1.721     harmsja  7922: .LC_FormSectionClearButton input:hover
1.795     www      7923: ul.LC_TabContent   li:hover a {
1.952     onken    7924:   color:$button_hover;
1.911     bisitz   7925:   text-decoration:none;
1.693     droeschl 7926: }
                   7927: 
1.779     bisitz   7928: h1 {
1.911     bisitz   7929:   padding: 0;
                   7930:   line-height:130%;
1.693     droeschl 7931: }
1.698     harmsja  7932: 
1.911     bisitz   7933: h2,
                   7934: h3,
                   7935: h4,
                   7936: h5,
                   7937: h6 {
                   7938:   margin: 5px 0 5px 0;
                   7939:   padding: 0;
                   7940:   line-height:130%;
1.693     droeschl 7941: }
1.795     www      7942: 
                   7943: .LC_hcell {
1.911     bisitz   7944:   padding:3px 15px 3px 15px;
                   7945:   margin: 0;
                   7946:   background-color:$tabbg;
                   7947:   color:$fontmenu;
                   7948:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7949: }
1.795     www      7950: 
1.840     bisitz   7951: .LC_Box > .LC_hcell {
1.911     bisitz   7952:   margin: 0 -10px 10px -10px;
1.835     bisitz   7953: }
                   7954: 
1.721     harmsja  7955: .LC_noBorder {
1.911     bisitz   7956:   border: 0;
1.698     harmsja  7957: }
1.693     droeschl 7958: 
1.721     harmsja  7959: .LC_FormSectionClearButton input {
1.911     bisitz   7960:   background-color:transparent;
                   7961:   border: none;
                   7962:   cursor:pointer;
                   7963:   text-decoration:underline;
1.693     droeschl 7964: }
1.763     bisitz   7965: 
                   7966: .LC_help_open_topic {
1.911     bisitz   7967:   color: #FFFFFF;
                   7968:   background-color: #EEEEFF;
                   7969:   margin: 1px;
                   7970:   padding: 4px;
                   7971:   border: 1px solid #000033;
                   7972:   white-space: nowrap;
                   7973:   /* vertical-align: middle; */
1.759     neumanie 7974: }
1.693     droeschl 7975: 
1.911     bisitz   7976: dl,
                   7977: ul,
                   7978: div,
                   7979: fieldset {
                   7980:   margin: 10px 10px 10px 0;
                   7981:   /* overflow: hidden; */
1.693     droeschl 7982: }
1.795     www      7983: 
1.1211    raeburn  7984: article.geogebraweb div {
                   7985:     margin: 0;
                   7986: }
                   7987: 
1.838     bisitz   7988: fieldset > legend {
1.911     bisitz   7989:   font-weight: bold;
                   7990:   padding: 0 5px 0 5px;
1.838     bisitz   7991: }
                   7992: 
1.813     bisitz   7993: #LC_nav_bar {
1.911     bisitz   7994:   float: left;
1.995     raeburn  7995:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7996:   margin: 0 0 2px 0;
1.807     droeschl 7997: }
                   7998: 
1.916     droeschl 7999: #LC_realm {
                   8000:   margin: 0.2em 0 0 0;
                   8001:   padding: 0;
                   8002:   font-weight: bold;
                   8003:   text-align: center;
1.995     raeburn  8004:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8005: }
                   8006: 
1.911     bisitz   8007: #LC_nav_bar em {
                   8008:   font-weight: bold;
                   8009:   font-style: normal;
1.807     droeschl 8010: }
                   8011: 
1.897     wenzelju 8012: ol.LC_primary_menu {
1.934     droeschl 8013:   margin: 0;
1.1076    raeburn  8014:   padding: 0;
1.807     droeschl 8015: }
                   8016: 
1.852     droeschl 8017: ol#LC_PathBreadcrumbs {
1.911     bisitz   8018:   margin: 0;
1.693     droeschl 8019: }
                   8020: 
1.897     wenzelju 8021: ol.LC_primary_menu li {
1.1076    raeburn  8022:   color: RGB(80, 80, 80);
                   8023:   vertical-align: middle;
                   8024:   text-align: left;
                   8025:   list-style: none;
1.1205    golterma 8026:   position: relative;
1.1076    raeburn  8027:   float: left;
1.1205    golterma 8028:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8029:   line-height: 1.5em;
1.1076    raeburn  8030: }
                   8031: 
1.1205    golterma 8032: ol.LC_primary_menu li a,
                   8033: ol.LC_primary_menu li p {
1.1076    raeburn  8034:   display: block;
                   8035:   margin: 0;
                   8036:   padding: 0 5px 0 10px;
                   8037:   text-decoration: none;
                   8038: }
                   8039: 
1.1205    golterma 8040: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8041:   display: inline-block;
                   8042:   width: 95%;
                   8043:   text-align: left;
                   8044: }
                   8045: 
                   8046: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8047:   display: inline-block;	
                   8048:   width: 5%;
                   8049:   float: right;
                   8050:   text-align: right;
                   8051:   font-size: 70%;
                   8052: }
                   8053: 
                   8054: ol.LC_primary_menu ul {
1.1076    raeburn  8055:   display: none;
1.1205    golterma 8056:   width: 15em;
1.1076    raeburn  8057:   background-color: $data_table_light;
1.1205    golterma 8058:   position: absolute;
                   8059:   top: 100%;
1.1076    raeburn  8060: }
                   8061: 
1.1205    golterma 8062: ol.LC_primary_menu ul ul {
                   8063:   left: 100%;
                   8064:   top: 0;
                   8065: }
                   8066: 
                   8067: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8068:   display: block;
                   8069:   position: absolute;
                   8070:   margin: 0;
                   8071:   padding: 0;
1.1078    raeburn  8072:   z-index: 2;
1.1076    raeburn  8073: }
                   8074: 
                   8075: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8076: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8077:   font-size: 90%;
1.911     bisitz   8078:   vertical-align: top;
1.1076    raeburn  8079:   float: none;
1.1079    raeburn  8080:   border-left: 1px solid black;
                   8081:   border-right: 1px solid black;
1.1205    golterma 8082: /* A dark bottom border to visualize different menu options; 
                   8083: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8084:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8085: }
                   8086: 
1.1205    golterma 8087: ol.LC_primary_menu li li p:hover {
                   8088:   color:$button_hover;
                   8089:   text-decoration:none;
                   8090:   background-color:$data_table_dark;
1.1076    raeburn  8091: }
                   8092: 
                   8093: ol.LC_primary_menu li li a:hover {
                   8094:    color:$button_hover;
                   8095:    background-color:$data_table_dark;
1.693     droeschl 8096: }
                   8097: 
1.1205    golterma 8098: /* Font-size equal to the size of the predecessors*/
                   8099: ol.LC_primary_menu li:hover li li {
                   8100:   font-size: 100%;
                   8101: }
                   8102: 
1.897     wenzelju 8103: ol.LC_primary_menu li img {
1.911     bisitz   8104:   vertical-align: bottom;
1.934     droeschl 8105:   height: 1.1em;
1.1077    raeburn  8106:   margin: 0.2em 0 0 0;
1.693     droeschl 8107: }
                   8108: 
1.897     wenzelju 8109: ol.LC_primary_menu a {
1.911     bisitz   8110:   color: RGB(80, 80, 80);
                   8111:   text-decoration: none;
1.693     droeschl 8112: }
1.795     www      8113: 
1.949     droeschl 8114: ol.LC_primary_menu a.LC_new_message {
                   8115:   font-weight:bold;
                   8116:   color: darkred;
                   8117: }
                   8118: 
1.975     raeburn  8119: ol.LC_docs_parameters {
                   8120:   margin-left: 0;
                   8121:   padding: 0;
                   8122:   list-style: none;
                   8123: }
                   8124: 
                   8125: ol.LC_docs_parameters li {
                   8126:   margin: 0;
                   8127:   padding-right: 20px;
                   8128:   display: inline;
                   8129: }
                   8130: 
1.976     raeburn  8131: ol.LC_docs_parameters li:before {
                   8132:   content: "\\002022 \\0020";
                   8133: }
                   8134: 
                   8135: li.LC_docs_parameters_title {
                   8136:   font-weight: bold;
                   8137: }
                   8138: 
                   8139: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8140:   content: "";
                   8141: }
                   8142: 
1.897     wenzelju 8143: ul#LC_secondary_menu {
1.1107    raeburn  8144:   clear: right;
1.911     bisitz   8145:   color: $fontmenu;
                   8146:   background: $tabbg;
                   8147:   list-style: none;
                   8148:   padding: 0;
                   8149:   margin: 0;
                   8150:   width: 100%;
1.995     raeburn  8151:   text-align: left;
1.1107    raeburn  8152:   float: left;
1.808     droeschl 8153: }
                   8154: 
1.897     wenzelju 8155: ul#LC_secondary_menu li {
1.911     bisitz   8156:   font-weight: bold;
                   8157:   line-height: 1.8em;
1.1107    raeburn  8158:   border-right: 1px solid black;
                   8159:   float: left;
                   8160: }
                   8161: 
                   8162: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8163:   background-color: $data_table_light;
                   8164: }
                   8165: 
                   8166: ul#LC_secondary_menu li a {
1.911     bisitz   8167:   padding: 0 0.8em;
1.1107    raeburn  8168: }
                   8169: 
                   8170: ul#LC_secondary_menu li ul {
                   8171:   display: none;
                   8172: }
                   8173: 
                   8174: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8175:   display: block;
                   8176:   position: absolute;
                   8177:   margin: 0;
                   8178:   padding: 0;
                   8179:   list-style:none;
                   8180:   float: none;
                   8181:   background-color: $data_table_light;
                   8182:   z-index: 2;
                   8183:   margin-left: -1px;
                   8184: }
                   8185: 
                   8186: ul#LC_secondary_menu li ul li {
                   8187:   font-size: 90%;
                   8188:   vertical-align: top;
                   8189:   border-left: 1px solid black;
1.911     bisitz   8190:   border-right: 1px solid black;
1.1119    raeburn  8191:   background-color: $data_table_light;
1.1107    raeburn  8192:   list-style:none;
                   8193:   float: none;
                   8194: }
                   8195: 
                   8196: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8197:   background-color: $data_table_dark;
1.807     droeschl 8198: }
                   8199: 
1.847     tempelho 8200: ul.LC_TabContent {
1.911     bisitz   8201:   display:block;
                   8202:   background: $sidebg;
                   8203:   border-bottom: solid 1px $lg_border_color;
                   8204:   list-style:none;
1.1020    raeburn  8205:   margin: -1px -10px 0 -10px;
1.911     bisitz   8206:   padding: 0;
1.693     droeschl 8207: }
                   8208: 
1.795     www      8209: ul.LC_TabContent li,
                   8210: ul.LC_TabContentBigger li {
1.911     bisitz   8211:   float:left;
1.741     harmsja  8212: }
1.795     www      8213: 
1.897     wenzelju 8214: ul#LC_secondary_menu li a {
1.911     bisitz   8215:   color: $fontmenu;
                   8216:   text-decoration: none;
1.693     droeschl 8217: }
1.795     www      8218: 
1.721     harmsja  8219: ul.LC_TabContent {
1.952     onken    8220:   min-height:20px;
1.721     harmsja  8221: }
1.795     www      8222: 
                   8223: ul.LC_TabContent li {
1.911     bisitz   8224:   vertical-align:middle;
1.959     onken    8225:   padding: 0 16px 0 10px;
1.911     bisitz   8226:   background-color:$tabbg;
                   8227:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8228:   border-left: solid 1px $font;
1.721     harmsja  8229: }
1.795     www      8230: 
1.847     tempelho 8231: ul.LC_TabContent .right {
1.911     bisitz   8232:   float:right;
1.847     tempelho 8233: }
                   8234: 
1.911     bisitz   8235: ul.LC_TabContent li a,
                   8236: ul.LC_TabContent li {
                   8237:   color:rgb(47,47,47);
                   8238:   text-decoration:none;
                   8239:   font-size:95%;
                   8240:   font-weight:bold;
1.952     onken    8241:   min-height:20px;
                   8242: }
                   8243: 
1.959     onken    8244: ul.LC_TabContent li a:hover,
                   8245: ul.LC_TabContent li a:focus {
1.952     onken    8246:   color: $button_hover;
1.959     onken    8247:   background:none;
                   8248:   outline:none;
1.952     onken    8249: }
                   8250: 
                   8251: ul.LC_TabContent li:hover {
                   8252:   color: $button_hover;
                   8253:   cursor:pointer;
1.721     harmsja  8254: }
1.795     www      8255: 
1.911     bisitz   8256: ul.LC_TabContent li.active {
1.952     onken    8257:   color: $font;
1.911     bisitz   8258:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8259:   border-bottom:solid 1px #FFFFFF;
                   8260:   cursor: default;
1.744     ehlerst  8261: }
1.795     www      8262: 
1.959     onken    8263: ul.LC_TabContent li.active a {
                   8264:   color:$font;
                   8265:   background:#FFFFFF;
                   8266:   outline: none;
                   8267: }
1.1047    raeburn  8268: 
                   8269: ul.LC_TabContent li.goback {
                   8270:   float: left;
                   8271:   border-left: none;
                   8272: }
                   8273: 
1.870     tempelho 8274: #maincoursedoc {
1.911     bisitz   8275:   clear:both;
1.870     tempelho 8276: }
                   8277: 
                   8278: ul.LC_TabContentBigger {
1.911     bisitz   8279:   display:block;
                   8280:   list-style:none;
                   8281:   padding: 0;
1.870     tempelho 8282: }
                   8283: 
1.795     www      8284: ul.LC_TabContentBigger li {
1.911     bisitz   8285:   vertical-align:bottom;
                   8286:   height: 30px;
                   8287:   font-size:110%;
                   8288:   font-weight:bold;
                   8289:   color: #737373;
1.841     tempelho 8290: }
                   8291: 
1.957     onken    8292: ul.LC_TabContentBigger li.active {
                   8293:   position: relative;
                   8294:   top: 1px;
                   8295: }
                   8296: 
1.870     tempelho 8297: ul.LC_TabContentBigger li a {
1.911     bisitz   8298:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8299:   height: 30px;
                   8300:   line-height: 30px;
                   8301:   text-align: center;
                   8302:   display: block;
                   8303:   text-decoration: none;
1.958     onken    8304:   outline: none;  
1.741     harmsja  8305: }
1.795     www      8306: 
1.870     tempelho 8307: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8308:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8309:   color:$font;
1.744     ehlerst  8310: }
1.795     www      8311: 
1.870     tempelho 8312: ul.LC_TabContentBigger li b {
1.911     bisitz   8313:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8314:   display: block;
                   8315:   float: left;
                   8316:   padding: 0 30px;
1.957     onken    8317:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8318: }
                   8319: 
1.956     onken    8320: ul.LC_TabContentBigger li:hover b {
                   8321:   color:$button_hover;
                   8322: }
                   8323: 
1.870     tempelho 8324: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8325:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8326:   color:$font;
1.957     onken    8327:   border: 0;
1.741     harmsja  8328: }
1.693     droeschl 8329: 
1.870     tempelho 8330: 
1.862     bisitz   8331: ul.LC_CourseBreadcrumbs {
                   8332:   background: $sidebg;
1.1020    raeburn  8333:   height: 2em;
1.862     bisitz   8334:   padding-left: 10px;
1.1020    raeburn  8335:   margin: 0;
1.862     bisitz   8336:   list-style-position: inside;
                   8337: }
                   8338: 
1.911     bisitz   8339: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8340: ol#LC_PathBreadcrumbs {
1.911     bisitz   8341:   padding-left: 10px;
                   8342:   margin: 0;
1.933     droeschl 8343:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8344: }
                   8345: 
1.911     bisitz   8346: ol#LC_MenuBreadcrumbs li,
                   8347: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8348: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8349:   display: inline;
1.933     droeschl 8350:   white-space: normal;  
1.693     droeschl 8351: }
                   8352: 
1.823     bisitz   8353: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8354: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8355:   text-decoration: none;
                   8356:   font-size:90%;
1.693     droeschl 8357: }
1.795     www      8358: 
1.969     droeschl 8359: ol#LC_MenuBreadcrumbs h1 {
                   8360:   display: inline;
                   8361:   font-size: 90%;
                   8362:   line-height: 2.5em;
                   8363:   margin: 0;
                   8364:   padding: 0;
                   8365: }
                   8366: 
1.795     www      8367: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8368:   text-decoration:none;
                   8369:   font-size:100%;
                   8370:   font-weight:bold;
1.693     droeschl 8371: }
1.795     www      8372: 
1.840     bisitz   8373: .LC_Box {
1.911     bisitz   8374:   border: solid 1px $lg_border_color;
                   8375:   padding: 0 10px 10px 10px;
1.746     neumanie 8376: }
1.795     www      8377: 
1.1020    raeburn  8378: .LC_DocsBox {
                   8379:   border: solid 1px $lg_border_color;
                   8380:   padding: 0 0 10px 10px;
                   8381: }
                   8382: 
1.795     www      8383: .LC_AboutMe_Image {
1.911     bisitz   8384:   float:left;
                   8385:   margin-right:10px;
1.747     neumanie 8386: }
1.795     www      8387: 
                   8388: .LC_Clear_AboutMe_Image {
1.911     bisitz   8389:   clear:left;
1.747     neumanie 8390: }
1.795     www      8391: 
1.721     harmsja  8392: dl.LC_ListStyleClean dt {
1.911     bisitz   8393:   padding-right: 5px;
                   8394:   display: table-header-group;
1.693     droeschl 8395: }
                   8396: 
1.721     harmsja  8397: dl.LC_ListStyleClean dd {
1.911     bisitz   8398:   display: table-row;
1.693     droeschl 8399: }
                   8400: 
1.721     harmsja  8401: .LC_ListStyleClean,
                   8402: .LC_ListStyleSimple,
                   8403: .LC_ListStyleNormal,
1.795     www      8404: .LC_ListStyleSpecial {
1.911     bisitz   8405:   /* display:block; */
                   8406:   list-style-position: inside;
                   8407:   list-style-type: none;
                   8408:   overflow: hidden;
                   8409:   padding: 0;
1.693     droeschl 8410: }
                   8411: 
1.721     harmsja  8412: .LC_ListStyleSimple li,
                   8413: .LC_ListStyleSimple dd,
                   8414: .LC_ListStyleNormal li,
                   8415: .LC_ListStyleNormal dd,
                   8416: .LC_ListStyleSpecial li,
1.795     www      8417: .LC_ListStyleSpecial dd {
1.911     bisitz   8418:   margin: 0;
                   8419:   padding: 5px 5px 5px 10px;
                   8420:   clear: both;
1.693     droeschl 8421: }
                   8422: 
1.721     harmsja  8423: .LC_ListStyleClean li,
                   8424: .LC_ListStyleClean dd {
1.911     bisitz   8425:   padding-top: 0;
                   8426:   padding-bottom: 0;
1.693     droeschl 8427: }
                   8428: 
1.721     harmsja  8429: .LC_ListStyleSimple dd,
1.795     www      8430: .LC_ListStyleSimple li {
1.911     bisitz   8431:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8432: }
                   8433: 
1.721     harmsja  8434: .LC_ListStyleSpecial li,
                   8435: .LC_ListStyleSpecial dd {
1.911     bisitz   8436:   list-style-type: none;
                   8437:   background-color: RGB(220, 220, 220);
                   8438:   margin-bottom: 4px;
1.693     droeschl 8439: }
                   8440: 
1.721     harmsja  8441: table.LC_SimpleTable {
1.911     bisitz   8442:   margin:5px;
                   8443:   border:solid 1px $lg_border_color;
1.795     www      8444: }
1.693     droeschl 8445: 
1.721     harmsja  8446: table.LC_SimpleTable tr {
1.911     bisitz   8447:   padding: 0;
                   8448:   border:solid 1px $lg_border_color;
1.693     droeschl 8449: }
1.795     www      8450: 
                   8451: table.LC_SimpleTable thead {
1.911     bisitz   8452:   background:rgb(220,220,220);
1.693     droeschl 8453: }
                   8454: 
1.721     harmsja  8455: div.LC_columnSection {
1.911     bisitz   8456:   display: block;
                   8457:   clear: both;
                   8458:   overflow: hidden;
                   8459:   margin: 0;
1.693     droeschl 8460: }
                   8461: 
1.721     harmsja  8462: div.LC_columnSection>* {
1.911     bisitz   8463:   float: left;
                   8464:   margin: 10px 20px 10px 0;
                   8465:   overflow:hidden;
1.693     droeschl 8466: }
1.721     harmsja  8467: 
1.795     www      8468: table em {
1.911     bisitz   8469:   font-weight: bold;
                   8470:   font-style: normal;
1.748     schulted 8471: }
1.795     www      8472: 
1.779     bisitz   8473: table.LC_tableBrowseRes,
1.795     www      8474: table.LC_tableOfContent {
1.911     bisitz   8475:   border:none;
                   8476:   border-spacing: 1px;
                   8477:   padding: 3px;
                   8478:   background-color: #FFFFFF;
                   8479:   font-size: 90%;
1.753     droeschl 8480: }
1.789     droeschl 8481: 
1.911     bisitz   8482: table.LC_tableOfContent {
                   8483:   border-collapse: collapse;
1.789     droeschl 8484: }
                   8485: 
1.771     droeschl 8486: table.LC_tableBrowseRes a,
1.768     schulted 8487: table.LC_tableOfContent a {
1.911     bisitz   8488:   background-color: transparent;
                   8489:   text-decoration: none;
1.753     droeschl 8490: }
                   8491: 
1.795     www      8492: table.LC_tableOfContent img {
1.911     bisitz   8493:   border: none;
                   8494:   height: 1.3em;
                   8495:   vertical-align: text-bottom;
                   8496:   margin-right: 0.3em;
1.753     droeschl 8497: }
1.757     schulted 8498: 
1.795     www      8499: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8500:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8501: }
                   8502: 
1.795     www      8503: a#LC_content_toolbar_everything {
1.911     bisitz   8504:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8505: }
                   8506: 
1.795     www      8507: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8508:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8509: }
                   8510: 
1.795     www      8511: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8512:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8513: }
                   8514: 
1.795     www      8515: a#LC_content_toolbar_changefolder {
1.911     bisitz   8516:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8517: }
                   8518: 
1.795     www      8519: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8520:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8521: }
                   8522: 
1.1043    raeburn  8523: a#LC_content_toolbar_edittoplevel {
                   8524:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8525: }
                   8526: 
1.1384  ! raeburn  8527: a#LC_content_toolbar_printout {
        !          8528:   background-image:url(/res/adm/pages/printout.gif);
        !          8529: }
        !          8530: 
1.795     www      8531: ul#LC_toolbar li a:hover {
1.911     bisitz   8532:   background-position: bottom center;
1.757     schulted 8533: }
                   8534: 
1.795     www      8535: ul#LC_toolbar {
1.911     bisitz   8536:   padding: 0;
                   8537:   margin: 2px;
                   8538:   list-style:none;
                   8539:   position:relative;
                   8540:   background-color:white;
1.1082    raeburn  8541:   overflow: auto;
1.757     schulted 8542: }
                   8543: 
1.795     www      8544: ul#LC_toolbar li {
1.911     bisitz   8545:   border:1px solid white;
                   8546:   padding: 0;
                   8547:   margin: 0;
                   8548:   float: left;
                   8549:   display:inline;
                   8550:   vertical-align:middle;
1.1082    raeburn  8551:   white-space: nowrap;
1.911     bisitz   8552: }
1.757     schulted 8553: 
1.783     amueller 8554: 
1.795     www      8555: a.LC_toolbarItem {
1.911     bisitz   8556:   display:block;
                   8557:   padding: 0;
                   8558:   margin: 0;
                   8559:   height: 32px;
                   8560:   width: 32px;
                   8561:   color:white;
                   8562:   border: none;
                   8563:   background-repeat:no-repeat;
                   8564:   background-color:transparent;
1.757     schulted 8565: }
                   8566: 
1.915     droeschl 8567: ul.LC_funclist {
                   8568:     margin: 0;
                   8569:     padding: 0.5em 1em 0.5em 0;
                   8570: }
                   8571: 
1.933     droeschl 8572: ul.LC_funclist > li:first-child {
                   8573:     font-weight:bold; 
                   8574:     margin-left:0.8em;
                   8575: }
                   8576: 
1.915     droeschl 8577: ul.LC_funclist + ul.LC_funclist {
                   8578:     /* 
                   8579:        left border as a seperator if we have more than
                   8580:        one list 
                   8581:     */
                   8582:     border-left: 1px solid $sidebg;
                   8583:     /* 
                   8584:        this hides the left border behind the border of the 
                   8585:        outer box if element is wrapped to the next 'line' 
                   8586:     */
                   8587:     margin-left: -1px;
                   8588: }
                   8589: 
1.843     bisitz   8590: ul.LC_funclist li {
1.915     droeschl 8591:   display: inline;
1.782     bisitz   8592:   white-space: nowrap;
1.915     droeschl 8593:   margin: 0 0 0 25px;
                   8594:   line-height: 150%;
1.782     bisitz   8595: }
                   8596: 
1.974     wenzelju 8597: .LC_hidden {
                   8598:   display: none;
                   8599: }
                   8600: 
1.1030    www      8601: .LCmodal-overlay {
                   8602: 		position:fixed;
                   8603: 		top:0;
                   8604: 		right:0;
                   8605: 		bottom:0;
                   8606: 		left:0;
                   8607: 		height:100%;
                   8608: 		width:100%;
                   8609: 		margin:0;
                   8610: 		padding:0;
                   8611: 		background:#999;
                   8612: 		opacity:.75;
                   8613: 		filter: alpha(opacity=75);
                   8614: 		-moz-opacity: 0.75;
                   8615: 		z-index:101;
                   8616: }
                   8617: 
                   8618: * html .LCmodal-overlay {   
                   8619: 		position: absolute;
                   8620: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8621: }
                   8622: 
                   8623: .LCmodal-window {
                   8624: 		position:fixed;
                   8625: 		top:50%;
                   8626: 		left:50%;
                   8627: 		margin:0;
                   8628: 		padding:0;
                   8629: 		z-index:102;
                   8630: 	}
                   8631: 
                   8632: * html .LCmodal-window {
                   8633: 		position:absolute;
                   8634: }
                   8635: 
                   8636: .LCclose-window {
                   8637: 		position:absolute;
                   8638: 		width:32px;
                   8639: 		height:32px;
                   8640: 		right:8px;
                   8641: 		top:8px;
                   8642: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8643: 		text-indent:-99999px;
                   8644: 		overflow:hidden;
                   8645: 		cursor:pointer;
                   8646: }
                   8647: 
1.1369    raeburn  8648: .LCisDisabled {
                   8649:   cursor: not-allowed;
                   8650:   opacity: 0.5;
                   8651: }
                   8652: 
                   8653: a[aria-disabled="true"] {
                   8654:   color: currentColor;
                   8655:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8656:   pointer-events: none;
                   8657:   text-decoration: none;
                   8658: }
                   8659: 
1.1335    raeburn  8660: pre.LC_wordwrap {
                   8661:   white-space: pre-wrap;
                   8662:   white-space: -moz-pre-wrap;
                   8663:   white-space: -pre-wrap;
                   8664:   white-space: -o-pre-wrap;
                   8665:   word-wrap: break-word;
                   8666: }
                   8667: 
1.1100    raeburn  8668: /*
1.1231    damieng  8669:   styles used for response display
                   8670: */
                   8671: div.LC_radiofoil, div.LC_rankfoil {
                   8672:   margin: .5em 0em .5em 0em;
                   8673: }
                   8674: table.LC_itemgroup {
                   8675:   margin-top: 1em;
                   8676: }
                   8677: 
                   8678: /*
1.1100    raeburn  8679:   styles used by TTH when "Default set of options to pass to tth/m
                   8680:   when converting TeX" in course settings has been set
                   8681: 
                   8682:   option passed: -t
                   8683: 
                   8684: */
                   8685: 
                   8686: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8687: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8688: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8689: td div.norm {line-height:normal;}
                   8690: 
                   8691: /*
                   8692:   option passed -y3
                   8693: */
                   8694: 
                   8695: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8696: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8697: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8698: 
1.1230    damieng  8699: /*
                   8700:   sections with roles, for content only
                   8701: */
                   8702: section[class^="role-"] {
                   8703:   padding-left: 10px;
                   8704:   padding-right: 5px;
                   8705:   margin-top: 8px;
                   8706:   margin-bottom: 8px;
                   8707:   border: 1px solid #2A4;
                   8708:   border-radius: 5px;
                   8709:   box-shadow: 0px 1px 1px #BBB;
                   8710: }
                   8711: section[class^="role-"]>h1 {
                   8712:   position: relative;
                   8713:   margin: 0px;
                   8714:   padding-top: 10px;
                   8715:   padding-left: 40px;
                   8716: }
                   8717: section[class^="role-"]>h1:before {
                   8718:   position: absolute;
                   8719:   left: -5px;
                   8720:   top: 5px;
                   8721: }
                   8722: section.role-activity>h1:before {
                   8723:   content:url('/adm/daxe/images/section_icons/activity.png');
                   8724: }
                   8725: section.role-advice>h1:before {
                   8726:   content:url('/adm/daxe/images/section_icons/advice.png');
                   8727: }
                   8728: section.role-bibliography>h1:before {
                   8729:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   8730: }
                   8731: section.role-citation>h1:before {
                   8732:   content:url('/adm/daxe/images/section_icons/citation.png');
                   8733: }
                   8734: section.role-conclusion>h1:before {
                   8735:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   8736: }
                   8737: section.role-definition>h1:before {
                   8738:   content:url('/adm/daxe/images/section_icons/definition.png');
                   8739: }
                   8740: section.role-demonstration>h1:before {
                   8741:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   8742: }
                   8743: section.role-example>h1:before {
                   8744:   content:url('/adm/daxe/images/section_icons/example.png');
                   8745: }
                   8746: section.role-explanation>h1:before {
                   8747:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   8748: }
                   8749: section.role-introduction>h1:before {
                   8750:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   8751: }
                   8752: section.role-method>h1:before {
                   8753:   content:url('/adm/daxe/images/section_icons/method.png');
                   8754: }
                   8755: section.role-more_information>h1:before {
                   8756:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   8757: }
                   8758: section.role-objectives>h1:before {
                   8759:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   8760: }
                   8761: section.role-prerequisites>h1:before {
                   8762:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   8763: }
                   8764: section.role-remark>h1:before {
                   8765:   content:url('/adm/daxe/images/section_icons/remark.png');
                   8766: }
                   8767: section.role-reminder>h1:before {
                   8768:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   8769: }
                   8770: section.role-summary>h1:before {
                   8771:   content:url('/adm/daxe/images/section_icons/summary.png');
                   8772: }
                   8773: section.role-syntax>h1:before {
                   8774:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   8775: }
                   8776: section.role-warning>h1:before {
                   8777:   content:url('/adm/daxe/images/section_icons/warning.png');
                   8778: }
                   8779: 
1.1269    raeburn  8780: #LC_minitab_header {
                   8781:   float:left;
                   8782:   width:100%;
                   8783:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8784:   font-size:93%;
                   8785:   line-height:normal;
                   8786:   margin: 0.5em 0 0.5em 0;
                   8787: }
                   8788: #LC_minitab_header ul {
                   8789:   margin:0;
                   8790:   padding:10px 10px 0;
                   8791:   list-style:none;
                   8792: }
                   8793: #LC_minitab_header li {
                   8794:   float:left;
                   8795:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8796:   margin:0;
                   8797:   padding:0 0 0 9px;
                   8798: }
                   8799: #LC_minitab_header a {
                   8800:   display:block;
                   8801:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8802:   padding:5px 15px 4px 6px;
                   8803: }
                   8804: #LC_minitab_header #LC_current_minitab {
                   8805:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8806: }
                   8807: #LC_minitab_header #LC_current_minitab a {
                   8808:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8809:   padding-bottom:5px;
                   8810: }
                   8811: 
                   8812: 
1.343     albertel 8813: END
                   8814: }
                   8815: 
1.306     albertel 8816: =pod
                   8817: 
                   8818: =item * &headtag()
                   8819: 
                   8820: Returns a uniform footer for LON-CAPA web pages.
                   8821: 
1.307     albertel 8822: Inputs: $title - optional title for the head
                   8823:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8824:         $args - optional arguments
1.319     albertel 8825:             force_register - if is true call registerurl so the remote is 
                   8826:                              informed
1.415     albertel 8827:             redirect       -> array ref of
                   8828:                                    1- seconds before redirect occurs
                   8829:                                    2- url to redirect to
                   8830:                                    3- whether the side effect should occur
1.315     albertel 8831:                            (side effect of setting 
                   8832:                                $env{'internal.head.redirect'} to the url 
                   8833:                                redirected too)
1.352     albertel 8834:             domain         -> force to color decorate a page for a specific
                   8835:                                domain
                   8836:             function       -> force usage of a specific rolish color scheme
                   8837:             bgcolor        -> override the default page bgcolor
1.460     albertel 8838:             no_auto_mt_title
                   8839:                            -> prevent &mt()ing the title arg
1.464     albertel 8840: 
1.306     albertel 8841: =cut
                   8842: 
                   8843: sub headtag {
1.313     albertel 8844:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8845:     
1.363     albertel 8846:     my $function = $args->{'function'} || &get_users_function();
                   8847:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8848:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  8849:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8850:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8851: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8852: 		   #time(),
1.418     albertel 8853: 		   $env{'environment.color.timestamp'},
1.363     albertel 8854: 		   $function,$domain,$bgcolor);
                   8855: 
1.369     www      8856:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8857: 
1.308     albertel 8858:     my $result =
                   8859: 	'<head>'.
1.1160    raeburn  8860: 	&font_settings($args);
1.319     albertel 8861: 
1.1188    raeburn  8862:     my $inhibitprint;
                   8863:     if ($args->{'print_suppress'}) {
                   8864:         $inhibitprint = &print_suppression();
                   8865:     }
1.1064    raeburn  8866: 
1.461     albertel 8867:     if (!$args->{'frameset'}) {
                   8868: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8869:     }
1.962     droeschl 8870:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   8871:         $result .= Apache::lonxml::display_title();
1.319     albertel 8872:     }
1.436     albertel 8873:     if (!$args->{'no_nav_bar'} 
                   8874: 	&& !$args->{'only_body'}
                   8875: 	&& !$args->{'frameset'}) {
1.1154    raeburn  8876: 	$result .= &help_menu_js($httphost);
1.1032    www      8877:         $result.=&modal_window();
1.1038    www      8878:         $result.=&togglebox_script();
1.1034    www      8879:         $result.=&wishlist_window();
1.1041    www      8880:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8881:     } else {
                   8882:         if ($args->{'add_modal'}) {
                   8883:            $result.=&modal_window();
                   8884:         }
                   8885:         if ($args->{'add_wishlist'}) {
                   8886:            $result.=&wishlist_window();
                   8887:         }
1.1038    www      8888:         if ($args->{'add_togglebox'}) {
                   8889:            $result.=&togglebox_script();
                   8890:         }
1.1041    www      8891:         if ($args->{'add_progressbar'}) {
                   8892:            $result.=&LCprogressbarUpdate_script();
                   8893:         }
1.436     albertel 8894:     }
1.314     albertel 8895:     if (ref($args->{'redirect'})) {
1.414     albertel 8896: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 8897: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 8898: 	if (!$inhibit_continue) {
                   8899: 	    $env{'internal.head.redirect'} = $url;
                   8900: 	}
1.313     albertel 8901: 	$result.=<<ADDMETA
                   8902: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 8903: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8904: ADDMETA
1.1210    raeburn  8905:     } else {
                   8906:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8907:             my $requrl = $env{'request.uri'};
                   8908:             if ($requrl eq '') {
                   8909:                 $requrl = $ENV{'REQUEST_URI'};
                   8910:                 $requrl =~ s/\?.+$//;
                   8911:             }
                   8912:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8913:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8914:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8915:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8916:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8917:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  8918:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  8919:                     my ($offload,$offloadoth);
1.1210    raeburn  8920:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8921:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  8922:                             $offload = 1;
1.1353    raeburn  8923:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8924:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8925:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8926:                                     $offloadoth = 1;
                   8927:                                     $dom_in_use = $env{'user.domain'};
                   8928:                                 }
                   8929:                             }
1.1340    raeburn  8930:                         }
                   8931:                     }
                   8932:                     unless ($offload) {
                   8933:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8934:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8935:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8936:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8937:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8938:                                         $offload = 1;
1.1352    raeburn  8939:                                         $offloadoth = 1;
1.1340    raeburn  8940:                                         $dom_in_use = $env{'user.domain'};
                   8941:                                     }
1.1210    raeburn  8942:                                 }
1.1340    raeburn  8943:                             }
                   8944:                         }
                   8945:                     }
                   8946:                     if ($offload) {
1.1358    raeburn  8947:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  8948:                         if (($newserver eq '') && ($offloadoth)) {
                   8949:                             my @domains = &Apache::lonnet::current_machine_domains();
                   8950:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   8951:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8952:                             }
                   8953:                         }
1.1340    raeburn  8954:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8955:                             my $numsec = 5;
                   8956:                             my $timeout = $numsec * 1000;
                   8957:                             my ($newurl,$locknum,%locks,$msg);
                   8958:                             if ($env{'request.role.adv'}) {
                   8959:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8960:                             }
                   8961:                             my $disable_submit = 0;
                   8962:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8963:                                 $disable_submit = 1;
                   8964:                             }
                   8965:                             if ($locknum) {
                   8966:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  8967:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  8968:                                        join(", ",sort(values(%locks)))."\n";
                   8969:                                 if (&show_course()) {
                   8970:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   8971:                                 } else {
                   8972:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  8973:                                 }
1.1340    raeburn  8974:                             } else {
                   8975:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8976:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8977:                                 }
                   8978:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8979:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8980:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8981:                                     $newurl .= '&role='.$env{'request.role'};
                   8982:                                 }
                   8983:                                 if ($env{'request.symb'}) {
                   8984:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8985:                                     if ($shownsymb =~ m{^/enc/}) {
                   8986:                                         my $reqdmajor = 2;
                   8987:                                         my $reqdminor = 11;
                   8988:                                         my $reqdsubminor = 3;
                   8989:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8990:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8991:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8992:                                         if (($major eq '' && $minor eq '') ||
                   8993:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8994:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8995:                                              ($reqdsubminor > $subminor))))) {
                   8996:                                             undef($shownsymb);
                   8997:                                         }
1.1210    raeburn  8998:                                     }
1.1340    raeburn  8999:                                     if ($shownsymb) {
                   9000:                                         &js_escape(\$shownsymb);
                   9001:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9002:                                     }
1.1340    raeburn  9003:                                 } else {
                   9004:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9005:                                     &js_escape(\$shownurl);
                   9006:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9007:                                 }
1.1340    raeburn  9008:                             }
                   9009:                             &js_escape(\$msg);
                   9010:                             $result.=<<OFFLOAD
1.1210    raeburn  9011: <meta http-equiv="pragma" content="no-cache" />
                   9012: <script type="text/javascript">
1.1215    raeburn  9013: // <![CDATA[
1.1210    raeburn  9014: function LC_Offload_Now() {
                   9015:     var dest = "$newurl";
                   9016:     if (dest != '') {
                   9017:         window.location.href="$newurl";
                   9018:     }
                   9019: }
1.1214    raeburn  9020: \$(document).ready(function () {
                   9021:     window.alert('$msg');
                   9022:     if ($disable_submit) {
1.1210    raeburn  9023:         \$(".LC_hwk_submit").prop("disabled", true);
                   9024:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9025:     }
                   9026:     setTimeout('LC_Offload_Now()', $timeout);
                   9027: });
1.1215    raeburn  9028: // ]]>
1.1210    raeburn  9029: </script>
                   9030: OFFLOAD
                   9031:                         }
                   9032:                     }
                   9033:                 }
                   9034:             }
                   9035:         }
1.313     albertel 9036:     }
1.306     albertel 9037:     if (!defined($title)) {
                   9038: 	$title = 'The LearningOnline Network with CAPA';
                   9039:     }
1.460     albertel 9040:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9041:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9042: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9043:     if (!$args->{'frameset'}) {
                   9044:         $result .= ' /';
                   9045:     }
                   9046:     $result .= '>' 
1.1064    raeburn  9047:         .$inhibitprint
1.414     albertel 9048: 	.$head_extra;
1.1242    raeburn  9049:     my $clientmobile;
                   9050:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9051:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9052:     } else {
                   9053:         $clientmobile = $env{'browser.mobile'};
                   9054:     }
                   9055:     if ($clientmobile) {
1.1137    raeburn  9056:         $result .= '
                   9057: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9058: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9059:     }
1.1278    raeburn  9060:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9061:     return $result.'</head>';
1.306     albertel 9062: }
                   9063: 
                   9064: =pod
                   9065: 
1.340     albertel 9066: =item * &font_settings()
                   9067: 
                   9068: Returns neccessary <meta> to set the proper encoding
                   9069: 
1.1160    raeburn  9070: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9071: 
                   9072: =cut
                   9073: 
                   9074: sub font_settings {
1.1160    raeburn  9075:     my ($args) = @_;
1.340     albertel 9076:     my $headerstring='';
1.1160    raeburn  9077:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9078:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9079:         $headerstring.=
                   9080:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9081:         if (!$args->{'frameset'}) {
                   9082: 	    $headerstring.= ' /';
                   9083:         }
                   9084: 	$headerstring .= '>'."\n";
1.340     albertel 9085:     }
                   9086:     return $headerstring;
                   9087: }
                   9088: 
1.341     albertel 9089: =pod
                   9090: 
1.1064    raeburn  9091: =item * &print_suppression()
                   9092: 
                   9093: In course context returns css which causes the body to be blank when media="print",
                   9094: if printout generation is unavailable for the current resource.
                   9095: 
                   9096: This could be because:
                   9097: 
                   9098: (a) printstartdate is in the future
                   9099: 
                   9100: (b) printenddate is in the past
                   9101: 
                   9102: (c) there is an active exam block with "printout"
                   9103: functionality blocked
                   9104: 
                   9105: Users with pav, pfo or evb privileges are exempt.
                   9106: 
                   9107: Inputs: none
                   9108: 
                   9109: =cut
                   9110: 
                   9111: 
                   9112: sub print_suppression {
                   9113:     my $noprint;
                   9114:     if ($env{'request.course.id'}) {
                   9115:         my $scope = $env{'request.course.id'};
                   9116:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9117:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9118:             return;
                   9119:         }
                   9120:         if ($env{'request.course.sec'} ne '') {
                   9121:             $scope .= "/$env{'request.course.sec'}";
                   9122:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9123:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9124:                 return;
1.1064    raeburn  9125:             }
                   9126:         }
                   9127:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9128:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9129:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9130:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9131:         if ($blocked) {
                   9132:             my $checkrole = "cm./$cdom/$cnum";
                   9133:             if ($env{'request.course.sec'} ne '') {
                   9134:                 $checkrole .= "/$env{'request.course.sec'}";
                   9135:             }
                   9136:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9137:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9138:                 $noprint = 1;
                   9139:             }
                   9140:         }
                   9141:         unless ($noprint) {
                   9142:             my $symb = &Apache::lonnet::symbread();
                   9143:             if ($symb ne '') {
                   9144:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9145:                 if (ref($navmap)) {
                   9146:                     my $res = $navmap->getBySymb($symb);
                   9147:                     if (ref($res)) {
                   9148:                         if (!$res->resprintable()) {
                   9149:                             $noprint = 1;
                   9150:                         }
                   9151:                     }
                   9152:                 }
                   9153:             }
                   9154:         }
                   9155:         if ($noprint) {
                   9156:             return <<"ENDSTYLE";
                   9157: <style type="text/css" media="print">
                   9158:     body { display:none }
                   9159: </style>
                   9160: ENDSTYLE
                   9161:         }
                   9162:     }
                   9163:     return;
                   9164: }
                   9165: 
                   9166: =pod
                   9167: 
1.341     albertel 9168: =item * &xml_begin()
                   9169: 
                   9170: Returns the needed doctype and <html>
                   9171: 
                   9172: Inputs: none
                   9173: 
                   9174: =cut
                   9175: 
                   9176: sub xml_begin {
1.1168    raeburn  9177:     my ($is_frameset) = @_;
1.341     albertel 9178:     my $output='';
                   9179: 
                   9180:     if ($env{'browser.mathml'}) {
                   9181: 	$output='<?xml version="1.0"?>'
                   9182:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9183: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9184:             
                   9185: #	    .'<!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">] >'
                   9186: 	    .'<!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">'
                   9187:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9188: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9189:     } elsif ($is_frameset) {
                   9190:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9191:                 '<html>'."\n";
1.341     albertel 9192:     } else {
1.1168    raeburn  9193: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9194:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9195:     }
                   9196:     return $output;
                   9197: }
1.340     albertel 9198: 
                   9199: =pod
                   9200: 
1.306     albertel 9201: =item * &start_page()
                   9202: 
                   9203: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9204: 
1.648     raeburn  9205: Inputs:
                   9206: 
                   9207: =over 4
                   9208: 
                   9209: $title - optional title for the page
                   9210: 
                   9211: $head_extra - optional extra HTML to incude inside the <head>
                   9212: 
                   9213: $args - additional optional args supported are:
                   9214: 
                   9215: =over 8
                   9216: 
                   9217:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9218:                                     arg on
1.814     bisitz   9219:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9220:              add_entries    -> additional attributes to add to the  <body>
                   9221:              domain         -> force to color decorate a page for a 
1.317     albertel 9222:                                     specific domain
1.648     raeburn  9223:              function       -> force usage of a specific rolish color
1.317     albertel 9224:                                     scheme
1.648     raeburn  9225:              redirect       -> see &headtag()
                   9226:              bgcolor        -> override the default page bg color
                   9227:              js_ready       -> return a string ready for being used in 
1.317     albertel 9228:                                     a javascript writeln
1.648     raeburn  9229:              html_encode    -> return a string ready for being used in 
1.320     albertel 9230:                                     a html attribute
1.648     raeburn  9231:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9232:                                     $forcereg arg
1.648     raeburn  9233:              frameset       -> if true will start with a <frameset>
1.330     albertel 9234:                                     rather than <body>
1.648     raeburn  9235:              skip_phases    -> hash ref of 
1.338     albertel 9236:                                     head -> skip the <html><head> generation
                   9237:                                     body -> skip all <body> generation
1.648     raeburn  9238:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9239:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9240:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9241:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9242:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9243:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9244:                                specific group
                   9245:              use_absolute   -> for request for external resource or syllabus, this
                   9246:                                will contain https://<hostname> if server uses
                   9247:                                https (as per hosts.tab), but request is for http
                   9248:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9249:              links_disabled -> Links in primary and secondary menus are disabled
                   9250:                                (Can enable them once page has loaded - see lonroles.pm
                   9251:                                for an example).
1.1380    raeburn  9252:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9253: 
1.648     raeburn  9254: =back
1.460     albertel 9255: 
1.648     raeburn  9256: =back
1.562     albertel 9257: 
1.306     albertel 9258: =cut
                   9259: 
                   9260: sub start_page {
1.309     albertel 9261:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9262:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9263: 
1.315     albertel 9264:     $env{'internal.start_page'}++;
1.1359    raeburn  9265:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9266: 
1.338     albertel 9267:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9268:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9269:     }
1.1316    raeburn  9270: 
                   9271:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9272:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9273:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9274:                 $args->{'no_primary_menu'} = 1;
                   9275:             }
                   9276:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9277:                 $args->{'no_inline_menu'} = 1;
                   9278:             }
                   9279:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9280:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9281:             }
                   9282:         } else {
                   9283:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9284:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9285:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9286:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9287:                     $args->{'no_primary_menu'} = 1;
                   9288:                 }
                   9289:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9290:                     $args->{'no_inline_menu'} = 1;
                   9291:                 }
                   9292:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9293:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9294:                 }
                   9295:             }
                   9296:         }
1.1316    raeburn  9297:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9298:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9299:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9300:     } elsif ($env{'request.course.id'}) {
                   9301:         my $expiretime=600;
                   9302:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9303:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9304:         }
                   9305:         my ($deeplinkmenu,$menuref);
                   9306:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9307:         if ($menucoll) {
                   9308:             if (ref($menuref) eq 'HASH') {
                   9309:                 %menu = %{$menuref};
                   9310:             }
                   9311:             if ($menu{'top'} eq 'n') {
                   9312:                 $args->{'no_primary_menu'} = 1;
                   9313:             }
                   9314:             if ($menu{'inline'} eq 'n') {
                   9315:                 unless (&Apache::lonnet::allowed('opa')) {
                   9316:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9317:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9318:                     my $crstype = &course_type();
                   9319:                     my $now = time;
                   9320:                     my $ccrole;
                   9321:                     if ($crstype eq 'Community') {
                   9322:                         $ccrole = 'co';
                   9323:                     } else {
                   9324:                         $ccrole = 'cc';
                   9325:                     }
                   9326:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9327:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9328:                         if ((($start) && ($start<0)) ||
                   9329:                             (($end) && ($end<$now))  ||
                   9330:                             (($start) && ($now<$start))) {
                   9331:                             $args->{'no_inline_menu'} = 1;
                   9332:                         }
                   9333:                     } else {
                   9334:                         $args->{'no_inline_menu'} = 1;
                   9335:                     }
                   9336:                 }
                   9337:             }
                   9338:         }
1.1316    raeburn  9339:     }
1.1359    raeburn  9340: 
1.338     albertel 9341:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9342: 	if ($args->{'frameset'}) {
                   9343: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9344: 						$args->{'add_entries'});
                   9345: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9346:         } else {
                   9347:             $result .=
                   9348:                 &bodytag($title, 
                   9349:                          $args->{'function'},       $args->{'add_entries'},
                   9350:                          $args->{'only_body'},      $args->{'domain'},
                   9351:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9352:                          $args->{'bgcolor'},        $args,
1.1359    raeburn  9353:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu);
1.831     bisitz   9354:         }
1.330     albertel 9355:     }
1.338     albertel 9356: 
1.315     albertel 9357:     if ($args->{'js_ready'}) {
1.713     kaisler  9358: 		$result = &js_ready($result);
1.315     albertel 9359:     }
1.320     albertel 9360:     if ($args->{'html_encode'}) {
1.713     kaisler  9361: 		$result = &html_encode($result);
                   9362:     }
                   9363: 
1.813     bisitz   9364:     # Preparation for new and consistent functionlist at top of screen
                   9365:     # if ($args->{'functionlist'}) {
                   9366:     #            $result .= &build_functionlist();
                   9367:     #}
                   9368: 
1.964     droeschl 9369:     # Don't add anything more if only_body wanted or in const space
                   9370:     return $result if    $args->{'only_body'} 
                   9371:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9372: 
                   9373:     #Breadcrumbs
1.758     kaisler  9374:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   9375: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9376: 		#if any br links exists, add them to the breadcrumbs
                   9377: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9378: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9379: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9380: 			}
                   9381: 		}
1.1096    raeburn  9382:                 # if @advtools array contains items add then to the breadcrumbs
                   9383:                 if (@advtools > 0) {
                   9384:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9385:                 }
1.1272    raeburn  9386:                 my $menulink;
                   9387:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9388:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9389:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9390:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9391:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9392:                      (!$env{'request.role.adv'}))) {
                   9393:                     $menulink = 0;
                   9394:                 } else {
                   9395:                     undef($menulink);
                   9396:                 }
1.758     kaisler  9397: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9398: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9399: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9400:                 } else {
1.1272    raeburn  9401: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9402: 		}
1.320     albertel 9403:     }
1.315     albertel 9404:     return $result;
1.306     albertel 9405: }
                   9406: 
                   9407: sub end_page {
1.315     albertel 9408:     my ($args) = @_;
                   9409:     $env{'internal.end_page'}++;
1.330     albertel 9410:     my $result;
1.335     albertel 9411:     if ($args->{'discussion'}) {
                   9412: 	my ($target,$parser);
                   9413: 	if (ref($args->{'discussion'})) {
                   9414: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9415: 				$args->{'discussion'}{'parser'});
                   9416: 	}
                   9417: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9418:     }
1.330     albertel 9419:     if ($args->{'frameset'}) {
                   9420: 	$result .= '</frameset>';
                   9421:     } else {
1.635     raeburn  9422: 	$result .= &endbodytag($args);
1.330     albertel 9423:     }
1.1080    raeburn  9424:     unless ($args->{'notbody'}) {
                   9425:         $result .= "\n</html>";
                   9426:     }
1.330     albertel 9427: 
1.315     albertel 9428:     if ($args->{'js_ready'}) {
1.317     albertel 9429: 	$result = &js_ready($result);
1.315     albertel 9430:     }
1.335     albertel 9431: 
1.320     albertel 9432:     if ($args->{'html_encode'}) {
                   9433: 	$result = &html_encode($result);
                   9434:     }
1.335     albertel 9435: 
1.315     albertel 9436:     return $result;
                   9437: }
                   9438: 
1.1359    raeburn  9439: sub menucoll_in_effect {
                   9440:     my ($menucoll,$deeplinkmenu,%menu);
                   9441:     if ($env{'request.course.id'}) {
                   9442:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9443:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9444:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9445:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9446:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9447:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9448:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9449:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9450:                     if (ref($navmap)) {
                   9451:                         $deeplink = $navmap->get_mapparam(undef,
                   9452:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9453:                                                           '0.deeplink');
1.1370    raeburn  9454:                     } else {
                   9455:                         $check_login_symb = 1;
1.1362    raeburn  9456:                     }
                   9457:                 } else {
1.1370    raeburn  9458:                     my $symb = &Apache::lonnet::symbread();
                   9459:                     if ($symb) {
                   9460:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9461:                     } else {
                   9462:                         $check_login_symb = 1;
                   9463:                     }
1.1362    raeburn  9464:                 }
                   9465:             } else {
1.1370    raeburn  9466:                 $check_login_symb = 1;
                   9467:             }
                   9468:             if ($check_login_symb) {
1.1362    raeburn  9469:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9470:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9471:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9472:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9473:                     if (ref($navmap)) {
                   9474:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9475:                     }
                   9476:                 } else {
                   9477:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9478:                 }
                   9479:             }
1.1359    raeburn  9480:             if ($deeplink ne '') {
1.1378    raeburn  9481:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9482:                 if ($display =~ /^\d+$/) {
                   9483:                     $deeplinkmenu = 1;
                   9484:                     $menucoll = $display;
                   9485:                 }
                   9486:             }
                   9487:         }
                   9488:         if ($menucoll) {
                   9489:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9490:         }
                   9491:     }
                   9492:     return ($menucoll,$deeplinkmenu,\%menu);
                   9493: }
                   9494: 
1.1362    raeburn  9495: sub deeplink_login_symb {
                   9496:     my ($cnum,$cdom) = @_;
                   9497:     my $login_symb;
                   9498:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9499:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9500:     }
                   9501:     return $login_symb;
                   9502: }
                   9503: 
                   9504: sub symb_from_tinyurl {
                   9505:     my ($url,$cnum,$cdom) = @_;
                   9506:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9507:         my $key = $1;
                   9508:         my ($tinyurl,$login);
                   9509:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9510:         if (defined($cached)) {
                   9511:             $tinyurl = $result;
                   9512:         } else {
                   9513:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9514:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9515:             if ($currtiny{$key} ne '') {
                   9516:                 $tinyurl = $currtiny{$key};
                   9517:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9518:             }
1.1364    raeburn  9519:         }
                   9520:         if ($tinyurl ne '') {
                   9521:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9522:             if (wantarray) {
                   9523:                 return ($cnumreq,$symb);
                   9524:             } elsif ($cnumreq eq $cnum) {
                   9525:                 return $symb;
1.1362    raeburn  9526:             }
                   9527:         }
                   9528:     }
1.1364    raeburn  9529:     if (wantarray) {
                   9530:         return ();
                   9531:     } else {
                   9532:         return;
                   9533:     }
1.1362    raeburn  9534: }
                   9535: 
1.1034    www      9536: sub wishlist_window {
                   9537:     return(<<'ENDWISHLIST');
1.1046    raeburn  9538: <script type="text/javascript">
1.1034    www      9539: // <![CDATA[
                   9540: // <!-- BEGIN LON-CAPA Internal
                   9541: function set_wishlistlink(title, path) {
                   9542:     if (!title) {
                   9543:         title = document.title;
                   9544:         title = title.replace(/^LON-CAPA /,'');
                   9545:     }
1.1175    raeburn  9546:     title = encodeURIComponent(title);
1.1203    raeburn  9547:     title = title.replace("'","\\\'");
1.1034    www      9548:     if (!path) {
                   9549:         path = location.pathname;
                   9550:     }
1.1175    raeburn  9551:     path = encodeURIComponent(path);
1.1203    raeburn  9552:     path = path.replace("'","\\\'");
1.1034    www      9553:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9554:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9555: }
                   9556: // END LON-CAPA Internal -->
                   9557: // ]]>
                   9558: </script>
                   9559: ENDWISHLIST
                   9560: }
                   9561: 
1.1030    www      9562: sub modal_window {
                   9563:     return(<<'ENDMODAL');
1.1046    raeburn  9564: <script type="text/javascript">
1.1030    www      9565: // <![CDATA[
                   9566: // <!-- BEGIN LON-CAPA Internal
                   9567: var modalWindow = {
                   9568: 	parent:"body",
                   9569: 	windowId:null,
                   9570: 	content:null,
                   9571: 	width:null,
                   9572: 	height:null,
                   9573: 	close:function()
                   9574: 	{
                   9575: 	        $(".LCmodal-window").remove();
                   9576: 	        $(".LCmodal-overlay").remove();
                   9577: 	},
                   9578: 	open:function()
                   9579: 	{
                   9580: 		var modal = "";
                   9581: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9582: 		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;\">";
                   9583: 		modal += this.content;
                   9584: 		modal += "</div>";	
                   9585: 
                   9586: 		$(this.parent).append(modal);
                   9587: 
                   9588: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9589: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9590: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9591: 	}
                   9592: };
1.1140    raeburn  9593: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9594: 	{
1.1266    raeburn  9595:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9596: 		modalWindow.windowId = "myModal";
                   9597: 		modalWindow.width = width;
                   9598: 		modalWindow.height = height;
1.1196    raeburn  9599: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9600: 		modalWindow.open();
1.1208    raeburn  9601: 	};
1.1030    www      9602: // END LON-CAPA Internal -->
                   9603: // ]]>
                   9604: </script>
                   9605: ENDMODAL
                   9606: }
                   9607: 
                   9608: sub modal_link {
1.1140    raeburn  9609:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9610:     unless ($width) { $width=480; }
                   9611:     unless ($height) { $height=400; }
1.1031    www      9612:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  9613:     unless ($transparency) { $transparency='true'; }
                   9614: 
1.1074    raeburn  9615:     my $target_attr;
                   9616:     if (defined($target)) {
                   9617:         $target_attr = 'target="'.$target.'"';
                   9618:     }
                   9619:     return <<"ENDLINK";
1.1336    raeburn  9620: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9621: ENDLINK
1.1030    www      9622: }
                   9623: 
1.1032    www      9624: sub modal_adhoc_script {
1.1365    raeburn  9625:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9626:     my $mathjax;
                   9627:     if ($possmathjax) {
                   9628:         $mathjax = <<'ENDJAX';
                   9629:                if (typeof MathJax == 'object') {
                   9630:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9631:                }
                   9632: ENDJAX
                   9633:     }
1.1032    www      9634:     return (<<ENDADHOC);
1.1046    raeburn  9635: <script type="text/javascript">
1.1032    www      9636: // <![CDATA[
                   9637:         var $funcname = function()
                   9638:         {
                   9639:                 modalWindow.windowId = "myModal";
                   9640:                 modalWindow.width = $width;
                   9641:                 modalWindow.height = $height;
                   9642:                 modalWindow.content = '$content';
                   9643:                 modalWindow.open();
1.1365    raeburn  9644:                 $mathjax
1.1032    www      9645:         };  
                   9646: // ]]>
                   9647: </script>
                   9648: ENDADHOC
                   9649: }
                   9650: 
1.1041    www      9651: sub modal_adhoc_inner {
1.1365    raeburn  9652:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9653:     my $innerwidth=$width-20;
                   9654:     $content=&js_ready(
1.1140    raeburn  9655:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   9656:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9657:                  $content.
1.1041    www      9658:                  &end_scrollbox().
1.1140    raeburn  9659:                  &end_page()
1.1041    www      9660:              );
1.1365    raeburn  9661:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9662: }
                   9663: 
                   9664: sub modal_adhoc_window {
1.1365    raeburn  9665:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9666:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9667:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9668: }
                   9669: 
                   9670: sub modal_adhoc_launch {
                   9671:     my ($funcname,$width,$height,$content)=@_;
                   9672:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9673: <script type="text/javascript">
                   9674: // <![CDATA[
                   9675: $funcname();
                   9676: // ]]>
                   9677: </script>
                   9678: ENDLAUNCH
                   9679: }
                   9680: 
                   9681: sub modal_adhoc_close {
                   9682:     return (<<ENDCLOSE);
                   9683: <script type="text/javascript">
                   9684: // <![CDATA[
                   9685: modalWindow.close();
                   9686: // ]]>
                   9687: </script>
                   9688: ENDCLOSE
                   9689: }
                   9690: 
1.1038    www      9691: sub togglebox_script {
                   9692:    return(<<ENDTOGGLE);
                   9693: <script type="text/javascript"> 
                   9694: // <![CDATA[
                   9695: function LCtoggleDisplay(id,hidetext,showtext) {
                   9696:    link = document.getElementById(id + "link").childNodes[0];
                   9697:    with (document.getElementById(id).style) {
                   9698:       if (display == "none" ) {
                   9699:           display = "inline";
                   9700:           link.nodeValue = hidetext;
                   9701:         } else {
                   9702:           display = "none";
                   9703:           link.nodeValue = showtext;
                   9704:        }
                   9705:    }
                   9706: }
                   9707: // ]]>
                   9708: </script>
                   9709: ENDTOGGLE
                   9710: }
                   9711: 
1.1039    www      9712: sub start_togglebox {
                   9713:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9714:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9715:     unless ($showtext) { $showtext=&mt('show'); }
                   9716:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9717:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9718:     return &start_data_table().
                   9719:            &start_data_table_header_row().
                   9720:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9721:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9722:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9723:            &end_data_table_header_row().
                   9724:            '<tr id="'.$id.'" style="display:none""><td>';
                   9725: }
                   9726: 
                   9727: sub end_togglebox {
                   9728:     return '</td></tr>'.&end_data_table();
                   9729: }
                   9730: 
1.1041    www      9731: sub LCprogressbar_script {
1.1302    raeburn  9732:    my ($id,$number_to_do)=@_;
                   9733:    if ($number_to_do) {
                   9734:        return(<<ENDPROGRESS);
1.1041    www      9735: <script type="text/javascript">
                   9736: // <![CDATA[
1.1045    www      9737: \$('#progressbar$id').progressbar({
1.1041    www      9738:   value: 0,
                   9739:   change: function(event, ui) {
                   9740:     var newVal = \$(this).progressbar('option', 'value');
                   9741:     \$('.pblabel', this).text(LCprogressTxt);
                   9742:   }
                   9743: });
                   9744: // ]]>
                   9745: </script>
                   9746: ENDPROGRESS
1.1302    raeburn  9747:    } else {
                   9748:        return(<<ENDPROGRESS);
                   9749: <script type="text/javascript">
                   9750: // <![CDATA[
                   9751: \$('#progressbar$id').progressbar({
                   9752:   value: false,
                   9753:   create: function(event, ui) {
                   9754:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9755:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9756:   }
                   9757: });
                   9758: // ]]>
                   9759: </script>
                   9760: ENDPROGRESS
                   9761:    }
1.1041    www      9762: }
                   9763: 
                   9764: sub LCprogressbarUpdate_script {
                   9765:    return(<<ENDPROGRESSUPDATE);
                   9766: <style type="text/css">
                   9767: .ui-progressbar { position:relative; }
1.1302    raeburn  9768: .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      9769: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9770: </style>
                   9771: <script type="text/javascript">
                   9772: // <![CDATA[
1.1045    www      9773: var LCprogressTxt='---';
                   9774: 
1.1302    raeburn  9775: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9776:    LCprogressTxt=progresstext;
1.1302    raeburn  9777:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9778:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9779:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  9780:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9781:    } else {
                   9782:        \$('#progressbar'+id).progressbar('value',percent);
                   9783:    }
1.1041    www      9784: }
                   9785: // ]]>
                   9786: </script>
                   9787: ENDPROGRESSUPDATE
                   9788: }
                   9789: 
1.1042    www      9790: my $LClastpercent;
1.1045    www      9791: my $LCidcnt;
                   9792: my $LCcurrentid;
1.1042    www      9793: 
1.1041    www      9794: sub LCprogressbar {
1.1302    raeburn  9795:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9796:     $LClastpercent=0;
1.1045    www      9797:     $LCidcnt++;
                   9798:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  9799:     my ($starting,$content);
                   9800:     if ($number_to_do) {
                   9801:         $starting=&mt('Starting');
                   9802:         $content=(<<ENDPROGBAR);
                   9803: $preamble
1.1045    www      9804:   <div id="progressbar$LCcurrentid">
1.1041    www      9805:     <span class="pblabel">$starting</span>
                   9806:   </div>
                   9807: ENDPROGBAR
1.1302    raeburn  9808:     } else {
                   9809:         $starting=&mt('Loading...');
                   9810:         $LClastpercent='false';
                   9811:         $content=(<<ENDPROGBAR);
                   9812: $preamble
                   9813:   <div id="progressbar$LCcurrentid">
                   9814:       <div class="progress-label">$starting</div>
                   9815:   </div>
                   9816: ENDPROGBAR
                   9817:     }
                   9818:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9819: }
                   9820: 
                   9821: sub LCprogressbarUpdate {
1.1302    raeburn  9822:     my ($r,$val,$text,$number_to_do)=@_;
                   9823:     if ($number_to_do) {
                   9824:         unless ($val) { 
                   9825:             if ($LClastpercent) {
                   9826:                 $val=$LClastpercent;
                   9827:             } else {
                   9828:                 $val=0;
                   9829:             }
                   9830:         }
                   9831:         if ($val<0) { $val=0; }
                   9832:         if ($val>100) { $val=0; }
                   9833:         $LClastpercent=$val;
                   9834:         unless ($text) { $text=$val.'%'; }
                   9835:     } else {
                   9836:         $val = 'false';
1.1042    www      9837:     }
1.1041    www      9838:     $text=&js_ready($text);
1.1044    www      9839:     &r_print($r,<<ENDUPDATE);
1.1041    www      9840: <script type="text/javascript">
                   9841: // <![CDATA[
1.1302    raeburn  9842: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9843: // ]]>
                   9844: </script>
                   9845: ENDUPDATE
1.1035    www      9846: }
                   9847: 
1.1042    www      9848: sub LCprogressbarClose {
                   9849:     my ($r)=@_;
                   9850:     $LClastpercent=0;
1.1044    www      9851:     &r_print($r,<<ENDCLOSE);
1.1042    www      9852: <script type="text/javascript">
                   9853: // <![CDATA[
1.1045    www      9854: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9855: // ]]>
                   9856: </script>
                   9857: ENDCLOSE
1.1044    www      9858: }
                   9859: 
                   9860: sub r_print {
                   9861:     my ($r,$to_print)=@_;
                   9862:     if ($r) {
                   9863:       $r->print($to_print);
                   9864:       $r->rflush();
                   9865:     } else {
                   9866:       print($to_print);
                   9867:     }
1.1042    www      9868: }
                   9869: 
1.320     albertel 9870: sub html_encode {
                   9871:     my ($result) = @_;
                   9872: 
1.322     albertel 9873:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9874:     
                   9875:     return $result;
                   9876: }
1.1044    www      9877: 
1.317     albertel 9878: sub js_ready {
                   9879:     my ($result) = @_;
                   9880: 
1.323     albertel 9881:     $result =~ s/[\n\r]/ /xmsg;
                   9882:     $result =~ s/\\/\\\\/xmsg;
                   9883:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9884:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9885:     
                   9886:     return $result;
                   9887: }
                   9888: 
1.315     albertel 9889: sub validate_page {
                   9890:     if (  exists($env{'internal.start_page'})
1.316     albertel 9891: 	  &&     $env{'internal.start_page'} > 1) {
                   9892: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9893: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9894: 				 $ENV{'request.filename'});
1.315     albertel 9895:     }
                   9896:     if (  exists($env{'internal.end_page'})
1.316     albertel 9897: 	  &&     $env{'internal.end_page'} > 1) {
                   9898: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9899: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9900: 				 $env{'request.filename'});
1.315     albertel 9901:     }
                   9902:     if (     exists($env{'internal.start_page'})
                   9903: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9904: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9905: 				 $env{'request.filename'});
1.315     albertel 9906:     }
                   9907:     if (   ! exists($env{'internal.start_page'})
                   9908: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9909: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9910: 				 $env{'request.filename'});
1.315     albertel 9911:     }
1.306     albertel 9912: }
1.315     albertel 9913: 
1.996     www      9914: 
                   9915: sub start_scrollbox {
1.1140    raeburn  9916:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9917:     unless ($outerwidth) { $outerwidth='520px'; }
                   9918:     unless ($width) { $width='500px'; }
                   9919:     unless ($height) { $height='200px'; }
1.1075    raeburn  9920:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9921:     if ($id ne '') {
1.1140    raeburn  9922:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  9923:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9924:     }
1.1075    raeburn  9925:     if ($bgcolor ne '') {
                   9926:         $tdcol = "background-color: $bgcolor;";
                   9927:     }
1.1137    raeburn  9928:     my $nicescroll_js;
                   9929:     if ($env{'browser.mobile'}) {
1.1140    raeburn  9930:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9931:     }
                   9932:     return <<"END";
                   9933: $nicescroll_js
                   9934: 
                   9935: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   9936: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   9937: END
                   9938: }
                   9939: 
                   9940: sub end_scrollbox {
                   9941:     return '</div></td></tr></table>';
                   9942: }
                   9943: 
                   9944: sub nicescroll_javascript {
                   9945:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9946:     my %options;
                   9947:     if (ref($cursor) eq 'HASH') {
                   9948:         %options = %{$cursor};
                   9949:     }
                   9950:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9951:         $options{'railalign'} = 'left';
                   9952:     }
                   9953:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9954:         my $function  = &get_users_function();
                   9955:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  9956:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  9957:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  9958:         }
1.1140    raeburn  9959:     }
                   9960:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9961:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  9962:             $options{'cursoropacity'}='1.0';
                   9963:         }
1.1140    raeburn  9964:     } else {
                   9965:         $options{'cursoropacity'}='1.0';
                   9966:     }
                   9967:     if ($options{'cursorfixedheight'} eq 'none') {
                   9968:         delete($options{'cursorfixedheight'});
                   9969:     } else {
                   9970:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9971:     }
                   9972:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9973:         delete($options{'railoffset'});
                   9974:     }
                   9975:     my @niceoptions;
                   9976:     while (my($key,$value) = each(%options)) {
                   9977:         if ($value =~ /^\{.+\}$/) {
                   9978:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  9979:         } else {
1.1140    raeburn  9980:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  9981:         }
1.1140    raeburn  9982:     }
                   9983:     my $nicescroll_js = '
1.1137    raeburn  9984: $(document).ready(
1.1140    raeburn  9985:       function() {
                   9986:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9987:       }
1.1137    raeburn  9988: );
                   9989: ';
1.1140    raeburn  9990:     if ($framecheck) {
                   9991:         $nicescroll_js .= '
                   9992: function expand_div(caller) {
                   9993:     if (top === self) {
                   9994:         document.getElementById("'.$id.'").style.width = "auto";
                   9995:         document.getElementById("'.$id.'").style.height = "auto";
                   9996:     } else {
                   9997:         try {
                   9998:             if (parent.frames) {
                   9999:                 if (parent.frames.length > 1) {
                   10000:                     var framesrc = parent.frames[1].location.href;
                   10001:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10002:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10003:                         document.getElementById("'.$id.'").style.width = "auto";
                   10004:                         document.getElementById("'.$id.'").style.height = "auto";
                   10005:                     }
                   10006:                 }
                   10007:             }
                   10008:         } catch (e) {
                   10009:             return;
                   10010:         }
1.1137    raeburn  10011:     }
1.1140    raeburn  10012:     return;
1.996     www      10013: }
1.1140    raeburn  10014: ';
                   10015:     }
                   10016:     if ($needjsready) {
                   10017:         $nicescroll_js = '
                   10018: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10019:     } else {
                   10020:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10021:     }
                   10022:     return $nicescroll_js;
1.996     www      10023: }
                   10024: 
1.318     albertel 10025: sub simple_error_page {
1.1150    bisitz   10026:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10027:     my %displayargs;
1.1151    raeburn  10028:     if (ref($args) eq 'HASH') {
                   10029:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10030:         if ($args->{'only_body'}) {
                   10031:             $displayargs{'only_body'} = 1;
                   10032:         }
                   10033:         if ($args->{'no_nav_bar'}) {
                   10034:             $displayargs{'no_nav_bar'} = 1;
                   10035:         }
1.1151    raeburn  10036:     } else {
                   10037:         $msg = &mt($msg);
                   10038:     }
1.1150    bisitz   10039: 
1.318     albertel 10040:     my $page =
1.1304    raeburn  10041: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10042: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10043: 	&Apache::loncommon::end_page();
                   10044:     if (ref($r)) {
                   10045: 	$r->print($page);
1.327     albertel 10046: 	return;
1.318     albertel 10047:     }
                   10048:     return $page;
                   10049: }
1.347     albertel 10050: 
                   10051: {
1.610     albertel 10052:     my @row_count;
1.961     onken    10053: 
                   10054:     sub start_data_table_count {
                   10055:         unshift(@row_count, 0);
                   10056:         return;
                   10057:     }
                   10058: 
                   10059:     sub end_data_table_count {
                   10060:         shift(@row_count);
                   10061:         return;
                   10062:     }
                   10063: 
1.347     albertel 10064:     sub start_data_table {
1.1018    raeburn  10065: 	my ($add_class,$id) = @_;
1.422     albertel 10066: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10067:         my $table_id;
                   10068:         if (defined($id)) {
                   10069:             $table_id = ' id="'.$id.'"';
                   10070:         }
1.961     onken    10071: 	&start_data_table_count();
1.1018    raeburn  10072: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10073:     }
                   10074: 
                   10075:     sub end_data_table {
1.961     onken    10076: 	&end_data_table_count();
1.389     albertel 10077: 	return '</table>'."\n";;
1.347     albertel 10078:     }
                   10079: 
                   10080:     sub start_data_table_row {
1.974     wenzelju 10081: 	my ($add_class, $id) = @_;
1.610     albertel 10082: 	$row_count[0]++;
                   10083: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10084: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10085:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10086:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10087:     }
1.471     banghart 10088:     
                   10089:     sub continue_data_table_row {
1.974     wenzelju 10090: 	my ($add_class, $id) = @_;
1.610     albertel 10091: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10092: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10093:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10094:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10095:     }
1.347     albertel 10096: 
                   10097:     sub end_data_table_row {
1.389     albertel 10098: 	return '</tr>'."\n";;
1.347     albertel 10099:     }
1.367     www      10100: 
1.421     albertel 10101:     sub start_data_table_empty_row {
1.707     bisitz   10102: #	$row_count[0]++;
1.421     albertel 10103: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10104:     }
                   10105: 
                   10106:     sub end_data_table_empty_row {
                   10107: 	return '</tr>'."\n";;
                   10108:     }
                   10109: 
1.367     www      10110:     sub start_data_table_header_row {
1.389     albertel 10111: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10112:     }
                   10113: 
                   10114:     sub end_data_table_header_row {
1.389     albertel 10115: 	return '</tr>'."\n";;
1.367     www      10116:     }
1.890     droeschl 10117: 
                   10118:     sub data_table_caption {
                   10119:         my $caption = shift;
                   10120:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10121:     }
1.347     albertel 10122: }
                   10123: 
1.548     albertel 10124: =pod
                   10125: 
                   10126: =item * &inhibit_menu_check($arg)
                   10127: 
                   10128: Checks for a inhibitmenu state and generates output to preserve it
                   10129: 
                   10130: Inputs:         $arg - can be any of
                   10131:                      - undef - in which case the return value is a string 
                   10132:                                to add  into arguments list of a uri
                   10133:                      - 'input' - in which case the return value is a HTML
                   10134:                                  <form> <input> field of type hidden to
                   10135:                                  preserve the value
                   10136:                      - a url - in which case the return value is the url with
                   10137:                                the neccesary cgi args added to preserve the
                   10138:                                inhibitmenu state
                   10139:                      - a ref to a url - no return value, but the string is
                   10140:                                         updated to include the neccessary cgi
                   10141:                                         args to preserve the inhibitmenu state
                   10142: 
                   10143: =cut
                   10144: 
                   10145: sub inhibit_menu_check {
                   10146:     my ($arg) = @_;
                   10147:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10148:     if ($arg eq 'input') {
                   10149: 	if ($env{'form.inhibitmenu'}) {
                   10150: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10151: 	} else {
                   10152: 	    return
                   10153: 	}
                   10154:     }
                   10155:     if ($env{'form.inhibitmenu'}) {
                   10156: 	if (ref($arg)) {
                   10157: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10158: 	} elsif ($arg eq '') {
                   10159: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10160: 	} else {
                   10161: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10162: 	}
                   10163:     }
                   10164:     if (!ref($arg)) {
                   10165: 	return $arg;
                   10166:     }
                   10167: }
                   10168: 
1.251     albertel 10169: ###############################################
1.182     matthew  10170: 
                   10171: =pod
                   10172: 
1.549     albertel 10173: =back
                   10174: 
                   10175: =head1 User Information Routines
                   10176: 
                   10177: =over 4
                   10178: 
1.405     albertel 10179: =item * &get_users_function()
1.182     matthew  10180: 
                   10181: Used by &bodytag to determine the current users primary role.
                   10182: Returns either 'student','coordinator','admin', or 'author'.
                   10183: 
                   10184: =cut
                   10185: 
                   10186: ###############################################
                   10187: sub get_users_function {
1.815     tempelho 10188:     my $function = 'norole';
1.818     tempelho 10189:     if ($env{'request.role'}=~/^(st)/) {
                   10190:         $function='student';
                   10191:     }
1.907     raeburn  10192:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10193:         $function='coordinator';
                   10194:     }
1.258     albertel 10195:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10196:         $function='admin';
                   10197:     }
1.826     bisitz   10198:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10199:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10200:         $function='author';
                   10201:     }
                   10202:     return $function;
1.54      www      10203: }
1.99      www      10204: 
                   10205: ###############################################
                   10206: 
1.233     raeburn  10207: =pod
                   10208: 
1.821     raeburn  10209: =item * &show_course()
                   10210: 
                   10211: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10212: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10213: 
                   10214: Inputs:
                   10215: None
                   10216: 
                   10217: Outputs:
                   10218: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10219: 
                   10220: =cut
                   10221: 
                   10222: ###############################################
                   10223: sub show_course {
                   10224:     my $course = !$env{'user.adv'};
                   10225:     if (!$env{'user.adv'}) {
                   10226:         foreach my $env (keys(%env)) {
                   10227:             next if ($env !~ m/^user\.priv\./);
                   10228:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10229:                 $course = 0;
                   10230:                 last;
                   10231:             }
                   10232:         }
                   10233:     }
                   10234:     return $course;
                   10235: }
                   10236: 
                   10237: ###############################################
                   10238: 
                   10239: =pod
                   10240: 
1.542     raeburn  10241: =item * &check_user_status()
1.274     raeburn  10242: 
                   10243: Determines current status of supplied role for a
                   10244: specific user. Roles can be active, previous or future.
                   10245: 
                   10246: Inputs: 
                   10247: user's domain, user's username, course's domain,
1.375     raeburn  10248: course's number, optional section ID.
1.274     raeburn  10249: 
                   10250: Outputs:
                   10251: role status: active, previous or future. 
                   10252: 
                   10253: =cut
                   10254: 
                   10255: sub check_user_status {
1.412     raeburn  10256:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10257:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10258:     my @uroles = keys(%userinfo);
1.274     raeburn  10259:     my $srchstr;
                   10260:     my $active_chk = 'none';
1.412     raeburn  10261:     my $now = time;
1.274     raeburn  10262:     if (@uroles > 0) {
1.908     raeburn  10263:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10264:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10265:         } else {
1.412     raeburn  10266:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10267:         }
                   10268:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10269:             my $role_end = 0;
                   10270:             my $role_start = 0;
                   10271:             $active_chk = 'active';
1.412     raeburn  10272:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10273:                 $role_end = $1;
                   10274:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10275:                     $role_start = $1;
1.274     raeburn  10276:                 }
                   10277:             }
                   10278:             if ($role_start > 0) {
1.412     raeburn  10279:                 if ($now < $role_start) {
1.274     raeburn  10280:                     $active_chk = 'future';
                   10281:                 }
                   10282:             }
                   10283:             if ($role_end > 0) {
1.412     raeburn  10284:                 if ($now > $role_end) {
1.274     raeburn  10285:                     $active_chk = 'previous';
                   10286:                 }
                   10287:             }
                   10288:         }
                   10289:     }
                   10290:     return $active_chk;
                   10291: }
                   10292: 
                   10293: ###############################################
                   10294: 
                   10295: =pod
                   10296: 
1.405     albertel 10297: =item * &get_sections()
1.233     raeburn  10298: 
                   10299: Determines all the sections for a course including
                   10300: sections with students and sections containing other roles.
1.419     raeburn  10301: Incoming parameters: 
                   10302: 
                   10303: 1. domain
                   10304: 2. course number 
                   10305: 3. reference to array containing roles for which sections should 
                   10306: be gathered (optional).
                   10307: 4. reference to array containing status types for which sections 
                   10308: should be gathered (optional).
                   10309: 
                   10310: If the third argument is undefined, sections are gathered for any role. 
                   10311: If the fourth argument is undefined, sections are gathered for any status.
                   10312: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10313:  
1.374     raeburn  10314: Returns section hash (keys are section IDs, values are
                   10315: number of users in each section), subject to the
1.419     raeburn  10316: optional roles filter, optional status filter 
1.233     raeburn  10317: 
                   10318: =cut
                   10319: 
                   10320: ###############################################
                   10321: sub get_sections {
1.419     raeburn  10322:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10323:     if (!defined($cdom) || !defined($cnum)) {
                   10324:         my $cid =  $env{'request.course.id'};
                   10325: 
                   10326: 	return if (!defined($cid));
                   10327: 
                   10328:         $cdom = $env{'course.'.$cid.'.domain'};
                   10329:         $cnum = $env{'course.'.$cid.'.num'};
                   10330:     }
                   10331: 
                   10332:     my %sectioncount;
1.419     raeburn  10333:     my $now = time;
1.240     albertel 10334: 
1.1118    raeburn  10335:     my $check_students = 1;
                   10336:     my $only_students = 0;
                   10337:     if (ref($possible_roles) eq 'ARRAY') {
                   10338:         if (grep(/^st$/,@{$possible_roles})) {
                   10339:             if (@{$possible_roles} == 1) {
                   10340:                 $only_students = 1;
                   10341:             }
                   10342:         } else {
                   10343:             $check_students = 0;
                   10344:         }
                   10345:     }
                   10346: 
                   10347:     if ($check_students) { 
1.276     albertel 10348: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10349: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10350: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10351:         my $start_index = &Apache::loncoursedata::CL_START();
                   10352:         my $end_index = &Apache::loncoursedata::CL_END();
                   10353:         my $status;
1.366     albertel 10354: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10355: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10356: 				                     $data->[$status_index],
                   10357:                                                      $data->[$start_index],
                   10358:                                                      $data->[$end_index]);
                   10359:             if ($stu_status eq 'Active') {
                   10360:                 $status = 'active';
                   10361:             } elsif ($end < $now) {
                   10362:                 $status = 'previous';
                   10363:             } elsif ($start > $now) {
                   10364:                 $status = 'future';
                   10365:             } 
                   10366: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10367:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10368:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10369: 		    $sectioncount{$section}++;
                   10370:                 }
1.240     albertel 10371: 	    }
                   10372: 	}
                   10373:     }
1.1118    raeburn  10374:     if ($only_students) {
                   10375:         return %sectioncount;
                   10376:     }
1.240     albertel 10377:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10378:     foreach my $user (sort(keys(%courseroles))) {
                   10379: 	if ($user !~ /^(\w{2})/) { next; }
                   10380: 	my ($role) = ($user =~ /^(\w{2})/);
                   10381: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10382: 	my ($section,$status);
1.240     albertel 10383: 	if ($role eq 'cr' &&
                   10384: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10385: 	    $section=$1;
                   10386: 	}
                   10387: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10388: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10389:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10390:         if ($end == -1 && $start == -1) {
                   10391:             next; #deleted role
                   10392:         }
                   10393:         if (!defined($possible_status)) { 
                   10394:             $sectioncount{$section}++;
                   10395:         } else {
                   10396:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10397:                 $status = 'active';
                   10398:             } elsif ($end < $now) {
                   10399:                 $status = 'future';
                   10400:             } elsif ($start > $now) {
                   10401:                 $status = 'previous';
                   10402:             }
                   10403:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10404:                 $sectioncount{$section}++;
                   10405:             }
                   10406:         }
1.233     raeburn  10407:     }
1.366     albertel 10408:     return %sectioncount;
1.233     raeburn  10409: }
                   10410: 
1.274     raeburn  10411: ###############################################
1.294     raeburn  10412: 
                   10413: =pod
1.405     albertel 10414: 
                   10415: =item * &get_course_users()
                   10416: 
1.275     raeburn  10417: Retrieves usernames:domains for users in the specified course
                   10418: with specific role(s), and access status. 
                   10419: 
                   10420: Incoming parameters:
1.277     albertel 10421: 1. course domain
                   10422: 2. course number
                   10423: 3. access status: users must have - either active, 
1.275     raeburn  10424: previous, future, or all.
1.277     albertel 10425: 4. reference to array of permissible roles
1.288     raeburn  10426: 5. reference to array of section restrictions (optional)
                   10427: 6. reference to results object (hash of hashes).
                   10428: 7. reference to optional userdata hash
1.609     raeburn  10429: 8. reference to optional statushash
1.630     raeburn  10430: 9. flag if privileged users (except those set to unhide in
                   10431:    course settings) should be excluded    
1.609     raeburn  10432: Keys of top level results hash are roles.
1.275     raeburn  10433: Keys of inner hashes are username:domain, with 
                   10434: values set to access type.
1.288     raeburn  10435: Optional userdata hash returns an array with arguments in the 
                   10436: same order as loncoursedata::get_classlist() for student data.
                   10437: 
1.609     raeburn  10438: Optional statushash returns
                   10439: 
1.288     raeburn  10440: Entries for end, start, section and status are blank because
                   10441: of the possibility of multiple values for non-student roles.
                   10442: 
1.275     raeburn  10443: =cut
1.405     albertel 10444: 
1.275     raeburn  10445: ###############################################
1.405     albertel 10446: 
1.275     raeburn  10447: sub get_course_users {
1.630     raeburn  10448:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10449:     my %idx = ();
1.419     raeburn  10450:     my %seclists;
1.288     raeburn  10451: 
                   10452:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10453:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10454:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10455:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10456:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10457:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10458:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10459:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10460: 
1.290     albertel 10461:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10462:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10463:         my $now = time;
1.277     albertel 10464:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10465:             my $match = 0;
1.412     raeburn  10466:             my $secmatch = 0;
1.419     raeburn  10467:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10468:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10469:             if ($section eq '') {
                   10470:                 $section = 'none';
                   10471:             }
1.291     albertel 10472:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10473:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10474:                     $secmatch = 1;
                   10475:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10476:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10477:                         $secmatch = 1;
                   10478:                     }
                   10479:                 } else {  
1.419     raeburn  10480: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10481: 		        $secmatch = 1;
                   10482:                     }
1.290     albertel 10483: 		}
1.412     raeburn  10484:                 if (!$secmatch) {
                   10485:                     next;
                   10486:                 }
1.419     raeburn  10487:             }
1.275     raeburn  10488:             if (defined($$types{'active'})) {
1.288     raeburn  10489:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10490:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10491:                     $match = 1;
1.275     raeburn  10492:                 }
                   10493:             }
                   10494:             if (defined($$types{'previous'})) {
1.609     raeburn  10495:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10496:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10497:                     $match = 1;
1.275     raeburn  10498:                 }
                   10499:             }
                   10500:             if (defined($$types{'future'})) {
1.609     raeburn  10501:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10502:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10503:                     $match = 1;
1.275     raeburn  10504:                 }
                   10505:             }
1.609     raeburn  10506:             if ($match) {
                   10507:                 push(@{$seclists{$student}},$section);
                   10508:                 if (ref($userdata) eq 'HASH') {
                   10509:                     $$userdata{$student} = $$classlist{$student};
                   10510:                 }
                   10511:                 if (ref($statushash) eq 'HASH') {
                   10512:                     $statushash->{$student}{'st'}{$section} = $status;
                   10513:                 }
1.288     raeburn  10514:             }
1.275     raeburn  10515:         }
                   10516:     }
1.412     raeburn  10517:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10518:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10519:         my $now = time;
1.609     raeburn  10520:         my %displaystatus = ( previous => 'Expired',
                   10521:                               active   => 'Active',
                   10522:                               future   => 'Future',
                   10523:                             );
1.1121    raeburn  10524:         my (%nothide,@possdoms);
1.630     raeburn  10525:         if ($hidepriv) {
                   10526:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10527:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10528:                 if ($user !~ /:/) {
                   10529:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10530:                 } else {
                   10531:                     $nothide{$user} = 1;
                   10532:                 }
                   10533:             }
1.1121    raeburn  10534:             my @possdoms = ($cdom);
                   10535:             if ($coursehash{'checkforpriv'}) {
                   10536:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10537:             }
1.630     raeburn  10538:         }
1.439     raeburn  10539:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10540:             my $match = 0;
1.412     raeburn  10541:             my $secmatch = 0;
1.439     raeburn  10542:             my $status;
1.412     raeburn  10543:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10544:             $user =~ s/:$//;
1.439     raeburn  10545:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10546:             if ($end == -1 || $start == -1) {
                   10547:                 next;
                   10548:             }
                   10549:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10550:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10551:                 my ($uname,$udom) = split(/:/,$user);
                   10552:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10553:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10554:                         $secmatch = 1;
                   10555:                     } elsif ($usec eq '') {
1.420     albertel 10556:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10557:                             $secmatch = 1;
                   10558:                         }
                   10559:                     } else {
                   10560:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10561:                             $secmatch = 1;
                   10562:                         }
                   10563:                     }
                   10564:                     if (!$secmatch) {
                   10565:                         next;
                   10566:                     }
1.288     raeburn  10567:                 }
1.419     raeburn  10568:                 if ($usec eq '') {
                   10569:                     $usec = 'none';
                   10570:                 }
1.275     raeburn  10571:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10572:                     if ($hidepriv) {
1.1121    raeburn  10573:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10574:                             (!$nothide{$uname.':'.$udom})) {
                   10575:                             next;
                   10576:                         }
                   10577:                     }
1.503     raeburn  10578:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10579:                         $status = 'previous';
                   10580:                     } elsif ($start > $now) {
                   10581:                         $status = 'future';
                   10582:                     } else {
                   10583:                         $status = 'active';
                   10584:                     }
1.277     albertel 10585:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10586:                         if ($status eq $type) {
1.420     albertel 10587:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10588:                                 push(@{$$users{$role}{$user}},$type);
                   10589:                             }
1.288     raeburn  10590:                             $match = 1;
                   10591:                         }
                   10592:                     }
1.419     raeburn  10593:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10594:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10595: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10596:                         }
1.420     albertel 10597:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10598:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10599:                         }
1.609     raeburn  10600:                         if (ref($statushash) eq 'HASH') {
                   10601:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10602:                         }
1.275     raeburn  10603:                     }
                   10604:                 }
                   10605:             }
                   10606:         }
1.290     albertel 10607:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10608:             if ((defined($cdom)) && (defined($cnum))) {
                   10609:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10610:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10611:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10612:                     next if ($owner eq '');
                   10613:                     my ($ownername,$ownerdom);
                   10614:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10615:                         $ownername = $1;
                   10616:                         $ownerdom = $2;
                   10617:                     } else {
                   10618:                         $ownername = $owner;
                   10619:                         $ownerdom = $cdom;
                   10620:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10621:                     }
                   10622:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10623:                     if (defined($userdata) && 
1.609     raeburn  10624: 			!exists($$userdata{$owner})) {
                   10625: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10626:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10627:                             push(@{$seclists{$owner}},'none');
                   10628:                         }
                   10629:                         if (ref($statushash) eq 'HASH') {
                   10630:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10631:                         }
1.290     albertel 10632: 		    }
1.279     raeburn  10633:                 }
                   10634:             }
                   10635:         }
1.419     raeburn  10636:         foreach my $user (keys(%seclists)) {
                   10637:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10638:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10639:         }
1.275     raeburn  10640:     }
                   10641:     return;
                   10642: }
                   10643: 
1.288     raeburn  10644: sub get_user_info {
                   10645:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10646:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10647: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10648:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10649:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10650:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10651:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10652:     return;
                   10653: }
1.275     raeburn  10654: 
1.472     raeburn  10655: ###############################################
                   10656: 
                   10657: =pod
                   10658: 
                   10659: =item * &get_user_quota()
                   10660: 
1.1134    raeburn  10661: Retrieves quota assigned for storage of user files.
                   10662: Default is to report quota for portfolio files.
1.472     raeburn  10663: 
                   10664: Incoming parameters:
                   10665: 1. user's username
                   10666: 2. user's domain
1.1134    raeburn  10667: 3. quota name - portfolio, author, or course
1.1136    raeburn  10668:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  10669: 4. crstype - official, unofficial, textbook, placement or community, 
                   10670:    if quota name is course
1.472     raeburn  10671: 
                   10672: Returns:
1.1163    raeburn  10673: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10674: 2. (Optional) Type of setting: custom or default
                   10675:    (individually assigned or default for user's 
                   10676:    institutional status).
                   10677: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10678:    or student - types as defined in localenroll::inst_usertypes 
                   10679:    for user's domain, which determines default quota for user.
                   10680: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10681: 
                   10682: If a value has been stored in the user's environment, 
1.536     raeburn  10683: it will return that, otherwise it returns the maximal default
1.1134    raeburn  10684: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10685: 
                   10686: =cut
                   10687: 
                   10688: ###############################################
                   10689: 
                   10690: 
                   10691: sub get_user_quota {
1.1136    raeburn  10692:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10693:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10694:     if (!defined($udom)) {
                   10695:         $udom = $env{'user.domain'};
                   10696:     }
                   10697:     if (!defined($uname)) {
                   10698:         $uname = $env{'user.name'};
                   10699:     }
                   10700:     if (($udom eq '' || $uname eq '') ||
                   10701:         ($udom eq 'public') && ($uname eq 'public')) {
                   10702:         $quota = 0;
1.536     raeburn  10703:         $quotatype = 'default';
                   10704:         $defquota = 0; 
1.472     raeburn  10705:     } else {
1.536     raeburn  10706:         my $inststatus;
1.1134    raeburn  10707:         if ($quotaname eq 'course') {
                   10708:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10709:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10710:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10711:             } else {
                   10712:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10713:                 $quota = $cenv{'internal.uploadquota'};
                   10714:             }
1.536     raeburn  10715:         } else {
1.1134    raeburn  10716:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10717:                 if ($quotaname eq 'author') {
                   10718:                     $quota = $env{'environment.authorquota'};
                   10719:                 } else {
                   10720:                     $quota = $env{'environment.portfolioquota'};
                   10721:                 }
                   10722:                 $inststatus = $env{'environment.inststatus'};
                   10723:             } else {
                   10724:                 my %userenv = 
                   10725:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10726:                                          'authorquota','inststatus'],$udom,$uname);
                   10727:                 my ($tmp) = keys(%userenv);
                   10728:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10729:                     if ($quotaname eq 'author') {
                   10730:                         $quota = $userenv{'authorquota'};
                   10731:                     } else {
                   10732:                         $quota = $userenv{'portfolioquota'};
                   10733:                     }
                   10734:                     $inststatus = $userenv{'inststatus'};
                   10735:                 } else {
                   10736:                     undef(%userenv);
                   10737:                 }
                   10738:             }
                   10739:         }
                   10740:         if ($quota eq '' || wantarray) {
                   10741:             if ($quotaname eq 'course') {
                   10742:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  10743:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  10744:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   10745:                     ($crstype eq 'placement')) { 
1.1136    raeburn  10746:                     $defquota = $domdefs{$crstype.'quota'};
                   10747:                 }
                   10748:                 if ($defquota eq '') {
                   10749:                     $defquota = 500;
                   10750:                 }
1.1134    raeburn  10751:             } else {
                   10752:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10753:             }
                   10754:             if ($quota eq '') {
                   10755:                 $quota = $defquota;
                   10756:                 $quotatype = 'default';
                   10757:             } else {
                   10758:                 $quotatype = 'custom';
                   10759:             }
1.472     raeburn  10760:         }
                   10761:     }
1.536     raeburn  10762:     if (wantarray) {
                   10763:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10764:     } else {
                   10765:         return $quota;
                   10766:     }
1.472     raeburn  10767: }
                   10768: 
                   10769: ###############################################
                   10770: 
                   10771: =pod
                   10772: 
                   10773: =item * &default_quota()
                   10774: 
1.536     raeburn  10775: Retrieves default quota assigned for storage of user portfolio files,
                   10776: given an (optional) user's institutional status.
1.472     raeburn  10777: 
                   10778: Incoming parameters:
1.1142    raeburn  10779: 
1.472     raeburn  10780: 1. domain
1.536     raeburn  10781: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10782:    status types (e.g., faculty, staff, student etc.)
                   10783:    which apply to the user for whom the default is being retrieved.
                   10784:    If the institutional status string in undefined, the domain
1.1134    raeburn  10785:    default quota will be returned.
                   10786: 3.  quota name - portfolio, author, or course
                   10787:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10788: 
                   10789: Returns:
1.1142    raeburn  10790: 
1.1163    raeburn  10791: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10792: 2. (Optional) institutional type which determined the value of the
                   10793:    default quota.
1.472     raeburn  10794: 
                   10795: If a value has been stored in the domain's configuration db,
                   10796: it will return that, otherwise it returns 20 (for backwards 
                   10797: compatibility with domains which have not set up a configuration
1.1163    raeburn  10798: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10799: 
1.536     raeburn  10800: If the user's status includes multiple types (e.g., staff and student),
                   10801: the largest default quota which applies to the user determines the
                   10802: default quota returned.
                   10803: 
1.472     raeburn  10804: =cut
                   10805: 
                   10806: ###############################################
                   10807: 
                   10808: 
                   10809: sub default_quota {
1.1134    raeburn  10810:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10811:     my ($defquota,$settingstatus);
                   10812:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10813:                                             ['quotas'],$udom);
1.1134    raeburn  10814:     my $key = 'defaultquota';
                   10815:     if ($quotaname eq 'author') {
                   10816:         $key = 'authorquota';
                   10817:     }
1.622     raeburn  10818:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10819:         if ($inststatus ne '') {
1.765     raeburn  10820:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10821:             foreach my $item (@statuses) {
1.1134    raeburn  10822:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10823:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10824:                         if ($defquota eq '') {
1.1134    raeburn  10825:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10826:                             $settingstatus = $item;
1.1134    raeburn  10827:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10828:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10829:                             $settingstatus = $item;
                   10830:                         }
                   10831:                     }
1.1134    raeburn  10832:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10833:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10834:                         if ($defquota eq '') {
                   10835:                             $defquota = $quotahash{'quotas'}{$item};
                   10836:                             $settingstatus = $item;
                   10837:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10838:                             $defquota = $quotahash{'quotas'}{$item};
                   10839:                             $settingstatus = $item;
                   10840:                         }
1.536     raeburn  10841:                     }
                   10842:                 }
                   10843:             }
                   10844:         }
                   10845:         if ($defquota eq '') {
1.1134    raeburn  10846:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10847:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10848:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10849:                 $defquota = $quotahash{'quotas'}{'default'};
                   10850:             }
1.536     raeburn  10851:             $settingstatus = 'default';
1.1139    raeburn  10852:             if ($defquota eq '') {
                   10853:                 if ($quotaname eq 'author') {
                   10854:                     $defquota = 500;
                   10855:                 }
                   10856:             }
1.536     raeburn  10857:         }
                   10858:     } else {
                   10859:         $settingstatus = 'default';
1.1134    raeburn  10860:         if ($quotaname eq 'author') {
                   10861:             $defquota = 500;
                   10862:         } else {
                   10863:             $defquota = 20;
                   10864:         }
1.536     raeburn  10865:     }
                   10866:     if (wantarray) {
                   10867:         return ($defquota,$settingstatus);
1.472     raeburn  10868:     } else {
1.536     raeburn  10869:         return $defquota;
1.472     raeburn  10870:     }
                   10871: }
                   10872: 
1.1135    raeburn  10873: ###############################################
                   10874: 
                   10875: =pod
                   10876: 
1.1136    raeburn  10877: =item * &excess_filesize_warning()
1.1135    raeburn  10878: 
                   10879: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  10880: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  10881: space to be exceeded.
1.1136    raeburn  10882: 
                   10883: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  10884: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  10885: 
1.1165    raeburn  10886: Inputs: 7 
1.1136    raeburn  10887: 1. username or coursenum
1.1135    raeburn  10888: 2. domain
1.1136    raeburn  10889: 3. context ('author' or 'course')
1.1135    raeburn  10890: 4. filename of file for which action is being requested
                   10891: 5. filesize (kB) of file
                   10892: 6. action being taken: copy or upload.
1.1237    raeburn  10893: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  10894: 
                   10895: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  10896:          otherwise return null.
                   10897: 
                   10898: =back
1.1135    raeburn  10899: 
                   10900: =cut
                   10901: 
1.1136    raeburn  10902: sub excess_filesize_warning {
1.1165    raeburn  10903:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  10904:     my $current_disk_usage = 0;
1.1165    raeburn  10905:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  10906:     if ($context eq 'author') {
                   10907:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10908:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10909:     } else {
                   10910:         foreach my $subdir ('docs','supplemental') {
                   10911:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10912:         }
                   10913:     }
1.1135    raeburn  10914:     $disk_quota = int($disk_quota * 1000);
                   10915:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   10916:         return '<p class="LC_warning">'.
1.1135    raeburn  10917:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   10918:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10919:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  10920:                             $disk_quota,$current_disk_usage).
                   10921:                '</p>';
                   10922:     }
                   10923:     return;
                   10924: }
                   10925: 
                   10926: ###############################################
                   10927: 
                   10928: 
1.1136    raeburn  10929: 
                   10930: 
1.384     raeburn  10931: sub get_secgrprole_info {
                   10932:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10933:     my %sections_count = &get_sections($cdom,$cnum);
                   10934:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10935:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10936:     my @groups = sort(keys(%curr_groups));
                   10937:     my $allroles = [];
                   10938:     my $rolehash;
                   10939:     my $accesshash = {
                   10940:                      active => 'Currently has access',
                   10941:                      future => 'Will have future access',
                   10942:                      previous => 'Previously had access',
                   10943:                   };
                   10944:     if ($needroles) {
                   10945:         $rolehash = {'all' => 'all'};
1.385     albertel 10946:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10947: 	if (&Apache::lonnet::error(%user_roles)) {
                   10948: 	    undef(%user_roles);
                   10949: 	}
                   10950:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10951:             my ($role)=split(/\:/,$item,2);
                   10952:             if ($role eq 'cr') { next; }
                   10953:             if ($role =~ /^cr/) {
                   10954:                 $$rolehash{$role} = (split('/',$role))[3];
                   10955:             } else {
                   10956:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10957:             }
                   10958:         }
                   10959:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10960:             push(@{$allroles},$key);
                   10961:         }
                   10962:         push (@{$allroles},'st');
                   10963:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10964:     }
                   10965:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10966: }
                   10967: 
1.555     raeburn  10968: sub user_picker {
1.1279    raeburn  10969:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10970:     my $currdom = $dom;
1.1253    raeburn  10971:     my @alldoms = &Apache::lonnet::all_domains();
                   10972:     if (@alldoms == 1) {
                   10973:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10974:                                                ['directorysrch'],$alldoms[0]);
                   10975:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10976:         my $showdom = $domdesc;
                   10977:         if ($showdom eq '') {
                   10978:             $showdom = $dom;
                   10979:         }
                   10980:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10981:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10982:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10983:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10984:             }
                   10985:         }
                   10986:     }
1.555     raeburn  10987:     my %curr_selected = (
                   10988:                         srchin => 'dom',
1.580     raeburn  10989:                         srchby => 'lastname',
1.555     raeburn  10990:                       );
                   10991:     my $srchterm;
1.625     raeburn  10992:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10993:         if ($srch->{'srchby'} ne '') {
                   10994:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10995:         }
                   10996:         if ($srch->{'srchin'} ne '') {
                   10997:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10998:         }
                   10999:         if ($srch->{'srchtype'} ne '') {
                   11000:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11001:         }
                   11002:         if ($srch->{'srchdomain'} ne '') {
                   11003:             $currdom = $srch->{'srchdomain'};
                   11004:         }
                   11005:         $srchterm = $srch->{'srchterm'};
                   11006:     }
1.1222    damieng  11007:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11008:                     'usr'       => 'Search criteria',
1.563     raeburn  11009:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11010:                     'uname'     => 'username',
                   11011:                     'lastname'  => 'last name',
1.555     raeburn  11012:                     'lastfirst' => 'last name, first name',
1.558     albertel 11013:                     'crs'       => 'in this course',
1.576     raeburn  11014:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11015:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11016:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11017:                     'exact'     => 'is',
                   11018:                     'contains'  => 'contains',
1.569     raeburn  11019:                     'begins'    => 'begins with',
1.1222    damieng  11020:                                        );
                   11021:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11022:                     'youm'      => "You must include some text to search for.",
                   11023:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11024:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11025:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11026:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11027:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11028:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11029:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11030:                                        );
1.1222    damieng  11031:     &html_escape(\%html_lt);
                   11032:     &js_escape(\%js_lt);
1.1255    raeburn  11033:     my $domform;
1.1277    raeburn  11034:     my $allow_blank = 1;
1.1255    raeburn  11035:     if ($fixeddom) {
1.1277    raeburn  11036:         $allow_blank = 0;
                   11037:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11038:     } else {
1.1287    raeburn  11039:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11040:         my ($trusted,$untrusted);
1.1287    raeburn  11041:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11042:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11043:         } elsif ($context eq 'author') {
1.1288    raeburn  11044:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11045:         } elsif ($context eq 'domain') {
1.1288    raeburn  11046:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11047:         }
1.1288    raeburn  11048:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11049:     }
1.563     raeburn  11050:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11051: 
                   11052:     my @srchins = ('crs','dom','alc','instd');
                   11053: 
                   11054:     foreach my $option (@srchins) {
                   11055:         # FIXME 'alc' option unavailable until 
                   11056:         #       loncreateuser::print_user_query_page()
                   11057:         #       has been completed.
                   11058:         next if ($option eq 'alc');
1.880     raeburn  11059:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11060:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11061:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11062:         if ($curr_selected{'srchin'} eq $option) {
                   11063:             $srchinsel .= ' 
1.1222    damieng  11064:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11065:         } else {
                   11066:             $srchinsel .= '
1.1222    damieng  11067:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11068:         }
1.555     raeburn  11069:     }
1.563     raeburn  11070:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11071: 
                   11072:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11073:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11074:         if ($curr_selected{'srchby'} eq $option) {
                   11075:             $srchbysel .= '
1.1222    damieng  11076:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11077:         } else {
                   11078:             $srchbysel .= '
1.1222    damieng  11079:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11080:          }
                   11081:     }
                   11082:     $srchbysel .= "\n  </select>\n";
                   11083: 
                   11084:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11085:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11086:         if ($curr_selected{'srchtype'} eq $option) {
                   11087:             $srchtypesel .= '
1.1222    damieng  11088:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11089:         } else {
                   11090:             $srchtypesel .= '
1.1222    damieng  11091:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11092:         }
                   11093:     }
                   11094:     $srchtypesel .= "\n  </select>\n";
                   11095: 
1.558     albertel 11096:     my ($newuserscript,$new_user_create);
1.994     raeburn  11097:     my $context_dom = $env{'request.role.domain'};
                   11098:     if ($context eq 'requestcrs') {
                   11099:         if ($env{'form.coursedom'} ne '') { 
                   11100:             $context_dom = $env{'form.coursedom'};
                   11101:         }
                   11102:     }
1.556     raeburn  11103:     if ($forcenewuser) {
1.576     raeburn  11104:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11105:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11106:                 if ($cancreate) {
                   11107:                     $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>';
                   11108:                 } else {
1.799     bisitz   11109:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11110:                     my %usertypetext = (
                   11111:                         official   => 'institutional',
                   11112:                         unofficial => 'non-institutional',
                   11113:                     );
1.799     bisitz   11114:                     $new_user_create = '<p class="LC_warning">'
                   11115:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11116:                                       .' '
                   11117:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11118:                                           ,'<a href="'.$helplink.'">','</a>')
                   11119:                                       .'</p><br />';
1.627     raeburn  11120:                 }
1.576     raeburn  11121:             }
                   11122:         }
                   11123: 
1.556     raeburn  11124:         $newuserscript = <<"ENDSCRIPT";
                   11125: 
1.570     raeburn  11126: function setSearch(createnew,callingForm) {
1.556     raeburn  11127:     if (createnew == 1) {
1.570     raeburn  11128:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11129:             if (callingForm.srchby.options[i].value == 'uname') {
                   11130:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11131:             }
                   11132:         }
1.570     raeburn  11133:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11134:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11135: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11136:             }
                   11137:         }
1.570     raeburn  11138:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11139:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11140:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11141:             }
                   11142:         }
1.570     raeburn  11143:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11144:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11145:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11146:             }
                   11147:         }
                   11148:     }
                   11149: }
                   11150: ENDSCRIPT
1.558     albertel 11151: 
1.556     raeburn  11152:     }
                   11153: 
1.555     raeburn  11154:     my $output = <<"END_BLOCK";
1.556     raeburn  11155: <script type="text/javascript">
1.824     bisitz   11156: // <![CDATA[
1.570     raeburn  11157: function validateEntry(callingForm) {
1.558     albertel 11158: 
1.556     raeburn  11159:     var checkok = 1;
1.558     albertel 11160:     var srchin;
1.570     raeburn  11161:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11162: 	if ( callingForm.srchin[i].checked ) {
                   11163: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11164: 	}
                   11165:     }
                   11166: 
1.570     raeburn  11167:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11168:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11169:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11170:     var srchterm =  callingForm.srchterm.value;
                   11171:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11172:     var msg = "";
                   11173: 
                   11174:     if (srchterm == "") {
                   11175:         checkok = 0;
1.1222    damieng  11176:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11177:     }
                   11178: 
1.569     raeburn  11179:     if (srchtype== 'begins') {
                   11180:         if (srchterm.length < 2) {
                   11181:             checkok = 0;
1.1222    damieng  11182:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11183:         }
                   11184:     }
                   11185: 
1.556     raeburn  11186:     if (srchtype== 'contains') {
                   11187:         if (srchterm.length < 3) {
                   11188:             checkok = 0;
1.1222    damieng  11189:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11190:         }
                   11191:     }
                   11192:     if (srchin == 'instd') {
                   11193:         if (srchdomain == '') {
                   11194:             checkok = 0;
1.1222    damieng  11195:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11196:         }
                   11197:     }
                   11198:     if (srchin == 'dom') {
                   11199:         if (srchdomain == '') {
                   11200:             checkok = 0;
1.1222    damieng  11201:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11202:         }
                   11203:     }
                   11204:     if (srchby == 'lastfirst') {
                   11205:         if (srchterm.indexOf(",") == -1) {
                   11206:             checkok = 0;
1.1222    damieng  11207:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11208:         }
                   11209:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11210:             checkok = 0;
1.1222    damieng  11211:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11212:         }
                   11213:     }
                   11214:     if (checkok == 0) {
1.1222    damieng  11215:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11216:         return;
                   11217:     }
                   11218:     if (checkok == 1) {
1.570     raeburn  11219:         callingForm.submit();
1.556     raeburn  11220:     }
                   11221: }
                   11222: 
                   11223: $newuserscript
                   11224: 
1.824     bisitz   11225: // ]]>
1.556     raeburn  11226: </script>
1.558     albertel 11227: 
                   11228: $new_user_create
                   11229: 
1.555     raeburn  11230: END_BLOCK
1.558     albertel 11231: 
1.876     raeburn  11232:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11233:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11234:                $domform.
                   11235:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11236:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11237:                $srchbysel.
                   11238:                $srchtypesel. 
                   11239:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11240:                $srchinsel.
                   11241:                &Apache::lonhtmlcommon::row_closure(1). 
                   11242:                &Apache::lonhtmlcommon::end_pick_box().
                   11243:                '<br />';
1.1253    raeburn  11244:     return ($output,1);
1.555     raeburn  11245: }
                   11246: 
1.612     raeburn  11247: sub user_rule_check {
1.615     raeburn  11248:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11249:     my ($response,%inst_response);
1.612     raeburn  11250:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11251:         if (keys(%{$usershash}) > 1) {
                   11252:             my (%by_username,%by_id,%userdoms);
                   11253:             my $checkid; 
                   11254:             if (ref($checks) eq 'HASH') {
                   11255:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11256:                     $checkid = 1;
                   11257:                 }
                   11258:             }
                   11259:             foreach my $user (keys(%{$usershash})) {
                   11260:                 my ($uname,$udom) = split(/:/,$user);
                   11261:                 if ($checkid) {
                   11262:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11263:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11264:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11265:                             $userdoms{$udom} = 1;
1.1227    raeburn  11266:                             if (ref($inst_results) eq 'HASH') {
                   11267:                                 $inst_results->{$uname.':'.$udom} = {};
                   11268:                             }
1.1226    raeburn  11269:                         }
                   11270:                     }
                   11271:                 } else {
                   11272:                     $by_username{$udom}{$uname} = 1;
                   11273:                     $userdoms{$udom} = 1;
1.1227    raeburn  11274:                     if (ref($inst_results) eq 'HASH') {
                   11275:                         $inst_results->{$uname.':'.$udom} = {};
                   11276:                     }
1.1226    raeburn  11277:                 }
                   11278:             }
                   11279:             foreach my $udom (keys(%userdoms)) {
                   11280:                 if (!$got_rules->{$udom}) {
                   11281:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11282:                                                              ['usercreation'],$udom);
                   11283:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11284:                         foreach my $item ('username','id') {
                   11285:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11286:                                 $$curr_rules{$udom}{$item} =
                   11287:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11288:                             }
                   11289:                         }
                   11290:                     }
                   11291:                     $got_rules->{$udom} = 1;
                   11292:                 }
1.612     raeburn  11293:             }
1.1226    raeburn  11294:             if ($checkid) {
                   11295:                 foreach my $udom (keys(%by_id)) {
                   11296:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11297:                     if ($outcome eq 'ok') {
1.1227    raeburn  11298:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11299:                             my $uname = $by_id{$udom}{$id};
                   11300:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11301:                         }
1.1226    raeburn  11302:                         if (ref($results) eq 'HASH') {
                   11303:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11304:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11305:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11306:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11307:                                 }
1.1226    raeburn  11308:                             }
                   11309:                         }
                   11310:                     }
1.612     raeburn  11311:                 }
1.615     raeburn  11312:             } else {
1.1226    raeburn  11313:                 foreach my $udom (keys(%by_username)) {
                   11314:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11315:                     if ($outcome eq 'ok') {
1.1227    raeburn  11316:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11317:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11318:                         }
1.1226    raeburn  11319:                         if (ref($results) eq 'HASH') {
                   11320:                             foreach my $uname (keys(%{$results})) {
                   11321:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11322:                             }
                   11323:                         }
                   11324:                     }
                   11325:                 }
1.612     raeburn  11326:             }
1.1226    raeburn  11327:         } elsif (keys(%{$usershash}) == 1) {
                   11328:             my $user = (keys(%{$usershash}))[0];
                   11329:             my ($uname,$udom) = split(/:/,$user);
                   11330:             if (($udom ne '') && ($uname ne '')) {
                   11331:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11332:                     if (ref($checks) eq 'HASH') {
                   11333:                         if (defined($checks->{'username'})) {
                   11334:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11335:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11336:                         } elsif (defined($checks->{'id'})) {
                   11337:                             if ($usershash->{$user}->{'id'} ne '') {
                   11338:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11339:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11340:                                                                   $usershash->{$user}->{'id'});
                   11341:                             } else {
                   11342:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11343:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11344:                             }
1.585     raeburn  11345:                         }
1.1226    raeburn  11346:                     } else {
                   11347:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11348:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11349:                        return;
                   11350:                     }
                   11351:                     if (!$got_rules->{$udom}) {
                   11352:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11353:                                                                  ['usercreation'],$udom);
                   11354:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11355:                             foreach my $item ('username','id') {
                   11356:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11357:                                    $$curr_rules{$udom}{$item} = 
                   11358:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11359:                                 }
                   11360:                             }
                   11361:                         }
                   11362:                         $got_rules->{$udom} = 1;
1.585     raeburn  11363:                     }
                   11364:                 }
1.1226    raeburn  11365:             } else {
                   11366:                 return;
                   11367:             }
                   11368:         } else {
                   11369:             return;
                   11370:         }
                   11371:         foreach my $user (keys(%{$usershash})) {
                   11372:             my ($uname,$udom) = split(/:/,$user);
                   11373:             next if (($udom eq '') || ($uname eq ''));
                   11374:             my $id;
1.1227    raeburn  11375:             if (ref($inst_results) eq 'HASH') {
                   11376:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11377:                     $id = $inst_results->{$user}->{'id'};
                   11378:                 }
                   11379:             }
                   11380:             if ($id eq '') { 
                   11381:                 if (ref($usershash->{$user})) {
                   11382:                     $id = $usershash->{$user}->{'id'};
                   11383:                 }
1.585     raeburn  11384:             }
1.612     raeburn  11385:             foreach my $item (keys(%{$checks})) {
                   11386:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11387:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11388:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11389:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11390:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11391:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11392:                                 if ($rule_check{$rule}) {
                   11393:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11394:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11395:                                         if (ref($inst_results) eq 'HASH') {
                   11396:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11397:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11398:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11399:                                                 } elsif ($item eq 'id') {
                   11400:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11401:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11402:                                                     }
1.615     raeburn  11403:                                                 }
1.612     raeburn  11404:                                             }
                   11405:                                         }
1.615     raeburn  11406:                                     }
                   11407:                                     last;
1.585     raeburn  11408:                                 }
                   11409:                             }
                   11410:                         }
                   11411:                     }
                   11412:                 }
                   11413:             }
                   11414:         }
                   11415:     }
1.612     raeburn  11416:     return;
                   11417: }
                   11418: 
                   11419: sub user_rule_formats {
                   11420:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11421:     my %text = ( 
                   11422:                  'username' => 'Usernames',
                   11423:                  'id'       => 'IDs',
                   11424:                );
                   11425:     my $output;
                   11426:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11427:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11428:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11429:             $output = '<br />'.
                   11430:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11431:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11432:                       ' <ul>';
1.612     raeburn  11433:             foreach my $rule (@{$ruleorder}) {
                   11434:                 if (ref($curr_rules) eq 'ARRAY') {
                   11435:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11436:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11437:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11438:                                         $rules->{$rule}{'desc'}.'</li>';
                   11439:                         }
                   11440:                     }
                   11441:                 }
                   11442:             }
                   11443:             $output .= '</ul>';
                   11444:         }
                   11445:     }
                   11446:     return $output;
                   11447: }
                   11448: 
                   11449: sub instrule_disallow_msg {
1.615     raeburn  11450:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11451:     my $response;
                   11452:     my %text = (
                   11453:                   item   => 'username',
                   11454:                   items  => 'usernames',
                   11455:                   match  => 'matches',
                   11456:                   do     => 'does',
                   11457:                   action => 'a username',
                   11458:                   one    => 'one',
                   11459:                );
                   11460:     if ($count > 1) {
                   11461:         $text{'item'} = 'usernames';
                   11462:         $text{'match'} ='match';
                   11463:         $text{'do'} = 'do';
                   11464:         $text{'action'} = 'usernames',
                   11465:         $text{'one'} = 'ones';
                   11466:     }
                   11467:     if ($checkitem eq 'id') {
                   11468:         $text{'items'} = 'IDs';
                   11469:         $text{'item'} = 'ID';
                   11470:         $text{'action'} = 'an ID';
1.615     raeburn  11471:         if ($count > 1) {
                   11472:             $text{'item'} = 'IDs';
                   11473:             $text{'action'} = 'IDs';
                   11474:         }
1.612     raeburn  11475:     }
1.674     bisitz   11476:     $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  11477:     if ($mode eq 'upload') {
                   11478:         if ($checkitem eq 'username') {
                   11479:             $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'}.");
                   11480:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11481:             $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  11482:         }
1.669     raeburn  11483:     } elsif ($mode eq 'selfcreate') {
                   11484:         if ($checkitem eq 'id') {
                   11485:             $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.");
                   11486:         }
1.615     raeburn  11487:     } else {
                   11488:         if ($checkitem eq 'username') {
                   11489:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11490:         } elsif ($checkitem eq 'id') {
                   11491:             $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.");
                   11492:         }
1.612     raeburn  11493:     }
                   11494:     return $response;
1.585     raeburn  11495: }
                   11496: 
1.624     raeburn  11497: sub personal_data_fieldtitles {
                   11498:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11499:                         id => 'Student/Employee ID',
                   11500:                         permanentemail => 'E-mail address',
                   11501:                         lastname => 'Last Name',
                   11502:                         firstname => 'First Name',
                   11503:                         middlename => 'Middle Name',
                   11504:                         generation => 'Generation',
                   11505:                         gen => 'Generation',
1.765     raeburn  11506:                         inststatus => 'Affiliation',
1.624     raeburn  11507:                    );
                   11508:     return %fieldtitles;
                   11509: }
                   11510: 
1.642     raeburn  11511: sub sorted_inst_types {
                   11512:     my ($dom) = @_;
1.1185    raeburn  11513:     my ($usertypes,$order);
                   11514:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11515:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11516:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11517:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11518:     } else {
                   11519:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11520:     }
1.642     raeburn  11521:     my $othertitle = &mt('All users');
                   11522:     if ($env{'request.course.id'}) {
1.668     raeburn  11523:         $othertitle  = &mt('Any users');
1.642     raeburn  11524:     }
                   11525:     my @types;
                   11526:     if (ref($order) eq 'ARRAY') {
                   11527:         @types = @{$order};
                   11528:     }
                   11529:     if (@types == 0) {
                   11530:         if (ref($usertypes) eq 'HASH') {
                   11531:             @types = sort(keys(%{$usertypes}));
                   11532:         }
                   11533:     }
                   11534:     if (keys(%{$usertypes}) > 0) {
                   11535:         $othertitle = &mt('Other users');
                   11536:     }
                   11537:     return ($othertitle,$usertypes,\@types);
                   11538: }
                   11539: 
1.645     raeburn  11540: sub get_institutional_codes {
1.1361    raeburn  11541:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11542: # Get complete list of course sections to update
                   11543:     my @currsections = ();
                   11544:     my @currxlists = ();
1.1361    raeburn  11545:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11546:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  11547:     my $crskey = $crs.':'.$coursecode;
                   11548:     @{$unclutteredsec{$crskey}} = ();
                   11549:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11550: 
                   11551:     if ($$settings{'internal.sectionnums'} ne '') {
                   11552:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11553:     }
                   11554: 
                   11555:     if ($$settings{'internal.crosslistings'} ne '') {
                   11556:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11557:     }
                   11558: 
                   11559:     if (@currxlists > 0) {
1.1361    raeburn  11560:         foreach my $xl (@currxlists) {
                   11561:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11562:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  11563:                     push(@{$allcourses},$1);
1.645     raeburn  11564:                     $$LC_code{$1} = $2;
                   11565:                 }
                   11566:             }
                   11567:         }
                   11568:     }
1.1361    raeburn  11569: 
1.645     raeburn  11570:     if (@currsections > 0) {
1.1361    raeburn  11571:         foreach my $sec (@currsections) {
                   11572:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11573:                 my $instsec = $1;
1.645     raeburn  11574:                 my $lc_sec = $2;
1.1361    raeburn  11575:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11576:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11577:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11578:                 }
                   11579:             }
                   11580:         }
                   11581:     }
                   11582: 
                   11583:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11584:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11585:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11586:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11587:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11588:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  11589:                     push(@{$allcourses},$sec);
1.1361    raeburn  11590:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11591:                 }
                   11592:             }
                   11593:         }
                   11594:     }
                   11595:     return;
                   11596: }
                   11597: 
1.971     raeburn  11598: sub get_standard_codeitems {
                   11599:     return ('Year','Semester','Department','Number','Section');
                   11600: }
                   11601: 
1.112     bowersj2 11602: =pod
                   11603: 
1.780     raeburn  11604: =head1 Slot Helpers
                   11605: 
                   11606: =over 4
                   11607: 
                   11608: =item * sorted_slots()
                   11609: 
1.1040    raeburn  11610: Sorts an array of slot names in order of an optional sort key,
                   11611: default sort is by slot start time (earliest first). 
1.780     raeburn  11612: 
                   11613: Inputs:
                   11614: 
                   11615: =over 4
                   11616: 
                   11617: slotsarr  - Reference to array of unsorted slot names.
                   11618: 
                   11619: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11620: 
1.1040    raeburn  11621: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11622: 
1.549     albertel 11623: =back
                   11624: 
1.780     raeburn  11625: Returns:
                   11626: 
                   11627: =over 4
                   11628: 
1.1040    raeburn  11629: sorted   - An array of slot names sorted by a specified sort key 
                   11630:            (default sort key is start time of the slot).
1.780     raeburn  11631: 
                   11632: =back
                   11633: 
                   11634: =cut
                   11635: 
                   11636: 
                   11637: sub sorted_slots {
1.1040    raeburn  11638:     my ($slotsarr,$slots,$sortkey) = @_;
                   11639:     if ($sortkey eq '') {
                   11640:         $sortkey = 'starttime';
                   11641:     }
1.780     raeburn  11642:     my @sorted;
                   11643:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11644:         @sorted =
                   11645:             sort {
                   11646:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11647:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11648:                      }
                   11649:                      if (ref($slots->{$a})) { return -1;}
                   11650:                      if (ref($slots->{$b})) { return 1;}
                   11651:                      return 0;
                   11652:                  } @{$slotsarr};
                   11653:     }
                   11654:     return @sorted;
                   11655: }
                   11656: 
1.1040    raeburn  11657: =pod
                   11658: 
                   11659: =item * get_future_slots()
                   11660: 
                   11661: Inputs:
                   11662: 
                   11663: =over 4
                   11664: 
                   11665: cnum - course number
                   11666: 
                   11667: cdom - course domain
                   11668: 
                   11669: now - current UNIX time
                   11670: 
                   11671: symb - optional symb
                   11672: 
                   11673: =back
                   11674: 
                   11675: Returns:
                   11676: 
                   11677: =over 4
                   11678: 
                   11679: sorted_reservable - ref to array of student_schedulable slots currently 
                   11680:                     reservable, ordered by end date of reservation period.
                   11681: 
                   11682: reservable_now - ref to hash of student_schedulable slots currently
                   11683:                  reservable.
                   11684: 
                   11685:     Keys in inner hash are:
                   11686:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11687:     (b) endreserve: end date of reservation period.
                   11688:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11689:         selected.
1.1040    raeburn  11690: 
                   11691: sorted_future - ref to array of student_schedulable slots reservable in
                   11692:                 the future, ordered by start date of reservation period.
                   11693: 
                   11694: future_reservable - ref to hash of student_schedulable slots reservable
                   11695:                     in the future.
                   11696: 
                   11697:     Keys in inner hash are:
                   11698:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  11699:     (b) startreserve: start date of reservation period.
                   11700:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11701:         selected.
1.1040    raeburn  11702: 
                   11703: =back
                   11704: 
                   11705: =cut
                   11706: 
                   11707: sub get_future_slots {
                   11708:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  11709:     my $map;
                   11710:     if ($symb) {
                   11711:         ($map) = &Apache::lonnet::decode_symb($symb);
                   11712:     }
1.1040    raeburn  11713:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11714:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11715:     foreach my $slot (keys(%slots)) {
                   11716:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11717:         if ($symb) {
1.1229    raeburn  11718:             if ($slots{$slot}->{'symb'} ne '') {
                   11719:                 my $canuse;
                   11720:                 my %oksymbs;
                   11721:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   11722:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   11723:                 if ($oksymbs{$symb}) {
                   11724:                     $canuse = 1;
                   11725:                 } else {
                   11726:                     foreach my $item (@slotsymbs) {
                   11727:                         if ($item =~ /\.(page|sequence)$/) {
                   11728:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   11729:                             if (($map ne '') && ($map eq $sloturl)) {
                   11730:                                 $canuse = 1;
                   11731:                                 last;
                   11732:                             }
                   11733:                         }
                   11734:                     }
                   11735:                 }
                   11736:                 next unless ($canuse);
                   11737:             }
1.1040    raeburn  11738:         }
                   11739:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11740:             ($slots{$slot}->{'endtime'} > $now)) {
                   11741:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11742:                 my $userallowed = 0;
                   11743:                 if ($slots{$slot}->{'allowedsections'}) {
                   11744:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11745:                     if (!defined($env{'request.role.sec'})
                   11746:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11747:                         $userallowed=1;
                   11748:                     } else {
                   11749:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11750:                             $userallowed=1;
                   11751:                         }
                   11752:                     }
                   11753:                     unless ($userallowed) {
                   11754:                         if (defined($env{'request.course.groups'})) {
                   11755:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11756:                             foreach my $group (@groups) {
                   11757:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11758:                                     $userallowed=1;
                   11759:                                     last;
                   11760:                                 }
                   11761:                             }
                   11762:                         }
                   11763:                     }
                   11764:                 }
                   11765:                 if ($slots{$slot}->{'allowedusers'}) {
                   11766:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11767:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11768:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11769:                         $userallowed = 1;
                   11770:                     }
                   11771:                 }
                   11772:                 next unless($userallowed);
                   11773:             }
                   11774:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11775:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11776:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  11777:             my $uniqueperiod;
                   11778:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11779:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11780:             }
1.1040    raeburn  11781:             if (($startreserve < $now) &&
                   11782:                 (!$endreserve || $endreserve > $now)) {
                   11783:                 my $lastres = $endreserve;
                   11784:                 if (!$lastres) {
                   11785:                     $lastres = $slots{$slot}->{'starttime'};
                   11786:                 }
                   11787:                 $reservable_now{$slot} = {
                   11788:                                            symb       => $symb,
1.1250    raeburn  11789:                                            endreserve => $lastres,
                   11790:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  11791:                                          };
                   11792:             } elsif (($startreserve > $now) &&
                   11793:                      (!$endreserve || $endreserve > $startreserve)) {
                   11794:                 $future_reservable{$slot} = {
                   11795:                                               symb         => $symb,
1.1250    raeburn  11796:                                               startreserve => $startreserve,
                   11797:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11798:                                             };
                   11799:             }
                   11800:         }
                   11801:     }
                   11802:     my @unsorted_reservable = keys(%reservable_now);
                   11803:     if (@unsorted_reservable > 0) {
                   11804:         @sorted_reservable = 
                   11805:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11806:     }
                   11807:     my @unsorted_future = keys(%future_reservable);
                   11808:     if (@unsorted_future > 0) {
                   11809:         @sorted_future =
                   11810:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11811:     }
                   11812:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11813: }
1.780     raeburn  11814: 
                   11815: =pod
                   11816: 
1.1057    foxr     11817: =back
                   11818: 
1.549     albertel 11819: =head1 HTTP Helpers
                   11820: 
                   11821: =over 4
                   11822: 
1.648     raeburn  11823: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11824: 
1.258     albertel 11825: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11826: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11827: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11828: 
                   11829: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11830: $possible_names is an ref to an array of form element names.  As an example:
                   11831: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11832: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11833: 
                   11834: =cut
1.1       albertel 11835: 
1.6       albertel 11836: sub get_unprocessed_cgi {
1.25      albertel 11837:   my ($query,$possible_names)= @_;
1.26      matthew  11838:   # $Apache::lonxml::debug=1;
1.356     albertel 11839:   foreach my $pair (split(/&/,$query)) {
                   11840:     my ($name, $value) = split(/=/,$pair);
1.369     www      11841:     $name = &unescape($name);
1.25      albertel 11842:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11843:       $value =~ tr/+/ /;
                   11844:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11845:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11846:     }
1.16      harris41 11847:   }
1.6       albertel 11848: }
                   11849: 
1.112     bowersj2 11850: =pod
                   11851: 
1.648     raeburn  11852: =item * &cacheheader() 
1.112     bowersj2 11853: 
                   11854: returns cache-controlling header code
                   11855: 
                   11856: =cut
                   11857: 
1.7       albertel 11858: sub cacheheader {
1.258     albertel 11859:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11860:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11861:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11862:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11863:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11864:     return $output;
1.7       albertel 11865: }
                   11866: 
1.112     bowersj2 11867: =pod
                   11868: 
1.648     raeburn  11869: =item * &no_cache($r) 
1.112     bowersj2 11870: 
                   11871: specifies header code to not have cache
                   11872: 
                   11873: =cut
                   11874: 
1.9       albertel 11875: sub no_cache {
1.216     albertel 11876:     my ($r) = @_;
                   11877:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11878: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11879:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11880:     $r->no_cache(1);
                   11881:     $r->header_out("Expires" => $date);
                   11882:     $r->header_out("Pragma" => "no-cache");
1.123     www      11883: }
                   11884: 
                   11885: sub content_type {
1.181     albertel 11886:     my ($r,$type,$charset) = @_;
1.299     foxr     11887:     if ($r) {
                   11888: 	#  Note that printout.pl calls this with undef for $r.
                   11889: 	&no_cache($r);
                   11890:     }
1.258     albertel 11891:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11892:     unless ($charset) {
                   11893: 	$charset=&Apache::lonlocal::current_encoding;
                   11894:     }
                   11895:     if ($charset) { $type.='; charset='.$charset; }
                   11896:     if ($r) {
                   11897: 	$r->content_type($type);
                   11898:     } else {
                   11899: 	print("Content-type: $type\n\n");
                   11900:     }
1.9       albertel 11901: }
1.25      albertel 11902: 
1.112     bowersj2 11903: =pod
                   11904: 
1.648     raeburn  11905: =item * &add_to_env($name,$value) 
1.112     bowersj2 11906: 
1.258     albertel 11907: adds $name to the %env hash with value
1.112     bowersj2 11908: $value, if $name already exists, the entry is converted to an array
                   11909: reference and $value is added to the array.
                   11910: 
                   11911: =cut
                   11912: 
1.25      albertel 11913: sub add_to_env {
                   11914:   my ($name,$value)=@_;
1.258     albertel 11915:   if (defined($env{$name})) {
                   11916:     if (ref($env{$name})) {
1.25      albertel 11917:       #already have multiple values
1.258     albertel 11918:       push(@{ $env{$name} },$value);
1.25      albertel 11919:     } else {
                   11920:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11921:       my $first=$env{$name};
                   11922:       undef($env{$name});
                   11923:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11924:     }
                   11925:   } else {
1.258     albertel 11926:     $env{$name}=$value;
1.25      albertel 11927:   }
1.31      albertel 11928: }
1.149     albertel 11929: 
                   11930: =pod
                   11931: 
1.648     raeburn  11932: =item * &get_env_multiple($name) 
1.149     albertel 11933: 
1.258     albertel 11934: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11935: values may be defined and end up as an array ref.
                   11936: 
                   11937: returns an array of values
                   11938: 
                   11939: =cut
                   11940: 
                   11941: sub get_env_multiple {
                   11942:     my ($name) = @_;
                   11943:     my @values;
1.258     albertel 11944:     if (defined($env{$name})) {
1.149     albertel 11945:         # exists is it an array
1.258     albertel 11946:         if (ref($env{$name})) {
                   11947:             @values=@{ $env{$name} };
1.149     albertel 11948:         } else {
1.258     albertel 11949:             $values[0]=$env{$name};
1.149     albertel 11950:         }
                   11951:     }
                   11952:     return(@values);
                   11953: }
                   11954: 
1.1249    damieng  11955: # Looks at given dependencies, and returns something depending on the context.
                   11956: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   11957: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   11958: # For all other contexts, returns ($output, $counter, $numpathchg).
                   11959: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   11960: # $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.
                   11961: # $numpathchg: integer with the number of cleaned up dependency paths.
                   11962: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   11963: # \%mapping: hash reference clean path -> original path for all dependencies.
                   11964: # @param {string} actionurl - The path to the handler, indicative of the context.
                   11965: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   11966: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   11967: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   11968: # @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)
                   11969: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  11970: sub ask_for_embedded_content {
1.1249    damieng  11971:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  11972:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11973:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  11974:         %currsubfile,%unused,$rem);
1.1071    raeburn  11975:     my $counter = 0;
                   11976:     my $numnew = 0;
1.987     raeburn  11977:     my $numremref = 0;
                   11978:     my $numinvalid = 0;
                   11979:     my $numpathchg = 0;
                   11980:     my $numexisting = 0;
1.1071    raeburn  11981:     my $numunused = 0;
                   11982:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  11983:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11984:     my $heading = &mt('Upload embedded files');
                   11985:     my $buttontext = &mt('Upload');
                   11986: 
1.1249    damieng  11987:     # fills these variables based on the context:
                   11988:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   11989:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  11990:     if ($env{'request.course.id'}) {
1.1123    raeburn  11991:         if ($actionurl eq '/adm/dependencies') {
                   11992:             $navmap = Apache::lonnavmaps::navmap->new();
                   11993:         }
                   11994:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11995:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  11996:     }
1.1123    raeburn  11997:     if (($actionurl eq '/adm/portfolio') || 
                   11998:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11999:         my $current_path='/';
                   12000:         if ($env{'form.currentpath'}) {
                   12001:             $current_path = $env{'form.currentpath'};
                   12002:         }
                   12003:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12004:             $udom = $cdom;
                   12005:             $uname = $cnum;
1.984     raeburn  12006:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12007:         } else {
                   12008:             $udom = $env{'user.domain'};
                   12009:             $uname = $env{'user.name'};
                   12010:             $url = '/userfiles/portfolio';
                   12011:         }
1.987     raeburn  12012:         $toplevel = $url.'/';
1.984     raeburn  12013:         $url .= $current_path;
                   12014:         $getpropath = 1;
1.987     raeburn  12015:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12016:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12017:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12018:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12019:         $toplevel = $url;
1.984     raeburn  12020:         if ($rest ne '') {
1.987     raeburn  12021:             $url .= $rest;
                   12022:         }
                   12023:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12024:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12025:             $url = $args->{'docs_url'};
                   12026:             $toplevel = $url;
1.1084    raeburn  12027:             if ($args->{'context'} eq 'paste') {
                   12028:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12029:                 ($path) = 
                   12030:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12031:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12032:                 $fileloc =~ s{^/}{};
                   12033:             }
1.1071    raeburn  12034:         }
1.1084    raeburn  12035:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12036:         if ($env{'request.course.id'} ne '') {
                   12037:             if (ref($args) eq 'HASH') {
                   12038:                 $url = $args->{'docs_url'};
                   12039:                 $title = $args->{'docs_title'};
1.1126    raeburn  12040:                 $toplevel = $url; 
                   12041:                 unless ($toplevel =~ m{^/}) {
                   12042:                     $toplevel = "/$url";
                   12043:                 }
1.1085    raeburn  12044:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12045:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12046:                     $path = $1;
                   12047:                 } else {
                   12048:                     ($path) =
                   12049:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12050:                 }
1.1195    raeburn  12051:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12052:                     $fileloc = $toplevel;
                   12053:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12054:                     my ($udom,$uname,$fname) =
                   12055:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12056:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12057:                 } else {
                   12058:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12059:                 }
1.1071    raeburn  12060:                 $fileloc =~ s{^/}{};
                   12061:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12062:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12063:             }
1.987     raeburn  12064:         }
1.1123    raeburn  12065:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12066:         $udom = $cdom;
                   12067:         $uname = $cnum;
                   12068:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12069:         $toplevel = $url;
                   12070:         $path = $url;
                   12071:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12072:         $fileloc =~ s{^/}{};
1.987     raeburn  12073:     }
1.1249    damieng  12074:     
                   12075:     # parses the dependency paths to get some info
                   12076:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12077:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12078:     # (will be completed later)
                   12079:     # $mapping:
                   12080:     #   for external URLs: external URL -> external URL
                   12081:     #   for relative paths: clean path -> original path
                   12082:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12083:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12084:     foreach my $file (keys(%{$allfiles})) {
                   12085:         my $embed_file;
                   12086:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12087:             $embed_file = $1;
                   12088:         } else {
                   12089:             $embed_file = $file;
                   12090:         }
1.1158    raeburn  12091:         my ($absolutepath,$cleaned_file);
                   12092:         if ($embed_file =~ m{^\w+://}) {
                   12093:             $cleaned_file = $embed_file;
1.1147    raeburn  12094:             $newfiles{$cleaned_file} = 1;
                   12095:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12096:         } else {
1.1158    raeburn  12097:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12098:             if ($embed_file =~ m{^/}) {
                   12099:                 $absolutepath = $embed_file;
                   12100:             }
1.1147    raeburn  12101:             if ($cleaned_file =~ m{/}) {
                   12102:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12103:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12104:                 my $item = $fname;
                   12105:                 if ($path ne '') {
                   12106:                     $item = $path.'/'.$fname;
                   12107:                     $subdependencies{$path}{$fname} = 1;
                   12108:                 } else {
                   12109:                     $dependencies{$item} = 1;
                   12110:                 }
                   12111:                 if ($absolutepath) {
                   12112:                     $mapping{$item} = $absolutepath;
                   12113:                 } else {
                   12114:                     $mapping{$item} = $embed_file;
                   12115:                 }
                   12116:             } else {
                   12117:                 $dependencies{$embed_file} = 1;
                   12118:                 if ($absolutepath) {
1.1147    raeburn  12119:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12120:                 } else {
1.1147    raeburn  12121:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12122:                 }
                   12123:             }
1.984     raeburn  12124:         }
                   12125:     }
1.1249    damieng  12126:     
                   12127:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12128:     # and lists
                   12129:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12130:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12131:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12132:     #                                    the path had to be cleaned up
                   12133:     # $existing: hash clean path -> 1 if the file exists
                   12134:     # $numexisting: number of keys in $existing
                   12135:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12136:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12137:     #                                      dependency subdirectories that are
                   12138:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12139:     my $dirptr = 16384;
1.984     raeburn  12140:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12141:         $currsubfile{$path} = {};
1.1123    raeburn  12142:         if (($actionurl eq '/adm/portfolio') || 
                   12143:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12144:             my ($sublistref,$listerror) =
                   12145:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12146:             if (ref($sublistref) eq 'ARRAY') {
                   12147:                 foreach my $line (@{$sublistref}) {
                   12148:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12149:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12150:                 }
1.984     raeburn  12151:             }
1.987     raeburn  12152:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12153:             if (opendir(my $dir,$url.'/'.$path)) {
                   12154:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12155:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12156:             }
1.1084    raeburn  12157:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12158:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12159:                   ($args->{'context'} eq 'paste')) ||
                   12160:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12161:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12162:                 my $dir;
                   12163:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12164:                     $dir = $fileloc;
                   12165:                 } else {
                   12166:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12167:                 }
1.1071    raeburn  12168:                 if ($dir ne '') {
                   12169:                     my ($sublistref,$listerror) =
                   12170:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12171:                     if (ref($sublistref) eq 'ARRAY') {
                   12172:                         foreach my $line (@{$sublistref}) {
                   12173:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12174:                                 undef,$mtime)=split(/\&/,$line,12);
                   12175:                             unless (($testdir&$dirptr) ||
                   12176:                                     ($file_name =~ /^\.\.?$/)) {
                   12177:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12178:                             }
                   12179:                         }
                   12180:                     }
                   12181:                 }
1.984     raeburn  12182:             }
                   12183:         }
                   12184:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12185:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12186:                 my $item = $path.'/'.$file;
                   12187:                 unless ($mapping{$item} eq $item) {
                   12188:                     $pathchanges{$item} = 1;
                   12189:                 }
                   12190:                 $existing{$item} = 1;
                   12191:                 $numexisting ++;
                   12192:             } else {
                   12193:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12194:             }
                   12195:         }
1.1071    raeburn  12196:         if ($actionurl eq '/adm/dependencies') {
                   12197:             foreach my $path (keys(%currsubfile)) {
                   12198:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12199:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12200:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12201:                              next if (($rem ne '') &&
                   12202:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12203:                                        (ref($navmap) &&
                   12204:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12205:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12206:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12207:                              $unused{$path.'/'.$file} = 1; 
                   12208:                          }
                   12209:                     }
                   12210:                 }
                   12211:             }
                   12212:         }
1.984     raeburn  12213:     }
1.1249    damieng  12214:     
                   12215:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12216:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12217:     my %currfile;
1.1123    raeburn  12218:     if (($actionurl eq '/adm/portfolio') ||
                   12219:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12220:         my ($dirlistref,$listerror) =
                   12221:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12222:         if (ref($dirlistref) eq 'ARRAY') {
                   12223:             foreach my $line (@{$dirlistref}) {
                   12224:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12225:                 $currfile{$file_name} = 1;
                   12226:             }
1.984     raeburn  12227:         }
1.987     raeburn  12228:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12229:         if (opendir(my $dir,$url)) {
1.987     raeburn  12230:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12231:             map {$currfile{$_} = 1;} @dir_list;
                   12232:         }
1.1084    raeburn  12233:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12234:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12235:               ($args->{'context'} eq 'paste')) ||
                   12236:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12237:         if ($env{'request.course.id'} ne '') {
                   12238:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12239:             if ($dir ne '') {
                   12240:                 my ($dirlistref,$listerror) =
                   12241:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12242:                 if (ref($dirlistref) eq 'ARRAY') {
                   12243:                     foreach my $line (@{$dirlistref}) {
                   12244:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12245:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12246:                         unless (($testdir&$dirptr) ||
                   12247:                                 ($file_name =~ /^\.\.?$/)) {
                   12248:                             $currfile{$file_name} = [$size,$mtime];
                   12249:                         }
                   12250:                     }
                   12251:                 }
                   12252:             }
                   12253:         }
1.984     raeburn  12254:     }
1.1249    damieng  12255:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12256:     # are not in subdirectories, using $currfile
1.984     raeburn  12257:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12258:         if (exists($currfile{$file})) {
1.987     raeburn  12259:             unless ($mapping{$file} eq $file) {
                   12260:                 $pathchanges{$file} = 1;
                   12261:             }
                   12262:             $existing{$file} = 1;
                   12263:             $numexisting ++;
                   12264:         } else {
1.984     raeburn  12265:             $newfiles{$file} = 1;
                   12266:         }
                   12267:     }
1.1071    raeburn  12268:     foreach my $file (keys(%currfile)) {
                   12269:         unless (($file eq $filename) ||
                   12270:                 ($file eq $filename.'.bak') ||
                   12271:                 ($dependencies{$file})) {
1.1085    raeburn  12272:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12273:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12274:                     next if (($rem ne '') &&
                   12275:                              (($env{"httpref.$rem".$file} ne '') ||
                   12276:                               (ref($navmap) &&
                   12277:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12278:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12279:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12280:                 }
1.1085    raeburn  12281:             }
1.1071    raeburn  12282:             $unused{$file} = 1;
                   12283:         }
                   12284:     }
1.1249    damieng  12285:     
                   12286:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12287:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12288:         ($args->{'context'} eq 'paste')) {
                   12289:         $counter = scalar(keys(%existing));
                   12290:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12291:         return ($output,$counter,$numpathchg,\%existing);
                   12292:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12293:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12294:         $counter = scalar(keys(%existing));
                   12295:         $numpathchg = scalar(keys(%pathchanges));
                   12296:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12297:     }
1.1249    damieng  12298:     
                   12299:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12300:     
                   12301:     # $upload_output: missing dependencies (with upload form)
                   12302:     # $modify_output: uploaded dependencies (in use)
                   12303:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12304:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12305:         if ($actionurl eq '/adm/dependencies') {
                   12306:             next if ($embed_file =~ m{^\w+://});
                   12307:         }
1.660     raeburn  12308:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12309:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12310:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12311:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12312:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12313:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12314:         }
1.1123    raeburn  12315:         $upload_output .= '</td>';
1.1071    raeburn  12316:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12317:             $upload_output.='<td align="right">'.
                   12318:                             '<span class="LC_info LC_fontsize_medium">'.
                   12319:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12320:             $numremref++;
1.660     raeburn  12321:         } elsif ($args->{'error_on_invalid_names'}
                   12322:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12323:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12324:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12325:             $numinvalid++;
1.660     raeburn  12326:         } else {
1.1123    raeburn  12327:             $upload_output .= '<td>'.
                   12328:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12329:                                                      $embed_file,\%mapping,
1.1071    raeburn  12330:                                                      $allfiles,$codebase,'upload');
                   12331:             $counter ++;
                   12332:             $numnew ++;
1.987     raeburn  12333:         }
                   12334:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12335:     }
                   12336:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12337:         if ($actionurl eq '/adm/dependencies') {
                   12338:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12339:             $modify_output .= &start_data_table_row().
                   12340:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12341:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12342:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12343:                               '<td>'.$size.'</td>'.
                   12344:                               '<td>'.$mtime.'</td>'.
                   12345:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12346:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12347:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12348:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12349:                               &embedded_file_element('upload_embedded',$counter,
                   12350:                                                      $embed_file,\%mapping,
                   12351:                                                      $allfiles,$codebase,'modify').
                   12352:                               '</div></td>'.
                   12353:                               &end_data_table_row()."\n";
                   12354:             $counter ++;
                   12355:         } else {
                   12356:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12357:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12358:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12359:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12360:                               &Apache::loncommon::end_data_table_row()."\n";
                   12361:         }
                   12362:     }
                   12363:     my $delidx = $counter;
                   12364:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12365:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12366:         $delete_output .= &start_data_table_row().
                   12367:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12368:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12369:                           '<td>'.$size.'</td>'.
                   12370:                           '<td>'.$mtime.'</td>'.
                   12371:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12372:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12373:                           &embedded_file_element('upload_embedded',$delidx,
                   12374:                                                  $oldfile,\%mapping,$allfiles,
                   12375:                                                  $codebase,'delete').'</td>'.
                   12376:                           &end_data_table_row()."\n"; 
                   12377:         $numunused ++;
                   12378:         $delidx ++;
1.987     raeburn  12379:     }
                   12380:     if ($upload_output) {
                   12381:         $upload_output = &start_data_table().
                   12382:                          $upload_output.
                   12383:                          &end_data_table()."\n";
                   12384:     }
1.1071    raeburn  12385:     if ($modify_output) {
                   12386:         $modify_output = &start_data_table().
                   12387:                          &start_data_table_header_row().
                   12388:                          '<th>'.&mt('File').'</th>'.
                   12389:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12390:                          '<th>'.&mt('Modified').'</th>'.
                   12391:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12392:                          &end_data_table_header_row().
                   12393:                          $modify_output.
                   12394:                          &end_data_table()."\n";
                   12395:     }
                   12396:     if ($delete_output) {
                   12397:         $delete_output = &start_data_table().
                   12398:                          &start_data_table_header_row().
                   12399:                          '<th>'.&mt('File').'</th>'.
                   12400:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12401:                          '<th>'.&mt('Modified').'</th>'.
                   12402:                          '<th>'.&mt('Delete?').'</th>'.
                   12403:                          &end_data_table_header_row().
                   12404:                          $delete_output.
                   12405:                          &end_data_table()."\n";
                   12406:     }
1.987     raeburn  12407:     my $applies = 0;
                   12408:     if ($numremref) {
                   12409:         $applies ++;
                   12410:     }
                   12411:     if ($numinvalid) {
                   12412:         $applies ++;
                   12413:     }
                   12414:     if ($numexisting) {
                   12415:         $applies ++;
                   12416:     }
1.1071    raeburn  12417:     if ($counter || $numunused) {
1.987     raeburn  12418:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12419:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12420:                   $state.'<h3>'.$heading.'</h3>'; 
                   12421:         if ($actionurl eq '/adm/dependencies') {
                   12422:             if ($numnew) {
                   12423:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12424:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12425:                            $upload_output.'<br />'."\n";
                   12426:             }
                   12427:             if ($numexisting) {
                   12428:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12429:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12430:                            $modify_output.'<br />'."\n";
                   12431:                            $buttontext = &mt('Save changes');
                   12432:             }
                   12433:             if ($numunused) {
                   12434:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12435:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12436:                            $delete_output.'<br />'."\n";
                   12437:                            $buttontext = &mt('Save changes');
                   12438:             }
                   12439:         } else {
                   12440:             $output .= $upload_output.'<br />'."\n";
                   12441:         }
                   12442:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12443:                    $counter.'" />'."\n";
                   12444:         if ($actionurl eq '/adm/dependencies') { 
                   12445:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12446:                        $numnew.'" />'."\n";
                   12447:         } elsif ($actionurl eq '') {
1.987     raeburn  12448:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12449:         }
                   12450:     } elsif ($applies) {
                   12451:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12452:         if ($applies > 1) {
                   12453:             $output .=  
1.1123    raeburn  12454:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12455:             if ($numremref) {
                   12456:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12457:             }
                   12458:             if ($numinvalid) {
                   12459:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12460:             }
                   12461:             if ($numexisting) {
                   12462:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12463:             }
                   12464:             $output .= '</ul><br />';
                   12465:         } elsif ($numremref) {
                   12466:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12467:         } elsif ($numinvalid) {
                   12468:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12469:         } elsif ($numexisting) {
                   12470:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12471:         }
                   12472:         $output .= $upload_output.'<br />';
                   12473:     }
                   12474:     my ($pathchange_output,$chgcount);
1.1071    raeburn  12475:     $chgcount = $counter;
1.987     raeburn  12476:     if (keys(%pathchanges) > 0) {
                   12477:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  12478:             if ($counter) {
1.987     raeburn  12479:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   12480:                                                   $embed_file,\%mapping,
1.1071    raeburn  12481:                                                   $allfiles,$codebase,'change');
1.987     raeburn  12482:             } else {
                   12483:                 $pathchange_output .= 
                   12484:                     &start_data_table_row().
                   12485:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12486:                     $chgcount.'" checked="checked" /></td>'.
                   12487:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12488:                     '<td>'.$embed_file.
                   12489:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12490:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12491:                     '</td>'.&end_data_table_row();
1.660     raeburn  12492:             }
1.987     raeburn  12493:             $numpathchg ++;
                   12494:             $chgcount ++;
1.660     raeburn  12495:         }
                   12496:     }
1.1127    raeburn  12497:     if (($counter) || ($numunused)) {
1.987     raeburn  12498:         if ($numpathchg) {
                   12499:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12500:                        $numpathchg.'" />'."\n";
                   12501:         }
                   12502:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12503:             ($actionurl eq '/adm/imsimport')) {
                   12504:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12505:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12506:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12507:         } elsif ($actionurl eq '/adm/dependencies') {
                   12508:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12509:         }
1.1123    raeburn  12510:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12511:     } elsif ($numpathchg) {
                   12512:         my %pathchange = ();
                   12513:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12514:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12515:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  12516:         }
1.987     raeburn  12517:     }
1.1071    raeburn  12518:     return ($output,$counter,$numpathchg);
1.987     raeburn  12519: }
                   12520: 
1.1147    raeburn  12521: =pod
                   12522: 
                   12523: =item * clean_path($name)
                   12524: 
                   12525: Performs clean-up of directories, subdirectories and filename in an
                   12526: embedded object, referenced in an HTML file which is being uploaded
                   12527: to a course or portfolio, where 
                   12528: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12529: checked.
                   12530: 
                   12531: Clean-up is similar to replacements in lonnet::clean_filename()
                   12532: except each / between sub-directory and next level is preserved.
                   12533: 
                   12534: =cut
                   12535: 
                   12536: sub clean_path {
                   12537:     my ($embed_file) = @_;
                   12538:     $embed_file =~s{^/+}{};
                   12539:     my @contents;
                   12540:     if ($embed_file =~ m{/}) {
                   12541:         @contents = split(/\//,$embed_file);
                   12542:     } else {
                   12543:         @contents = ($embed_file);
                   12544:     }
                   12545:     my $lastidx = scalar(@contents)-1;
                   12546:     for (my $i=0; $i<=$lastidx; $i++) { 
                   12547:         $contents[$i]=~s{\\}{/}g;
                   12548:         $contents[$i]=~s/\s+/\_/g;
                   12549:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12550:         if ($i == $lastidx) {
                   12551:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12552:         }
                   12553:     }
                   12554:     if ($lastidx > 0) {
                   12555:         return join('/',@contents);
                   12556:     } else {
                   12557:         return $contents[0];
                   12558:     }
                   12559: }
                   12560: 
1.987     raeburn  12561: sub embedded_file_element {
1.1071    raeburn  12562:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12563:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12564:                    (ref($codebase) eq 'HASH'));
                   12565:     my $output;
1.1071    raeburn  12566:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12567:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12568:     }
                   12569:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12570:                &escape($embed_file).'" />';
                   12571:     unless (($context eq 'upload_embedded') && 
                   12572:             ($mapping->{$embed_file} eq $embed_file)) {
                   12573:         $output .='
                   12574:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12575:     }
                   12576:     my $attrib;
                   12577:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12578:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12579:     }
                   12580:     $output .=
                   12581:         "\n\t\t".
                   12582:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12583:         $attrib.'" />';
                   12584:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12585:         $output .=
                   12586:             "\n\t\t".
                   12587:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12588:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12589:     }
1.987     raeburn  12590:     return $output;
1.660     raeburn  12591: }
                   12592: 
1.1071    raeburn  12593: sub get_dependency_details {
                   12594:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12595:     my ($size,$mtime,$showsize,$showmtime);
                   12596:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12597:         if ($embed_file =~ m{/}) {
                   12598:             my ($path,$fname) = split(/\//,$embed_file);
                   12599:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12600:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12601:             }
                   12602:         } else {
                   12603:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12604:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12605:             }
                   12606:         }
                   12607:         $showsize = $size/1024.0;
                   12608:         $showsize = sprintf("%.1f",$showsize);
                   12609:         if ($mtime > 0) {
                   12610:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12611:         }
                   12612:     }
                   12613:     return ($showsize,$showmtime);
                   12614: }
                   12615: 
                   12616: sub ask_embedded_js {
                   12617:     return <<"END";
                   12618: <script type="text/javascript"">
                   12619: // <![CDATA[
                   12620: function toggleBrowse(counter) {
                   12621:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12622:     var fileid = document.getElementById('embedded_item_'+counter);
                   12623:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12624:     if (chkboxid.checked == true) {
                   12625:         uploaddivid.style.display='block';
                   12626:     } else {
                   12627:         uploaddivid.style.display='none';
                   12628:         fileid.value = '';
                   12629:     }
                   12630: }
                   12631: // ]]>
                   12632: </script>
                   12633: 
                   12634: END
                   12635: }
                   12636: 
1.661     raeburn  12637: sub upload_embedded {
                   12638:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12639:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12640:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12641:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12642:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12643:         my $orig_uploaded_filename =
                   12644:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12645:         foreach my $type ('orig','ref','attrib','codebase') {
                   12646:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12647:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12648:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12649:             }
                   12650:         }
1.661     raeburn  12651:         my ($path,$fname) =
                   12652:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12653:         # no path, whole string is fname
                   12654:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12655:         $fname = &Apache::lonnet::clean_filename($fname);
                   12656:         # See if there is anything left
                   12657:         next if ($fname eq '');
                   12658: 
                   12659:         # Check if file already exists as a file or directory.
                   12660:         my ($state,$msg);
                   12661:         if ($context eq 'portfolio') {
                   12662:             my $port_path = $dirpath;
                   12663:             if ($group ne '') {
                   12664:                 $port_path = "groups/$group/$port_path";
                   12665:             }
1.987     raeburn  12666:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12667:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12668:                                               $dir_root,$port_path,$disk_quota,
                   12669:                                               $current_disk_usage,$uname,$udom);
                   12670:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12671:                 || $state eq 'file_locked') {
1.661     raeburn  12672:                 $output .= $msg;
                   12673:                 next;
                   12674:             }
                   12675:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12676:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12677:             if ($state eq 'exists') {
                   12678:                 $output .= $msg;
                   12679:                 next;
                   12680:             }
                   12681:         }
                   12682:         # Check if extension is valid
                   12683:         if (($fname =~ /\.(\w+)$/) &&
                   12684:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   12685:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12686:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12687:             next;
                   12688:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12689:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12690:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12691:             next;
                   12692:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   12693:             $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  12694:             next;
                   12695:         }
                   12696:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  12697:         my $subdir = $path;
                   12698:         $subdir =~ s{/+$}{};
1.661     raeburn  12699:         if ($context eq 'portfolio') {
1.984     raeburn  12700:             my $result;
                   12701:             if ($state eq 'existingfile') {
                   12702:                 $result=
                   12703:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  12704:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12705:             } else {
1.984     raeburn  12706:                 $result=
                   12707:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12708:                                                     $dirpath.
1.1123    raeburn  12709:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12710:                 if ($result !~ m|^/uploaded/|) {
                   12711:                     $output .= '<span class="LC_error">'
                   12712:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12713:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12714:                                .'</span><br />';
                   12715:                     next;
                   12716:                 } else {
1.987     raeburn  12717:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12718:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12719:                 }
1.661     raeburn  12720:             }
1.1123    raeburn  12721:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  12722:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12723:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12724:             my $result =
1.1126    raeburn  12725:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12726:             if ($result !~ m|^/uploaded/|) {
                   12727:                 $output .= '<span class="LC_error">'
                   12728:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12729:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12730:                            .'</span><br />';
                   12731:                     next;
                   12732:             } else {
                   12733:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12734:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  12735:                 if ($context eq 'syllabus') {
                   12736:                     &Apache::lonnet::make_public_indefinitely($result);
                   12737:                 }
1.987     raeburn  12738:             }
1.661     raeburn  12739:         } else {
                   12740: # Save the file
                   12741:             my $target = $env{'form.embedded_item_'.$i};
                   12742:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12743:             my $dest = $fullpath.$fname;
                   12744:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12745:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12746:             my $count;
                   12747:             my $filepath = $dir_root;
1.1027    raeburn  12748:             foreach my $subdir (@parts) {
                   12749:                 $filepath .= "/$subdir";
                   12750:                 if (!-e $filepath) {
1.661     raeburn  12751:                     mkdir($filepath,0770);
                   12752:                 }
                   12753:             }
                   12754:             my $fh;
                   12755:             if (!open($fh,'>'.$dest)) {
                   12756:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12757:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12758:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12759:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12760:                            '</span><br />';
                   12761:             } else {
                   12762:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12763:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12764:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12765:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12766:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12767:                               '</span><br />';
                   12768:                 } else {
1.987     raeburn  12769:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12770:                                $url.'</span>').'<br />';
                   12771:                     unless ($context eq 'testbank') {
                   12772:                         $footer .= &mt('View embedded file: [_1]',
                   12773:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12774:                     }
                   12775:                 }
                   12776:                 close($fh);
                   12777:             }
                   12778:         }
                   12779:         if ($env{'form.embedded_ref_'.$i}) {
                   12780:             $pathchange{$i} = 1;
                   12781:         }
                   12782:     }
                   12783:     if ($output) {
                   12784:         $output = '<p>'.$output.'</p>';
                   12785:     }
                   12786:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12787:     $returnflag = 'ok';
1.1071    raeburn  12788:     my $numpathchgs = scalar(keys(%pathchange));
                   12789:     if ($numpathchgs > 0) {
1.987     raeburn  12790:         if ($context eq 'portfolio') {
                   12791:             $output .= '<p>'.&mt('or').'</p>';
                   12792:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12793:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12794:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12795:             $returnflag = 'modify_orightml';
                   12796:         }
                   12797:     }
1.1071    raeburn  12798:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12799: }
                   12800: 
                   12801: sub modify_html_form {
                   12802:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12803:     my $end = 0;
                   12804:     my $modifyform;
                   12805:     if ($context eq 'upload_embedded') {
                   12806:         return unless (ref($pathchange) eq 'HASH');
                   12807:         if ($env{'form.number_embedded_items'}) {
                   12808:             $end += $env{'form.number_embedded_items'};
                   12809:         }
                   12810:         if ($env{'form.number_pathchange_items'}) {
                   12811:             $end += $env{'form.number_pathchange_items'};
                   12812:         }
                   12813:         if ($end) {
                   12814:             for (my $i=0; $i<$end; $i++) {
                   12815:                 if ($i < $env{'form.number_embedded_items'}) {
                   12816:                     next unless($pathchange->{$i});
                   12817:                 }
                   12818:                 $modifyform .=
                   12819:                     &start_data_table_row().
                   12820:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12821:                     'checked="checked" /></td>'.
                   12822:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12823:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12824:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12825:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12826:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12827:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12828:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12829:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12830:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12831:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12832:                     &end_data_table_row();
1.1071    raeburn  12833:             }
1.987     raeburn  12834:         }
                   12835:     } else {
                   12836:         $modifyform = $pathchgtable;
                   12837:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12838:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12839:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12840:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12841:         }
                   12842:     }
                   12843:     if ($modifyform) {
1.1071    raeburn  12844:         if ($actionurl eq '/adm/dependencies') {
                   12845:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12846:         }
1.987     raeburn  12847:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12848:                '<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".
                   12849:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12850:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12851:                '</ol></p>'."\n".'<p>'.
                   12852:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12853:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12854:                &start_data_table()."\n".
                   12855:                &start_data_table_header_row().
                   12856:                '<th>'.&mt('Change?').'</th>'.
                   12857:                '<th>'.&mt('Current reference').'</th>'.
                   12858:                '<th>'.&mt('Required reference').'</th>'.
                   12859:                &end_data_table_header_row()."\n".
                   12860:                $modifyform.
                   12861:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12862:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12863:                '</form>'."\n";
                   12864:     }
                   12865:     return;
                   12866: }
                   12867: 
                   12868: sub modify_html_refs {
1.1123    raeburn  12869:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12870:     my $container;
                   12871:     if ($context eq 'portfolio') {
                   12872:         $container = $env{'form.container'};
                   12873:     } elsif ($context eq 'coursedoc') {
                   12874:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12875:     } elsif ($context eq 'manage_dependencies') {
                   12876:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12877:         $container = "/$container";
1.1123    raeburn  12878:     } elsif ($context eq 'syllabus') {
                   12879:         $container = $url;
1.987     raeburn  12880:     } else {
1.1027    raeburn  12881:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12882:     }
                   12883:     my (%allfiles,%codebase,$output,$content);
                   12884:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  12885:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  12886:         if (wantarray) {
                   12887:             return ('',0,0); 
                   12888:         } else {
                   12889:             return;
                   12890:         }
                   12891:     }
                   12892:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12893:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12894:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12895:             if (wantarray) {
                   12896:                 return ('',0,0);
                   12897:             } else {
                   12898:                 return;
                   12899:             }
                   12900:         } 
1.987     raeburn  12901:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12902:         if ($content eq '-1') {
                   12903:             if (wantarray) {
                   12904:                 return ('',0,0);
                   12905:             } else {
                   12906:                 return;
                   12907:             }
                   12908:         }
1.987     raeburn  12909:     } else {
1.1071    raeburn  12910:         unless ($container =~ /^\Q$dir_root\E/) {
                   12911:             if (wantarray) {
                   12912:                 return ('',0,0);
                   12913:             } else {
                   12914:                 return;
                   12915:             }
                   12916:         } 
1.1317    raeburn  12917:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12918:             $content = join('', <$fh>);
                   12919:             close($fh);
                   12920:         } else {
1.1071    raeburn  12921:             if (wantarray) {
                   12922:                 return ('',0,0);
                   12923:             } else {
                   12924:                 return;
                   12925:             }
1.987     raeburn  12926:         }
                   12927:     }
                   12928:     my ($count,$codebasecount) = (0,0);
                   12929:     my $mm = new File::MMagic;
                   12930:     my $mime_type = $mm->checktype_contents($content);
                   12931:     if ($mime_type eq 'text/html') {
                   12932:         my $parse_result = 
                   12933:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12934:                                                     \%codebase,\$content);
                   12935:         if ($parse_result eq 'ok') {
                   12936:             foreach my $i (@changes) {
                   12937:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12938:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12939:                 if ($allfiles{$ref}) {
                   12940:                     my $newname =  $orig;
                   12941:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12942:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12943:                     if ($attrib_regexp =~ /:/) {
                   12944:                         $attrib_regexp =~ s/\:/|/g;
                   12945:                     }
                   12946:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12947:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12948:                         $count += $numchg;
1.1123    raeburn  12949:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  12950:                         delete($allfiles{$ref});
1.987     raeburn  12951:                     }
                   12952:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12953:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12954:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12955:                         $codebasecount ++;
                   12956:                     }
                   12957:                 }
                   12958:             }
1.1123    raeburn  12959:             my $skiprewrites;
1.987     raeburn  12960:             if ($count || $codebasecount) {
                   12961:                 my $saveresult;
1.1071    raeburn  12962:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  12963:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12964:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12965:                     if ($url eq $container) {
                   12966:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12967:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12968:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12969:                                             $fname.'</span>').'</p>';
1.987     raeburn  12970:                     } else {
                   12971:                          $output = '<p class="LC_error">'.
                   12972:                                    &mt('Error: update failed for: [_1].',
                   12973:                                    '<span class="LC_filename">'.
                   12974:                                    $container.'</span>').'</p>';
                   12975:                     }
1.1123    raeburn  12976:                     if ($context eq 'syllabus') {
                   12977:                         unless ($saveresult eq 'ok') {
                   12978:                             $skiprewrites = 1;
                   12979:                         }
                   12980:                     }
1.987     raeburn  12981:                 } else {
1.1317    raeburn  12982:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12983:                         print $fh $content;
                   12984:                         close($fh);
                   12985:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12986:                                   $count,'<span class="LC_filename">'.
                   12987:                                   $container.'</span>').'</p>';
1.661     raeburn  12988:                     } else {
1.987     raeburn  12989:                          $output = '<p class="LC_error">'.
                   12990:                                    &mt('Error: could not update [_1].',
                   12991:                                    '<span class="LC_filename">'.
                   12992:                                    $container.'</span>').'</p>';
1.661     raeburn  12993:                     }
                   12994:                 }
                   12995:             }
1.1123    raeburn  12996:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12997:                 my ($actionurl,$state);
                   12998:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12999:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13000:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13001:                                               \%codebase,
                   13002:                                               {'context' => 'rewrites',
                   13003:                                                'ignore_remote_references' => 1,});
                   13004:                 if (ref($mapping) eq 'HASH') {
                   13005:                     my $rewrites = 0;
                   13006:                     foreach my $key (keys(%{$mapping})) {
                   13007:                         next if ($key =~ m{^https?://});
                   13008:                         my $ref = $mapping->{$key};
                   13009:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13010:                         my $attrib;
                   13011:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13012:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13013:                         }
                   13014:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13015:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13016:                             $rewrites += $numchg;
                   13017:                         }
                   13018:                     }
                   13019:                     if ($rewrites) {
                   13020:                         my $saveresult; 
                   13021:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13022:                         if ($url eq $container) {
                   13023:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13024:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13025:                                             $count,'<span class="LC_filename">'.
                   13026:                                             $fname.'</span>').'</p>';
                   13027:                         } else {
                   13028:                             $output .= '<p class="LC_error">'.
                   13029:                                        &mt('Error: could not update links in [_1].',
                   13030:                                        '<span class="LC_filename">'.
                   13031:                                        $container.'</span>').'</p>';
                   13032: 
                   13033:                         }
                   13034:                     }
                   13035:                 }
                   13036:             }
1.987     raeburn  13037:         } else {
                   13038:             &logthis('Failed to parse '.$container.
                   13039:                      ' to modify references: '.$parse_result);
1.661     raeburn  13040:         }
                   13041:     }
1.1071    raeburn  13042:     if (wantarray) {
                   13043:         return ($output,$count,$codebasecount);
                   13044:     } else {
                   13045:         return $output;
                   13046:     }
1.661     raeburn  13047: }
                   13048: 
                   13049: sub check_for_existing {
                   13050:     my ($path,$fname,$element) = @_;
                   13051:     my ($state,$msg);
                   13052:     if (-d $path.'/'.$fname) {
                   13053:         $state = 'exists';
                   13054:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13055:     } elsif (-e $path.'/'.$fname) {
                   13056:         $state = 'exists';
                   13057:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13058:     }
                   13059:     if ($state eq 'exists') {
                   13060:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13061:     }
                   13062:     return ($state,$msg);
                   13063: }
                   13064: 
                   13065: sub check_for_upload {
                   13066:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13067:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13068:     my $filesize = length($env{'form.'.$element});
                   13069:     if (!$filesize) {
                   13070:         my $msg = '<span class="LC_error">'.
                   13071:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13072:                       '<span class="LC_filename">'.$fname.'</span>',
                   13073:                       $filesize).'<br />'.
1.1007    raeburn  13074:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13075:                   '</span>';
                   13076:         return ('zero_bytes',$msg);
                   13077:     }
                   13078:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13079:     my $getpropath = 1;
1.1021    raeburn  13080:     my ($dirlistref,$listerror) =
                   13081:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13082:     my $found_file = 0;
                   13083:     my $locked_file = 0;
1.991     raeburn  13084:     my @lockers;
                   13085:     my $navmap;
                   13086:     if ($env{'request.course.id'}) {
                   13087:         $navmap = Apache::lonnavmaps::navmap->new();
                   13088:     }
1.1021    raeburn  13089:     if (ref($dirlistref) eq 'ARRAY') {
                   13090:         foreach my $line (@{$dirlistref}) {
                   13091:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13092:             if ($file_name eq $fname){
                   13093:                 $file_name = $path.$file_name;
                   13094:                 if ($group ne '') {
                   13095:                     $file_name = $group.$file_name;
                   13096:                 }
                   13097:                 $found_file = 1;
                   13098:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13099:                     foreach my $lock (@lockers) {
                   13100:                         if (ref($lock) eq 'ARRAY') {
                   13101:                             my ($symb,$crsid) = @{$lock};
                   13102:                             if ($crsid eq $env{'request.course.id'}) {
                   13103:                                 if (ref($navmap)) {
                   13104:                                     my $res = $navmap->getBySymb($symb);
                   13105:                                     foreach my $part (@{$res->parts()}) { 
                   13106:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13107:                                         unless (($slot_status == $res->RESERVED) ||
                   13108:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13109:                                             $locked_file = 1;
                   13110:                                         }
1.991     raeburn  13111:                                     }
1.1021    raeburn  13112:                                 } else {
                   13113:                                     $locked_file = 1;
1.991     raeburn  13114:                                 }
                   13115:                             } else {
                   13116:                                 $locked_file = 1;
                   13117:                             }
                   13118:                         }
1.1021    raeburn  13119:                    }
                   13120:                 } else {
                   13121:                     my @info = split(/\&/,$rest);
                   13122:                     my $currsize = $info[6]/1000;
                   13123:                     if ($currsize < $filesize) {
                   13124:                         my $extra = $filesize - $currsize;
                   13125:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13126:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13127:                                       &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   13128:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13129:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13130:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13131:                             return ('will_exceed_quota',$msg);
                   13132:                         }
1.984     raeburn  13133:                     }
                   13134:                 }
1.661     raeburn  13135:             }
                   13136:         }
                   13137:     }
                   13138:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13139:         my $msg = '<p class="LC_warning">'.
                   13140:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13141:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13142:         return ('will_exceed_quota',$msg);
                   13143:     } elsif ($found_file) {
                   13144:         if ($locked_file) {
1.1179    bisitz   13145:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13146:             $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   13147:             $msg .= '</p>';
1.661     raeburn  13148:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13149:             return ('file_locked',$msg);
                   13150:         } else {
1.1179    bisitz   13151:             my $msg = '<p class="LC_error">';
1.984     raeburn  13152:             $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   13153:             $msg .= '</p>';
1.984     raeburn  13154:             return ('existingfile',$msg);
1.661     raeburn  13155:         }
                   13156:     }
                   13157: }
                   13158: 
1.987     raeburn  13159: sub check_for_traversal {
                   13160:     my ($path,$url,$toplevel) = @_;
                   13161:     my @parts=split(/\//,$path);
                   13162:     my $cleanpath;
                   13163:     my $fullpath = $url;
                   13164:     for (my $i=0;$i<@parts;$i++) {
                   13165:         next if ($parts[$i] eq '.');
                   13166:         if ($parts[$i] eq '..') {
                   13167:             $fullpath =~ s{([^/]+/)$}{};
                   13168:         } else {
                   13169:             $fullpath .= $parts[$i].'/';
                   13170:         }
                   13171:     }
                   13172:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13173:         $cleanpath = $1;
                   13174:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13175:         my $curr_toprel = $1;
                   13176:         my @parts = split(/\//,$curr_toprel);
                   13177:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13178:         my @urlparts = split(/\//,$url_toprel);
                   13179:         my $doubledots;
                   13180:         my $startdiff = -1;
                   13181:         for (my $i=0; $i<@urlparts; $i++) {
                   13182:             if ($startdiff == -1) {
                   13183:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13184:                     $startdiff = $i;
                   13185:                     $doubledots .= '../';
                   13186:                 }
                   13187:             } else {
                   13188:                 $doubledots .= '../';
                   13189:             }
                   13190:         }
                   13191:         if ($startdiff > -1) {
                   13192:             $cleanpath = $doubledots;
                   13193:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13194:                 $cleanpath .= $parts[$i].'/';
                   13195:             }
                   13196:         }
                   13197:     }
                   13198:     $cleanpath =~ s{(/)$}{};
                   13199:     return $cleanpath;
                   13200: }
1.31      albertel 13201: 
1.1053    raeburn  13202: sub is_archive_file {
                   13203:     my ($mimetype) = @_;
                   13204:     if (($mimetype eq 'application/octet-stream') ||
                   13205:         ($mimetype eq 'application/x-stuffit') ||
                   13206:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13207:         return 1;
                   13208:     }
                   13209:     return;
                   13210: }
                   13211: 
                   13212: sub decompress_form {
1.1065    raeburn  13213:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13214:     my %lt = &Apache::lonlocal::texthash (
                   13215:         this => 'This file is an archive file.',
1.1067    raeburn  13216:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13217:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13218:         youm => 'You may wish to extract its contents.',
                   13219:         extr => 'Extract contents',
1.1067    raeburn  13220:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13221:         proa => 'Process automatically?',
1.1053    raeburn  13222:         yes  => 'Yes',
                   13223:         no   => 'No',
1.1067    raeburn  13224:         fold => 'Title for folder containing movie',
                   13225:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13226:     );
1.1065    raeburn  13227:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13228:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13229:     my $info = &list_archive_contents($fileloc,\@paths);
                   13230:     if (@paths) {
                   13231:         foreach my $path (@paths) {
                   13232:             $path =~ s{^/}{};
1.1067    raeburn  13233:             if ($path =~ m{^([^/]+)/$}) {
                   13234:                 $topdir = $1;
                   13235:             }
1.1065    raeburn  13236:             if ($path =~ m{^([^/]+)/}) {
                   13237:                 $toplevel{$1} = $path;
                   13238:             } else {
                   13239:                 $toplevel{$path} = $path;
                   13240:             }
                   13241:         }
                   13242:     }
1.1067    raeburn  13243:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13244:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13245:                         "$topdir/media/",
                   13246:                         "$topdir/media/$topdir.mp4",
                   13247:                         "$topdir/media/FirstFrame.png",
                   13248:                         "$topdir/media/player.swf",
                   13249:                         "$topdir/media/swfobject.js",
                   13250:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13251:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13252:                          "$topdir/$topdir.mp4",
                   13253:                          "$topdir/$topdir\_config.xml",
                   13254:                          "$topdir/$topdir\_controller.swf",
                   13255:                          "$topdir/$topdir\_embed.css",
                   13256:                          "$topdir/$topdir\_First_Frame.png",
                   13257:                          "$topdir/$topdir\_player.html",
                   13258:                          "$topdir/$topdir\_Thumbnails.png",
                   13259:                          "$topdir/playerProductInstall.swf",
                   13260:                          "$topdir/scripts/",
                   13261:                          "$topdir/scripts/config_xml.js",
                   13262:                          "$topdir/scripts/handlebars.js",
                   13263:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13264:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13265:                          "$topdir/scripts/modernizr.js",
                   13266:                          "$topdir/scripts/player-min.js",
                   13267:                          "$topdir/scripts/swfobject.js",
                   13268:                          "$topdir/skins/",
                   13269:                          "$topdir/skins/configuration_express.xml",
                   13270:                          "$topdir/skins/express_show/",
                   13271:                          "$topdir/skins/express_show/player-min.css",
                   13272:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13273:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13274:                          "$topdir/$topdir.mp4",
                   13275:                          "$topdir/$topdir\_config.xml",
                   13276:                          "$topdir/$topdir\_controller.swf",
                   13277:                          "$topdir/$topdir\_embed.css",
                   13278:                          "$topdir/$topdir\_First_Frame.png",
                   13279:                          "$topdir/$topdir\_player.html",
                   13280:                          "$topdir/$topdir\_Thumbnails.png",
                   13281:                          "$topdir/playerProductInstall.swf",
                   13282:                          "$topdir/scripts/",
                   13283:                          "$topdir/scripts/config_xml.js",
                   13284:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13285:                          "$topdir/skins/",
                   13286:                          "$topdir/skins/configuration_express.xml",
                   13287:                          "$topdir/skins/express_show/",
                   13288:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13289:                          "$topdir/skins/express_show/spritesheet.png",
                   13290:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13291:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13292:         if (@diffs == 0) {
1.1164    raeburn  13293:             $is_camtasia = 6;
                   13294:         } else {
1.1197    raeburn  13295:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13296:             if (@diffs == 0) {
                   13297:                 $is_camtasia = 8;
1.1197    raeburn  13298:             } else {
                   13299:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13300:                 if (@diffs == 0) {
                   13301:                     $is_camtasia = 8;
                   13302:                 }
1.1164    raeburn  13303:             }
1.1067    raeburn  13304:         }
                   13305:     }
                   13306:     my $output;
                   13307:     if ($is_camtasia) {
                   13308:         $output = <<"ENDCAM";
                   13309: <script type="text/javascript" language="Javascript">
                   13310: // <![CDATA[
                   13311: 
                   13312: function camtasiaToggle() {
                   13313:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13314:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13315:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13316:                 document.getElementById('camtasia_titles').style.display='block';
                   13317:             } else {
                   13318:                 document.getElementById('camtasia_titles').style.display='none';
                   13319:             }
                   13320:         }
                   13321:     }
                   13322:     return;
                   13323: }
                   13324: 
                   13325: // ]]>
                   13326: </script>
                   13327: <p>$lt{'camt'}</p>
                   13328: ENDCAM
1.1065    raeburn  13329:     } else {
1.1067    raeburn  13330:         $output = '<p>'.$lt{'this'};
                   13331:         if ($info eq '') {
                   13332:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13333:         } else {
                   13334:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13335:                        '<div><pre>'.$info.'</pre></div>';
                   13336:         }
1.1065    raeburn  13337:     }
1.1067    raeburn  13338:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13339:     my $duplicates;
                   13340:     my $num = 0;
                   13341:     if (ref($dirlist) eq 'ARRAY') {
                   13342:         foreach my $item (@{$dirlist}) {
                   13343:             if (ref($item) eq 'ARRAY') {
                   13344:                 if (exists($toplevel{$item->[0]})) {
                   13345:                     $duplicates .= 
                   13346:                         &start_data_table_row().
                   13347:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13348:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13349:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13350:                         'value="1" />'.&mt('Yes').'</label>'.
                   13351:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13352:                         '<td>'.$item->[0].'</td>';
                   13353:                     if ($item->[2]) {
                   13354:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13355:                     } else {
                   13356:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13357:                     }
                   13358:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13359:                                    '<td>'.
                   13360:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13361:                                    '</td>'.
                   13362:                                    &end_data_table_row();
                   13363:                     $num ++;
                   13364:                 }
                   13365:             }
                   13366:         }
                   13367:     }
                   13368:     my $itemcount;
                   13369:     if (@paths > 0) {
                   13370:         $itemcount = scalar(@paths);
                   13371:     } else {
                   13372:         $itemcount = 1;
                   13373:     }
1.1067    raeburn  13374:     if ($is_camtasia) {
                   13375:         $output .= $lt{'auto'}.'<br />'.
                   13376:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13377:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13378:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13379:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13380:                    $lt{'no'}.'</label></span><br />'.
                   13381:                    '<div id="camtasia_titles" style="display:block">'.
                   13382:                    &Apache::lonhtmlcommon::start_pick_box().
                   13383:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13384:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13385:                    &Apache::lonhtmlcommon::row_closure().
                   13386:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13387:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13388:                    &Apache::lonhtmlcommon::row_closure(1).
                   13389:                    &Apache::lonhtmlcommon::end_pick_box().
                   13390:                    '</div>';
                   13391:     }
1.1065    raeburn  13392:     $output .= 
                   13393:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13394:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13395:         "\n";
1.1065    raeburn  13396:     if ($duplicates ne '') {
                   13397:         $output .= '<p><span class="LC_warning">'.
                   13398:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13399:                    &start_data_table().
                   13400:                    &start_data_table_header_row().
                   13401:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13402:                    '<th>'.&mt('Name').'</th>'.
                   13403:                    '<th>'.&mt('Type').'</th>'.
                   13404:                    '<th>'.&mt('Size').'</th>'.
                   13405:                    '<th>'.&mt('Last modified').'</th>'.
                   13406:                    &end_data_table_header_row().
                   13407:                    $duplicates.
                   13408:                    &end_data_table().
                   13409:                    '</p>';
                   13410:     }
1.1067    raeburn  13411:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13412:     if (ref($hiddenelements) eq 'HASH') {
                   13413:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13414:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13415:         }
                   13416:     }
                   13417:     $output .= <<"END";
1.1067    raeburn  13418: <br />
1.1053    raeburn  13419: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13420: </form>
                   13421: $noextract
                   13422: END
                   13423:     return $output;
                   13424: }
                   13425: 
1.1065    raeburn  13426: sub decompression_utility {
                   13427:     my ($program) = @_;
                   13428:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13429:     my $location;
                   13430:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13431:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13432:                          '/usr/sbin/') {
                   13433:             if (-x $dir.$program) {
                   13434:                 $location = $dir.$program;
                   13435:                 last;
                   13436:             }
                   13437:         }
                   13438:     }
                   13439:     return $location;
                   13440: }
                   13441: 
                   13442: sub list_archive_contents {
                   13443:     my ($file,$pathsref) = @_;
                   13444:     my (@cmd,$output);
                   13445:     my $needsregexp;
                   13446:     if ($file =~ /\.zip$/) {
                   13447:         @cmd = (&decompression_utility('unzip'),"-l");
                   13448:         $needsregexp = 1;
                   13449:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13450:              ($file =~ /\.tgz$/)) {
                   13451:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13452:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13453:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13454:     } elsif ($file =~ m|\.tar$|) {
                   13455:         @cmd = (&decompression_utility('tar'),"-tf");
                   13456:     }
                   13457:     if (@cmd) {
                   13458:         undef($!);
                   13459:         undef($@);
                   13460:         if (open(my $fh,"-|", @cmd, $file)) {
                   13461:             while (my $line = <$fh>) {
                   13462:                 $output .= $line;
                   13463:                 chomp($line);
                   13464:                 my $item;
                   13465:                 if ($needsregexp) {
                   13466:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13467:                 } else {
                   13468:                     $item = $line;
                   13469:                 }
                   13470:                 if ($item ne '') {
                   13471:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   13472:                         push(@{$pathsref},$item);
                   13473:                     } 
                   13474:                 }
                   13475:             }
                   13476:             close($fh);
                   13477:         }
                   13478:     }
                   13479:     return $output;
                   13480: }
                   13481: 
1.1053    raeburn  13482: sub decompress_uploaded_file {
                   13483:     my ($file,$dir) = @_;
                   13484:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13485:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13486:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13487:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13488:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13489:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13490:     my $decompressed = $env{'cgi.decompressed'};
                   13491:     &Apache::lonnet::delenv('cgi.file');
                   13492:     &Apache::lonnet::delenv('cgi.dir');
                   13493:     &Apache::lonnet::delenv('cgi.decompressed');
                   13494:     return ($decompressed,$result);
                   13495: }
                   13496: 
1.1055    raeburn  13497: sub process_decompression {
                   13498:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  13499:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13500:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13501:                &mt('Unexpected file path.').'</p>'."\n";
                   13502:     }
                   13503:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13504:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13505:                &mt('Unexpected course context.').'</p>'."\n";
                   13506:     }
1.1293    raeburn  13507:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  13508:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13509:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13510:     }
1.1055    raeburn  13511:     my ($dir,$error,$warning,$output);
1.1180    raeburn  13512:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   13513:         $error = &mt('Filename not a supported archive file type.').
                   13514:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13515:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13516:     } else {
                   13517:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13518:         if ($docuhome eq 'no_host') {
                   13519:             $error = &mt('Could not determine home server for course.');
                   13520:         } else {
                   13521:             my @ids=&Apache::lonnet::current_machine_ids();
                   13522:             my $currdir = "$dir_root/$destination";
                   13523:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13524:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13525:                        "$dir_root/$destination";
                   13526:             } else {
                   13527:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13528:                        "$dir_root/$docudom/$docuname/$destination";
                   13529:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13530:                     $error = &mt('Archive file not found.');
                   13531:                 }
                   13532:             }
1.1065    raeburn  13533:             my (@to_overwrite,@to_skip);
                   13534:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13535:                 my $total = $env{'form.archive_overwrite_total'};
                   13536:                 for (my $i=0; $i<$total; $i++) {
                   13537:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13538:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13539:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13540:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13541:                     }
                   13542:                 }
                   13543:             }
                   13544:             my $numskip = scalar(@to_skip);
1.1292    raeburn  13545:             my $numoverwrite = scalar(@to_overwrite);
                   13546:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  13547:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13548:             } elsif ($dir eq '') {
1.1055    raeburn  13549:                 $error = &mt('Directory containing archive file unavailable.');
                   13550:             } elsif (!$error) {
1.1065    raeburn  13551:                 my ($decompressed,$display);
1.1292    raeburn  13552:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13553:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13554:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  13555:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13556:                         ($decompressed,$display) = 
                   13557:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13558:                         foreach my $item (@to_skip) {
                   13559:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13560:                                 if (-f "$dir/$tempdir/$item") { 
                   13561:                                     unlink("$dir/$tempdir/$item");
                   13562:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  13563:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  13564:                                 }
                   13565:                             }
                   13566:                         }
                   13567:                         foreach my $item (@to_overwrite) {
                   13568:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13569:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13570:                                     if (-f "$dir/$item") {
                   13571:                                         unlink("$dir/$item");
                   13572:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  13573:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  13574:                                     }
                   13575:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13576:                                 }
1.1065    raeburn  13577:                             }
                   13578:                         }
1.1292    raeburn  13579:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  13580:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  13581:                         }
1.1065    raeburn  13582:                     }
                   13583:                 } else {
                   13584:                     ($decompressed,$display) = 
                   13585:                         &decompress_uploaded_file($file,$dir);
                   13586:                 }
1.1055    raeburn  13587:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13588:                     $output = '<p class="LC_info">'.
                   13589:                               &mt('Files extracted successfully from archive.').
                   13590:                               '</p>'."\n";
1.1055    raeburn  13591:                     my ($warning,$result,@contents);
                   13592:                     my ($newdirlistref,$newlisterror) =
                   13593:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13594:                                                  $docuname,1);
                   13595:                     my (%is_dir,%changes,@newitems);
                   13596:                     my $dirptr = 16384;
1.1065    raeburn  13597:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13598:                         foreach my $dir_line (@{$newdirlistref}) {
                   13599:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  13600:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  13601:                                 push(@newitems,$item);
                   13602:                                 if ($dirptr&$testdir) {
                   13603:                                     $is_dir{$item} = 1;
                   13604:                                 }
                   13605:                                 $changes{$item} = 1;
                   13606:                             }
                   13607:                         }
                   13608:                     }
                   13609:                     if (keys(%changes) > 0) {
                   13610:                         foreach my $item (sort(@newitems)) {
                   13611:                             if ($changes{$item}) {
                   13612:                                 push(@contents,$item);
                   13613:                             }
                   13614:                         }
                   13615:                     }
                   13616:                     if (@contents > 0) {
1.1067    raeburn  13617:                         my $wantform;
                   13618:                         unless ($env{'form.autoextract_camtasia'}) {
                   13619:                             $wantform = 1;
                   13620:                         }
1.1056    raeburn  13621:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13622:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13623:                                                                 $currdir,\%is_dir,
                   13624:                                                                 \%children,\%parent,
1.1056    raeburn  13625:                                                                 \@contents,\%dirorder,
                   13626:                                                                 \%titles,$wantform);
1.1055    raeburn  13627:                         if ($datatable ne '') {
                   13628:                             $output .= &archive_options_form('decompressed',$datatable,
                   13629:                                                              $count,$hiddenelem);
1.1065    raeburn  13630:                             my $startcount = 6;
1.1055    raeburn  13631:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13632:                                                            \%titles,\%children);
1.1055    raeburn  13633:                         }
1.1067    raeburn  13634:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  13635:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13636:                             my %displayed;
                   13637:                             my $total = 1;
                   13638:                             $env{'form.archive_directory'} = [];
                   13639:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13640:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13641:                                 $path =~ s{/$}{};
                   13642:                                 my $item;
                   13643:                                 if ($path ne '') {
                   13644:                                     $item = "$path/$titles{$i}";
                   13645:                                 } else {
                   13646:                                     $item = $titles{$i};
                   13647:                                 }
                   13648:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13649:                                 if ($item eq $contents[0]) {
                   13650:                                     push(@{$env{'form.archive_directory'}},$i);
                   13651:                                     $env{'form.archive_'.$i} = 'display';
                   13652:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13653:                                     $displayed{'folder'} = $i;
1.1164    raeburn  13654:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13655:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  13656:                                     $env{'form.archive_'.$i} = 'display';
                   13657:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13658:                                     $displayed{'web'} = $i;
                   13659:                                 } else {
1.1164    raeburn  13660:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13661:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13662:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13663:                                         push(@{$env{'form.archive_directory'}},$i);
                   13664:                                     }
                   13665:                                     $env{'form.archive_'.$i} = 'dependency';
                   13666:                                 }
                   13667:                                 $total ++;
                   13668:                             }
                   13669:                             for (my $i=1; $i<$total; $i++) {
                   13670:                                 next if ($i == $displayed{'web'});
                   13671:                                 next if ($i == $displayed{'folder'});
                   13672:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13673:                             }
                   13674:                             $env{'form.phase'} = 'decompress_cleanup';
                   13675:                             $env{'form.archivedelete'} = 1;
                   13676:                             $env{'form.archive_count'} = $total-1;
                   13677:                             $output .=
                   13678:                                 &process_extracted_files('coursedocs',$docudom,
                   13679:                                                          $docuname,$destination,
                   13680:                                                          $dir_root,$hiddenelem);
                   13681:                         }
1.1055    raeburn  13682:                     } else {
                   13683:                         $warning = &mt('No new items extracted from archive file.');
                   13684:                     }
                   13685:                 } else {
                   13686:                     $output = $display;
                   13687:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13688:                 }
                   13689:             }
                   13690:         }
                   13691:     }
                   13692:     if ($error) {
                   13693:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13694:                    $error.'</p>'."\n";
                   13695:     }
                   13696:     if ($warning) {
                   13697:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13698:     }
                   13699:     return $output;
                   13700: }
                   13701: 
                   13702: sub get_extracted {
1.1056    raeburn  13703:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13704:         $titles,$wantform) = @_;
1.1055    raeburn  13705:     my $count = 0;
                   13706:     my $depth = 0;
                   13707:     my $datatable;
1.1056    raeburn  13708:     my @hierarchy;
1.1055    raeburn  13709:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13710:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13711:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13712:     foreach my $item (@{$contents}) {
                   13713:         $count ++;
1.1056    raeburn  13714:         @{$dirorder->{$count}} = @hierarchy;
                   13715:         $titles->{$count} = $item;
1.1055    raeburn  13716:         &archive_hierarchy($depth,$count,$parent,$children);
                   13717:         if ($wantform) {
                   13718:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13719:                                        $currdir,$depth,$count);
                   13720:         }
                   13721:         if ($is_dir->{$item}) {
                   13722:             $depth ++;
1.1056    raeburn  13723:             push(@hierarchy,$count);
                   13724:             $parent->{$depth} = $count;
1.1055    raeburn  13725:             $datatable .=
                   13726:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13727:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13728:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13729:             $depth --;
1.1056    raeburn  13730:             pop(@hierarchy);
1.1055    raeburn  13731:         }
                   13732:     }
                   13733:     return ($count,$datatable);
                   13734: }
                   13735: 
                   13736: sub recurse_extracted_archive {
1.1056    raeburn  13737:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13738:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13739:     my $result='';
1.1056    raeburn  13740:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13741:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13742:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13743:         return $result;
                   13744:     }
                   13745:     my $dirptr = 16384;
                   13746:     my ($newdirlistref,$newlisterror) =
                   13747:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13748:     if (ref($newdirlistref) eq 'ARRAY') {
                   13749:         foreach my $dir_line (@{$newdirlistref}) {
                   13750:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13751:             unless ($item =~ /^\.+$/) {
                   13752:                 $$count ++;
1.1056    raeburn  13753:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13754:                 $titles->{$$count} = $item;
1.1055    raeburn  13755:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13756: 
1.1055    raeburn  13757:                 my $is_dir;
                   13758:                 if ($dirptr&$testdir) {
                   13759:                     $is_dir = 1;
                   13760:                 }
                   13761:                 if ($wantform) {
                   13762:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13763:                 }
                   13764:                 if ($is_dir) {
                   13765:                     $$depth ++;
1.1056    raeburn  13766:                     push(@{$hierarchy},$$count);
                   13767:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13768:                     $result .=
                   13769:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13770:                                                    $docuname,$depth,$count,
1.1056    raeburn  13771:                                                    $hierarchy,$dirorder,$children,
                   13772:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13773:                     $$depth --;
1.1056    raeburn  13774:                     pop(@{$hierarchy});
1.1055    raeburn  13775:                 }
                   13776:             }
                   13777:         }
                   13778:     }
                   13779:     return $result;
                   13780: }
                   13781: 
                   13782: sub archive_hierarchy {
                   13783:     my ($depth,$count,$parent,$children) =@_;
                   13784:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13785:         if (exists($parent->{$depth})) {
                   13786:              $children->{$parent->{$depth}} .= $count.':';
                   13787:         }
                   13788:     }
                   13789:     return;
                   13790: }
                   13791: 
                   13792: sub archive_row {
                   13793:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13794:     my ($name) = ($item =~ m{([^/]+)$});
                   13795:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13796:                                        'display'    => 'Add as file',
1.1055    raeburn  13797:                                        'dependency' => 'Include as dependency',
                   13798:                                        'discard'    => 'Discard',
                   13799:                                       );
                   13800:     if ($is_dir) {
1.1059    raeburn  13801:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13802:     }
1.1056    raeburn  13803:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13804:     my $offset = 0;
1.1055    raeburn  13805:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13806:         $offset ++;
1.1065    raeburn  13807:         if ($action ne 'display') {
                   13808:             $offset ++;
                   13809:         }  
1.1055    raeburn  13810:         $output .= '<td><span class="LC_nobreak">'.
                   13811:                    '<label><input type="radio" name="archive_'.$count.
                   13812:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13813:         my $text = $choices{$action};
                   13814:         if ($is_dir) {
                   13815:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13816:             if ($action eq 'display') {
1.1059    raeburn  13817:                 $text = &mt('Add as folder');
1.1055    raeburn  13818:             }
1.1056    raeburn  13819:         } else {
                   13820:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13821: 
                   13822:         }
                   13823:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13824:         if ($action eq 'dependency') {
                   13825:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13826:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13827:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13828:                        '<option value=""></option>'."\n".
                   13829:                        '</select>'."\n".
                   13830:                        '</div>';
1.1059    raeburn  13831:         } elsif ($action eq 'display') {
                   13832:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13833:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13834:                        '</div>';
1.1055    raeburn  13835:         }
1.1056    raeburn  13836:         $output .= '</td>';
1.1055    raeburn  13837:     }
                   13838:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13839:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13840:     for (my $i=0; $i<$depth; $i++) {
                   13841:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13842:     }
                   13843:     if ($is_dir) {
                   13844:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13845:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13846:     } else {
                   13847:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13848:     }
                   13849:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13850:                &end_data_table_row();
                   13851:     return $output;
                   13852: }
                   13853: 
                   13854: sub archive_options_form {
1.1065    raeburn  13855:     my ($form,$display,$count,$hiddenelem) = @_;
                   13856:     my %lt = &Apache::lonlocal::texthash(
                   13857:                perm => 'Permanently remove archive file?',
                   13858:                hows => 'How should each extracted item be incorporated in the course?',
                   13859:                cont => 'Content actions for all',
                   13860:                addf => 'Add as folder/file',
                   13861:                incd => 'Include as dependency for a displayed file',
                   13862:                disc => 'Discard',
                   13863:                no   => 'No',
                   13864:                yes  => 'Yes',
                   13865:                save => 'Save',
                   13866:     );
                   13867:     my $output = <<"END";
                   13868: <form name="$form" method="post" action="">
                   13869: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13870: <label>
                   13871:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13872: </label>
                   13873: &nbsp;
                   13874: <label>
                   13875:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13876: </span>
                   13877: </p>
                   13878: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13879: <br />$lt{'hows'}
                   13880: <div class="LC_columnSection">
                   13881:   <fieldset>
                   13882:     <legend>$lt{'cont'}</legend>
                   13883:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13884:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13885:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13886:   </fieldset>
                   13887: </div>
                   13888: END
                   13889:     return $output.
1.1055    raeburn  13890:            &start_data_table()."\n".
1.1065    raeburn  13891:            $display."\n".
1.1055    raeburn  13892:            &end_data_table()."\n".
                   13893:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13894:            $hiddenelem.
1.1065    raeburn  13895:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13896:            '</form>';
                   13897: }
                   13898: 
                   13899: sub archive_javascript {
1.1056    raeburn  13900:     my ($startcount,$numitems,$titles,$children) = @_;
                   13901:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13902:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13903:     my $scripttag = <<START;
                   13904: <script type="text/javascript">
                   13905: // <![CDATA[
                   13906: 
                   13907: function checkAll(form,prefix) {
                   13908:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13909:     for (var i=0; i < form.elements.length; i++) {
                   13910:         var id = form.elements[i].id;
                   13911:         if ((id != '') && (id != undefined)) {
                   13912:             if (idstr.test(id)) {
                   13913:                 if (form.elements[i].type == 'radio') {
                   13914:                     form.elements[i].checked = true;
1.1056    raeburn  13915:                     var nostart = i-$startcount;
1.1059    raeburn  13916:                     var offset = nostart%7;
                   13917:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13918:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13919:                 }
                   13920:             }
                   13921:         }
                   13922:     }
                   13923: }
                   13924: 
                   13925: function propagateCheck(form,count) {
                   13926:     if (count > 0) {
1.1059    raeburn  13927:         var startelement = $startcount + ((count-1) * 7);
                   13928:         for (var j=1; j<6; j++) {
                   13929:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13930:                 var item = startelement + j; 
                   13931:                 if (form.elements[item].type == 'radio') {
                   13932:                     if (form.elements[item].checked) {
                   13933:                         containerCheck(form,count,j);
                   13934:                         break;
                   13935:                     }
1.1055    raeburn  13936:                 }
                   13937:             }
                   13938:         }
                   13939:     }
                   13940: }
                   13941: 
                   13942: numitems = $numitems
1.1056    raeburn  13943: var titles = new Array(numitems);
                   13944: var parents = new Array(numitems);
1.1055    raeburn  13945: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13946:     parents[i] = new Array;
1.1055    raeburn  13947: }
1.1059    raeburn  13948: var maintitle = '$maintitle';
1.1055    raeburn  13949: 
                   13950: START
                   13951: 
1.1056    raeburn  13952:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13953:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13954:         for (my $i=0; $i<@contents; $i ++) {
                   13955:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13956:         }
                   13957:     }
                   13958: 
1.1056    raeburn  13959:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13960:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13961:     }
                   13962: 
1.1055    raeburn  13963:     $scripttag .= <<END;
                   13964: 
                   13965: function containerCheck(form,count,offset) {
                   13966:     if (count > 0) {
1.1056    raeburn  13967:         dependencyCheck(form,count,offset);
1.1059    raeburn  13968:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13969:         form.elements[item].checked = true;
                   13970:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13971:             if (parents[count].length > 0) {
                   13972:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13973:                     containerCheck(form,parents[count][j],offset);
                   13974:                 }
                   13975:             }
                   13976:         }
                   13977:     }
                   13978: }
                   13979: 
                   13980: function dependencyCheck(form,count,offset) {
                   13981:     if (count > 0) {
1.1059    raeburn  13982:         var chosen = (offset+$startcount)+7*(count-1);
                   13983:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13984:         var currtype = form.elements[depitem].type;
                   13985:         if (form.elements[chosen].value == 'dependency') {
                   13986:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13987:             form.elements[depitem].options.length = 0;
                   13988:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  13989:             for (var i=1; i<=numitems; i++) {
                   13990:                 if (i == count) {
                   13991:                     continue;
                   13992:                 }
1.1059    raeburn  13993:                 var startelement = $startcount + (i-1) * 7;
                   13994:                 for (var j=1; j<6; j++) {
                   13995:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13996:                         var item = startelement + j;
                   13997:                         if (form.elements[item].type == 'radio') {
                   13998:                             if (form.elements[item].checked) {
                   13999:                                 if (form.elements[item].value == 'display') {
                   14000:                                     var n = form.elements[depitem].options.length;
                   14001:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14002:                                 }
                   14003:                             }
                   14004:                         }
                   14005:                     }
                   14006:                 }
                   14007:             }
                   14008:         } else {
                   14009:             document.getElementById('arc_depon_'+count).style.display='none';
                   14010:             form.elements[depitem].options.length = 0;
                   14011:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14012:         }
1.1059    raeburn  14013:         titleCheck(form,count,offset);
1.1056    raeburn  14014:     }
                   14015: }
                   14016: 
                   14017: function propagateSelect(form,count,offset) {
                   14018:     if (count > 0) {
1.1065    raeburn  14019:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14020:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14021:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14022:             if (parents[count].length > 0) {
                   14023:                 for (var j=0; j<parents[count].length; j++) {
                   14024:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14025:                 }
                   14026:             }
                   14027:         }
                   14028:     }
                   14029: }
1.1056    raeburn  14030: 
                   14031: function containerSelect(form,count,offset,picked) {
                   14032:     if (count > 0) {
1.1065    raeburn  14033:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14034:         if (form.elements[item].type == 'radio') {
                   14035:             if (form.elements[item].value == 'dependency') {
                   14036:                 if (form.elements[item+1].type == 'select-one') {
                   14037:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14038:                         if (form.elements[item+1].options[i].value == picked) {
                   14039:                             form.elements[item+1].selectedIndex = i;
                   14040:                             break;
                   14041:                         }
                   14042:                     }
                   14043:                 }
                   14044:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14045:                     if (parents[count].length > 0) {
                   14046:                         for (var j=0; j<parents[count].length; j++) {
                   14047:                             containerSelect(form,parents[count][j],offset,picked);
                   14048:                         }
                   14049:                     }
                   14050:                 }
                   14051:             }
                   14052:         }
                   14053:     }
                   14054: }
                   14055: 
1.1059    raeburn  14056: function titleCheck(form,count,offset) {
                   14057:     if (count > 0) {
                   14058:         var chosen = (offset+$startcount)+7*(count-1);
                   14059:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14060:         var currtype = form.elements[depitem].type;
                   14061:         if (form.elements[chosen].value == 'display') {
                   14062:             document.getElementById('arc_title_'+count).style.display='block';
                   14063:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14064:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14065:             }
                   14066:         } else {
                   14067:             document.getElementById('arc_title_'+count).style.display='none';
                   14068:             if (currtype == 'text') { 
                   14069:                 document.getElementById('archive_title_'+count).value='';
                   14070:             }
                   14071:         }
                   14072:     }
                   14073:     return;
                   14074: }
                   14075: 
1.1055    raeburn  14076: // ]]>
                   14077: </script>
                   14078: END
                   14079:     return $scripttag;
                   14080: }
                   14081: 
                   14082: sub process_extracted_files {
1.1067    raeburn  14083:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14084:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14085:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14086:     my @ids=&Apache::lonnet::current_machine_ids();
                   14087:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14088:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14089:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14090:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14091:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14092:         $pathtocheck = "$dir_root/$destination";
                   14093:         $dir = $dir_root;
                   14094:         $ishome = 1;
                   14095:     } else {
                   14096:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14097:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14098:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14099:     }
                   14100:     my $currdir = "$dir_root/$destination";
                   14101:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14102:     if ($env{'form.folderpath'}) {
                   14103:         my @items = split('&',$env{'form.folderpath'});
                   14104:         $folders{'0'} = $items[-2];
1.1099    raeburn  14105:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14106:             $containers{'0'}='page';
                   14107:         } else {  
                   14108:             $containers{'0'}='sequence';
                   14109:         }
1.1055    raeburn  14110:     }
                   14111:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14112:     if ($numitems) {
                   14113:         for (my $i=1; $i<=$numitems; $i++) {
                   14114:             my $path = $env{'form.archive_content_'.$i};
                   14115:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14116:                 my $item = $1;
                   14117:                 $toplevelitems{$item} = $i;
                   14118:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14119:                     $is_dir{$item} = 1;
                   14120:                 }
                   14121:             }
                   14122:         }
                   14123:     }
1.1067    raeburn  14124:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14125:     if (keys(%toplevelitems) > 0) {
                   14126:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14127:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14128:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14129:     }
1.1066    raeburn  14130:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14131:     if ($numitems) {
                   14132:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14133:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14134:             my $path = $env{'form.archive_content_'.$i};
                   14135:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14136:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14137:                     if ($prefix ne '' && $path ne '') {
                   14138:                         if (-e $prefix.$path) {
1.1066    raeburn  14139:                             if ((@archdirs > 0) && 
                   14140:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14141:                                 $todeletedir{$prefix.$path} = 1;
                   14142:                             } else {
                   14143:                                 $todelete{$prefix.$path} = 1;
                   14144:                             }
1.1055    raeburn  14145:                         }
                   14146:                     }
                   14147:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14148:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14149:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14150:                     $docstitle = $env{'form.archive_title_'.$i};
                   14151:                     if ($docstitle eq '') {
                   14152:                         $docstitle = $title;
                   14153:                     }
1.1055    raeburn  14154:                     $outer = 0;
1.1056    raeburn  14155:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14156:                         if (@{$dirorder{$i}} > 0) {
                   14157:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14158:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14159:                                     $outer = $item;
                   14160:                                     last;
                   14161:                                 }
                   14162:                             }
                   14163:                         }
                   14164:                     }
                   14165:                     my ($errtext,$fatal) = 
                   14166:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14167:                                                '/'.$folders{$outer}.'.'.
                   14168:                                                $containers{$outer});
                   14169:                     next if ($fatal);
                   14170:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14171:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14172:                             $mapinner{$i} = time;
1.1055    raeburn  14173:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14174:                             $containers{$i} = 'sequence';
                   14175:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14176:                                       $folders{$i}.'.'.$containers{$i};
                   14177:                             my $newidx = &LONCAPA::map::getresidx();
                   14178:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14179:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14180:                             push(@LONCAPA::map::order,$newidx);
                   14181:                             my ($outtext,$errtext) =
                   14182:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14183:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14184:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14185:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14186:                             unless ($errtext) {
1.1294    raeburn  14187:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14188:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14189:                                             '</li>'."\n";
1.1067    raeburn  14190:                             }
1.1055    raeburn  14191:                         }
                   14192:                     } else {
                   14193:                         if ($context eq 'coursedocs') {
                   14194:                             my $newidx=&LONCAPA::map::getresidx();
                   14195:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14196:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14197:                                       $title;
1.1294    raeburn  14198:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   14199:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14200:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14201:                                 }
                   14202:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14203:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14204:                                 }
                   14205:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14206:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14207:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14208:                                         unless ($ishome) {
                   14209:                                             my $fetch = "$newdest{$i}/$title";
                   14210:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14211:                                             $prompttofetch{$fetch} = 1;
                   14212:                                         }
1.1292    raeburn  14213:                                     }
1.1067    raeburn  14214:                                 }
1.1294    raeburn  14215:                                 $LONCAPA::map::resources[$newidx]=
                   14216:                                     $docstitle.':'.$url.':false:normal:res';
                   14217:                                 push(@LONCAPA::map::order, $newidx);
                   14218:                                 my ($outtext,$errtext)=
                   14219:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14220:                                                             $docuname.'/'.$folders{$outer}.
                   14221:                                                             '.'.$containers{$outer},1,1);
                   14222:                                 unless ($errtext) {
                   14223:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14224:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14225:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14226:                                                    '</li>'."\n";
                   14227:                                     }
1.1067    raeburn  14228:                                 }
1.1294    raeburn  14229:                             } else {
                   14230:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14231:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14232:                             }
1.1055    raeburn  14233:                         }
                   14234:                     }
1.1086    raeburn  14235:                 }
                   14236:             } else {
1.1294    raeburn  14237:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14238:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14239:             }
                   14240:         }
                   14241:         for (my $i=1; $i<=$numitems; $i++) {
                   14242:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14243:             my $path = $env{'form.archive_content_'.$i};
                   14244:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14245:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14246:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14247:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14248:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14249:                         my ($itemidx,$fullpath,$relpath);
                   14250:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14251:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14252:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14253:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14254:                                     $itemidx = $j;
1.1056    raeburn  14255:                                 }
                   14256:                             }
1.1086    raeburn  14257:                         }
                   14258:                         if ($itemidx eq '') {
                   14259:                             $itemidx =  0;
                   14260:                         } 
                   14261:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14262:                             if ($mapinner{$referrer{$i}}) {
                   14263:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14264:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14265:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14266:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14267:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14268:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14269:                                             if (!-e $fullpath) {
                   14270:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14271:                                             }
                   14272:                                         }
1.1086    raeburn  14273:                                     } else {
                   14274:                                         last;
1.1056    raeburn  14275:                                     }
1.1086    raeburn  14276:                                 }
                   14277:                             }
                   14278:                         } elsif ($newdest{$referrer{$i}}) {
                   14279:                             $fullpath = $newdest{$referrer{$i}};
                   14280:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14281:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14282:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14283:                                     last;
                   14284:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14285:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14286:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14287:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14288:                                         if (!-e $fullpath) {
                   14289:                                             mkdir($fullpath,0755);
1.1056    raeburn  14290:                                         }
                   14291:                                     }
1.1086    raeburn  14292:                                 } else {
                   14293:                                     last;
1.1056    raeburn  14294:                                 }
1.1055    raeburn  14295:                             }
                   14296:                         }
1.1086    raeburn  14297:                         if ($fullpath ne '') {
                   14298:                             if (-e "$prefix$path") {
1.1292    raeburn  14299:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14300:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14301:                                 }
1.1086    raeburn  14302:                             }
                   14303:                             if (-e "$fullpath/$title") {
                   14304:                                 my $showpath;
                   14305:                                 if ($relpath ne '') {
                   14306:                                     $showpath = "$relpath/$title";
                   14307:                                 } else {
                   14308:                                     $showpath = "/$title";
                   14309:                                 } 
1.1294    raeburn  14310:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14311:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14312:                                            '</li>'."\n";
1.1292    raeburn  14313:                                 unless ($ishome) {
                   14314:                                     my $fetch = "$fullpath/$title";
                   14315:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14316:                                     $prompttofetch{$fetch} = 1;
                   14317:                                 }
1.1086    raeburn  14318:                             }
                   14319:                         }
1.1055    raeburn  14320:                     }
1.1086    raeburn  14321:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14322:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14323:                                     &HTML::Entities::encode($path,'<>&"'),
                   14324:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14325:                                 '<br />';
1.1055    raeburn  14326:                 }
                   14327:             } else {
1.1294    raeburn  14328:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14329:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14330:             }
                   14331:         }
                   14332:         if (keys(%todelete)) {
                   14333:             foreach my $key (keys(%todelete)) {
                   14334:                 unlink($key);
1.1066    raeburn  14335:             }
                   14336:         }
                   14337:         if (keys(%todeletedir)) {
                   14338:             foreach my $key (keys(%todeletedir)) {
                   14339:                 rmdir($key);
                   14340:             }
                   14341:         }
                   14342:         foreach my $dir (sort(keys(%is_dir))) {
                   14343:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14344:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14345:             }
                   14346:         }
1.1067    raeburn  14347:         if ($result ne '') {
                   14348:             $output .= '<ul>'."\n".
                   14349:                        $result."\n".
                   14350:                        '</ul>';
                   14351:         }
                   14352:         unless ($ishome) {
                   14353:             my $replicationfail;
                   14354:             foreach my $item (keys(%prompttofetch)) {
                   14355:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14356:                 unless ($fetchresult eq 'ok') {
                   14357:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14358:                 }
                   14359:             }
                   14360:             if ($replicationfail) {
                   14361:                 $output .= '<p class="LC_error">'.
                   14362:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14363:                            $replicationfail.
                   14364:                            '</ul></p>';
                   14365:             }
                   14366:         }
1.1055    raeburn  14367:     } else {
                   14368:         $warning = &mt('No items found in archive.');
                   14369:     }
                   14370:     if ($error) {
                   14371:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14372:                    $error.'</p>'."\n";
                   14373:     }
                   14374:     if ($warning) {
                   14375:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14376:     }
                   14377:     return $output;
                   14378: }
                   14379: 
1.1066    raeburn  14380: sub cleanup_empty_dirs {
                   14381:     my ($path) = @_;
                   14382:     if (($path ne '') && (-d $path)) {
                   14383:         if (opendir(my $dirh,$path)) {
                   14384:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14385:             my $numitems = 0;
                   14386:             foreach my $item (@dircontents) {
                   14387:                 if (-d "$path/$item") {
1.1111    raeburn  14388:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14389:                     if (-e "$path/$item") {
                   14390:                         $numitems ++;
                   14391:                     }
                   14392:                 } else {
                   14393:                     $numitems ++;
                   14394:                 }
                   14395:             }
                   14396:             if ($numitems == 0) {
                   14397:                 rmdir($path);
                   14398:             }
                   14399:             closedir($dirh);
                   14400:         }
                   14401:     }
                   14402:     return;
                   14403: }
                   14404: 
1.41      ng       14405: =pod
1.45      matthew  14406: 
1.1162    raeburn  14407: =item * &get_folder_hierarchy()
1.1068    raeburn  14408: 
                   14409: Provides hierarchy of names of folders/sub-folders containing the current
                   14410: item,
                   14411: 
                   14412: Inputs: 3
                   14413:      - $navmap - navmaps object
                   14414: 
                   14415:      - $map - url for map (either the trigger itself, or map containing
                   14416:                            the resource, which is the trigger).
                   14417: 
                   14418:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14419: 
                   14420: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14421: 
                   14422: =cut
                   14423: 
                   14424: sub get_folder_hierarchy {
                   14425:     my ($navmap,$map,$showitem) = @_;
                   14426:     my @pathitems;
                   14427:     if (ref($navmap)) {
                   14428:         my $mapres = $navmap->getResourceByUrl($map);
                   14429:         if (ref($mapres)) {
                   14430:             my $pcslist = $mapres->map_hierarchy();
                   14431:             if ($pcslist ne '') {
                   14432:                 my @pcs = split(/,/,$pcslist);
                   14433:                 foreach my $pc (@pcs) {
                   14434:                     if ($pc == 1) {
1.1129    raeburn  14435:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14436:                     } else {
                   14437:                         my $res = $navmap->getByMapPc($pc);
                   14438:                         if (ref($res)) {
                   14439:                             my $title = $res->compTitle();
                   14440:                             $title =~ s/\W+/_/g;
                   14441:                             if ($title ne '') {
                   14442:                                 push(@pathitems,$title);
                   14443:                             }
                   14444:                         }
                   14445:                     }
                   14446:                 }
                   14447:             }
1.1071    raeburn  14448:             if ($showitem) {
                   14449:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14450:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14451:                 } else {
                   14452:                     my $maptitle = $mapres->compTitle();
                   14453:                     $maptitle =~ s/\W+/_/g;
                   14454:                     if ($maptitle ne '') {
                   14455:                         push(@pathitems,$maptitle);
                   14456:                     }
1.1068    raeburn  14457:                 }
                   14458:             }
                   14459:         }
                   14460:     }
                   14461:     return @pathitems;
                   14462: }
                   14463: 
                   14464: =pod
                   14465: 
1.1015    raeburn  14466: =item * &get_turnedin_filepath()
                   14467: 
                   14468: Determines path in a user's portfolio file for storage of files uploaded
                   14469: to a specific essayresponse or dropbox item.
                   14470: 
                   14471: Inputs: 3 required + 1 optional.
                   14472: $symb is symb for resource, $uname and $udom are for current user (required).
                   14473: $caller is optional (can be "submission", if routine is called when storing
                   14474: an upoaded file when "Submit Answer" button was pressed).
                   14475: 
                   14476: Returns array containing $path and $multiresp. 
                   14477: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   14478: than one file upload item.  Callers of routine should append partid as a 
                   14479: subdirectory to $path in cases where $multiresp is 1.
                   14480: 
                   14481: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14482: 
                   14483: =cut
                   14484: 
                   14485: sub get_turnedin_filepath {
                   14486:     my ($symb,$uname,$udom,$caller) = @_;
                   14487:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14488:     my $turnindir;
                   14489:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14490:     $turnindir = $userhash{'turnindir'};
                   14491:     my ($path,$multiresp);
                   14492:     if ($turnindir eq '') {
                   14493:         if ($caller eq 'submission') {
                   14494:             $turnindir = &mt('turned in');
                   14495:             $turnindir =~ s/\W+/_/g;
                   14496:             my %newhash = (
                   14497:                             'turnindir' => $turnindir,
                   14498:                           );
                   14499:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14500:         }
                   14501:     }
                   14502:     if ($turnindir ne '') {
                   14503:         $path = '/'.$turnindir.'/';
                   14504:         my ($multipart,$turnin,@pathitems);
                   14505:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14506:         if (defined($navmap)) {
                   14507:             my $mapres = $navmap->getResourceByUrl($map);
                   14508:             if (ref($mapres)) {
                   14509:                 my $pcslist = $mapres->map_hierarchy();
                   14510:                 if ($pcslist ne '') {
                   14511:                     foreach my $pc (split(/,/,$pcslist)) {
                   14512:                         my $res = $navmap->getByMapPc($pc);
                   14513:                         if (ref($res)) {
                   14514:                             my $title = $res->compTitle();
                   14515:                             $title =~ s/\W+/_/g;
                   14516:                             if ($title ne '') {
1.1149    raeburn  14517:                                 if (($pc > 1) && (length($title) > 12)) {
                   14518:                                     $title = substr($title,0,12);
                   14519:                                 }
1.1015    raeburn  14520:                                 push(@pathitems,$title);
                   14521:                             }
                   14522:                         }
                   14523:                     }
                   14524:                 }
                   14525:                 my $maptitle = $mapres->compTitle();
                   14526:                 $maptitle =~ s/\W+/_/g;
                   14527:                 if ($maptitle ne '') {
1.1149    raeburn  14528:                     if (length($maptitle) > 12) {
                   14529:                         $maptitle = substr($maptitle,0,12);
                   14530:                     }
1.1015    raeburn  14531:                     push(@pathitems,$maptitle);
                   14532:                 }
                   14533:                 unless ($env{'request.state'} eq 'construct') {
                   14534:                     my $res = $navmap->getBySymb($symb);
                   14535:                     if (ref($res)) {
                   14536:                         my $partlist = $res->parts();
                   14537:                         my $totaluploads = 0;
                   14538:                         if (ref($partlist) eq 'ARRAY') {
                   14539:                             foreach my $part (@{$partlist}) {
                   14540:                                 my @types = $res->responseType($part);
                   14541:                                 my @ids = $res->responseIds($part);
                   14542:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14543:                                     if ($types[$i] eq 'essay') {
                   14544:                                         my $partid = $part.'_'.$ids[$i];
                   14545:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14546:                                             $totaluploads ++;
                   14547:                                         }
                   14548:                                     }
                   14549:                                 }
                   14550:                             }
                   14551:                             if ($totaluploads > 1) {
                   14552:                                 $multiresp = 1;
                   14553:                             }
                   14554:                         }
                   14555:                     }
                   14556:                 }
                   14557:             } else {
                   14558:                 return;
                   14559:             }
                   14560:         } else {
                   14561:             return;
                   14562:         }
                   14563:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14564:         $restitle =~ s/\W+/_/g;
                   14565:         if ($restitle eq '') {
                   14566:             $restitle = ($resurl =~ m{/[^/]+$});
                   14567:             if ($restitle eq '') {
                   14568:                 $restitle = time;
                   14569:             }
                   14570:         }
1.1149    raeburn  14571:         if (length($restitle) > 12) {
                   14572:             $restitle = substr($restitle,0,12);
                   14573:         }
1.1015    raeburn  14574:         push(@pathitems,$restitle);
                   14575:         $path .= join('/',@pathitems);
                   14576:     }
                   14577:     return ($path,$multiresp);
                   14578: }
                   14579: 
                   14580: =pod
                   14581: 
1.464     albertel 14582: =back
1.41      ng       14583: 
1.112     bowersj2 14584: =head1 CSV Upload/Handling functions
1.38      albertel 14585: 
1.41      ng       14586: =over 4
                   14587: 
1.648     raeburn  14588: =item * &upfile_store($r)
1.41      ng       14589: 
                   14590: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14591: needs $env{'form.upfile'}
1.41      ng       14592: returns $datatoken to be put into hidden field
                   14593: 
                   14594: =cut
1.31      albertel 14595: 
                   14596: sub upfile_store {
                   14597:     my $r=shift;
1.258     albertel 14598:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14599:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14600:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14601:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14602: 
1.1299    raeburn  14603:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14604:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14605:                                      time.'_'.$$);
                   14606:     return if ($datatoken eq '');
                   14607: 
1.31      albertel 14608:     {
1.158     raeburn  14609:         my $datafile = $r->dir_config('lonDaemons').
                   14610:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14611:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14612:             print $fh $env{'form.upfile'};
1.158     raeburn  14613:             close($fh);
                   14614:         }
1.31      albertel 14615:     }
                   14616:     return $datatoken;
                   14617: }
                   14618: 
1.56      matthew  14619: =pod
                   14620: 
1.1290    raeburn  14621: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14622: 
                   14623: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  14624: $datatoken is the name to assign to the temporary file.
1.258     albertel 14625: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14626: 
                   14627: =cut
1.31      albertel 14628: 
                   14629: sub load_tmp_file {
1.1290    raeburn  14630:     my ($r,$datatoken) = @_;
                   14631:     return if ($datatoken eq '');
1.31      albertel 14632:     my @studentdata=();
                   14633:     {
1.158     raeburn  14634:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  14635:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  14636:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14637:             @studentdata=<$fh>;
                   14638:             close($fh);
                   14639:         }
1.31      albertel 14640:     }
1.258     albertel 14641:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14642: }
                   14643: 
1.1290    raeburn  14644: sub valid_datatoken {
                   14645:     my ($datatoken) = @_;
1.1325    raeburn  14646:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  14647:         return $datatoken;
                   14648:     }
                   14649:     return;
                   14650: }
                   14651: 
1.56      matthew  14652: =pod
                   14653: 
1.648     raeburn  14654: =item * &upfile_record_sep()
1.41      ng       14655: 
                   14656: Separate uploaded file into records
                   14657: returns array of records,
1.258     albertel 14658: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14659: 
                   14660: =cut
1.31      albertel 14661: 
                   14662: sub upfile_record_sep {
1.258     albertel 14663:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14664:     } else {
1.248     albertel 14665: 	my @records;
1.258     albertel 14666: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14667: 	    if ($line=~/^\s*$/) { next; }
                   14668: 	    push(@records,$line);
                   14669: 	}
                   14670: 	return @records;
1.31      albertel 14671:     }
                   14672: }
                   14673: 
1.56      matthew  14674: =pod
                   14675: 
1.648     raeburn  14676: =item * &record_sep($record)
1.41      ng       14677: 
1.258     albertel 14678: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14679: 
                   14680: =cut
                   14681: 
1.263     www      14682: sub takeleft {
                   14683:     my $index=shift;
                   14684:     return substr('0000'.$index,-4,4);
                   14685: }
                   14686: 
1.31      albertel 14687: sub record_sep {
                   14688:     my $record=shift;
                   14689:     my %components=();
1.258     albertel 14690:     if ($env{'form.upfiletype'} eq 'xml') {
                   14691:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14692:         my $i=0;
1.356     albertel 14693:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14694:             $field=~s/^(\"|\')//;
                   14695:             $field=~s/(\"|\')$//;
1.263     www      14696:             $components{&takeleft($i)}=$field;
1.31      albertel 14697:             $i++;
                   14698:         }
1.258     albertel 14699:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14700:         my $i=0;
1.356     albertel 14701:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14702:             $field=~s/^(\"|\')//;
                   14703:             $field=~s/(\"|\')$//;
1.263     www      14704:             $components{&takeleft($i)}=$field;
1.31      albertel 14705:             $i++;
                   14706:         }
                   14707:     } else {
1.561     www      14708:         my $separator=',';
1.480     banghart 14709:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14710:             $separator=';';
1.480     banghart 14711:         }
1.31      albertel 14712:         my $i=0;
1.561     www      14713: # the character we are looking for to indicate the end of a quote or a record 
                   14714:         my $looking_for=$separator;
                   14715: # do not add the characters to the fields
                   14716:         my $ignore=0;
                   14717: # we just encountered a separator (or the beginning of the record)
                   14718:         my $just_found_separator=1;
                   14719: # store the field we are working on here
                   14720:         my $field='';
                   14721: # work our way through all characters in record
                   14722:         foreach my $character ($record=~/(.)/g) {
                   14723:             if ($character eq $looking_for) {
                   14724:                if ($character ne $separator) {
                   14725: # Found the end of a quote, again looking for separator
                   14726:                   $looking_for=$separator;
                   14727:                   $ignore=1;
                   14728:                } else {
                   14729: # Found a separator, store away what we got
                   14730:                   $components{&takeleft($i)}=$field;
                   14731: 	          $i++;
                   14732:                   $just_found_separator=1;
                   14733:                   $ignore=0;
                   14734:                   $field='';
                   14735:                }
                   14736:                next;
                   14737:             }
                   14738: # single or double quotation marks after a separator indicate beginning of a quote
                   14739: # we are now looking for the end of the quote and need to ignore separators
                   14740:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14741:                $looking_for=$character;
                   14742:                next;
                   14743:             }
                   14744: # ignore would be true after we reached the end of a quote
                   14745:             if ($ignore) { next; }
                   14746:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14747:             $field.=$character;
                   14748:             $just_found_separator=0; 
1.31      albertel 14749:         }
1.561     www      14750: # catch the very last entry, since we never encountered the separator
                   14751:         $components{&takeleft($i)}=$field;
1.31      albertel 14752:     }
                   14753:     return %components;
                   14754: }
                   14755: 
1.144     matthew  14756: ######################################################
                   14757: ######################################################
                   14758: 
1.56      matthew  14759: =pod
                   14760: 
1.648     raeburn  14761: =item * &upfile_select_html()
1.41      ng       14762: 
1.144     matthew  14763: Return HTML code to select a file from the users machine and specify 
                   14764: the file type.
1.41      ng       14765: 
                   14766: =cut
                   14767: 
1.144     matthew  14768: ######################################################
                   14769: ######################################################
1.31      albertel 14770: sub upfile_select_html {
1.144     matthew  14771:     my %Types = (
                   14772:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14773:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14774:                  space => &mt('Space separated'),
                   14775:                  tab   => &mt('Tabulator separated'),
                   14776: #                 xml   => &mt('HTML/XML'),
                   14777:                  );
                   14778:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14779:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14780:     foreach my $type (sort(keys(%Types))) {
                   14781:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14782:     }
                   14783:     $Str .= "</select>\n";
                   14784:     return $Str;
1.31      albertel 14785: }
                   14786: 
1.301     albertel 14787: sub get_samples {
                   14788:     my ($records,$toget) = @_;
                   14789:     my @samples=({});
                   14790:     my $got=0;
                   14791:     foreach my $rec (@$records) {
                   14792: 	my %temp = &record_sep($rec);
                   14793: 	if (! grep(/\S/, values(%temp))) { next; }
                   14794: 	if (%temp) {
                   14795: 	    $samples[$got]=\%temp;
                   14796: 	    $got++;
                   14797: 	    if ($got == $toget) { last; }
                   14798: 	}
                   14799:     }
                   14800:     return \@samples;
                   14801: }
                   14802: 
1.144     matthew  14803: ######################################################
                   14804: ######################################################
                   14805: 
1.56      matthew  14806: =pod
                   14807: 
1.648     raeburn  14808: =item * &csv_print_samples($r,$records)
1.41      ng       14809: 
                   14810: Prints a table of sample values from each column uploaded $r is an
                   14811: Apache Request ref, $records is an arrayref from
                   14812: &Apache::loncommon::upfile_record_sep
                   14813: 
                   14814: =cut
                   14815: 
1.144     matthew  14816: ######################################################
                   14817: ######################################################
1.31      albertel 14818: sub csv_print_samples {
                   14819:     my ($r,$records) = @_;
1.662     bisitz   14820:     my $samples = &get_samples($records,5);
1.301     albertel 14821: 
1.594     raeburn  14822:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14823:               &start_data_table_header_row());
1.356     albertel 14824:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14825:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14826:     $r->print(&end_data_table_header_row());
1.301     albertel 14827:     foreach my $hash (@$samples) {
1.594     raeburn  14828: 	$r->print(&start_data_table_row());
1.356     albertel 14829: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14830: 	    $r->print('<td>');
1.356     albertel 14831: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14832: 	    $r->print('</td>');
                   14833: 	}
1.594     raeburn  14834: 	$r->print(&end_data_table_row());
1.31      albertel 14835:     }
1.594     raeburn  14836:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14837: }
                   14838: 
1.144     matthew  14839: ######################################################
                   14840: ######################################################
                   14841: 
1.56      matthew  14842: =pod
                   14843: 
1.648     raeburn  14844: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14845: 
                   14846: Prints a table to create associations between values and table columns.
1.144     matthew  14847: 
1.41      ng       14848: $r is an Apache Request ref,
                   14849: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14850: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14851: 
                   14852: =cut
                   14853: 
1.144     matthew  14854: ######################################################
                   14855: ######################################################
1.31      albertel 14856: sub csv_print_select_table {
                   14857:     my ($r,$records,$d) = @_;
1.301     albertel 14858:     my $i=0;
                   14859:     my $samples = &get_samples($records,1);
1.144     matthew  14860:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14861: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14862:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14863:               '<th>'.&mt('Column').'</th>'.
                   14864:               &end_data_table_header_row()."\n");
1.356     albertel 14865:     foreach my $array_ref (@$d) {
                   14866: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14867: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14868: 
1.875     bisitz   14869: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14870: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14871: 	$r->print('<option value="none"></option>');
1.356     albertel 14872: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14873: 	    $r->print('<option value="'.$sample.'"'.
                   14874:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14875:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14876: 	}
1.594     raeburn  14877: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14878: 	$i++;
                   14879:     }
1.594     raeburn  14880:     $r->print(&end_data_table());
1.31      albertel 14881:     $i--;
                   14882:     return $i;
                   14883: }
1.56      matthew  14884: 
1.144     matthew  14885: ######################################################
                   14886: ######################################################
                   14887: 
1.56      matthew  14888: =pod
1.31      albertel 14889: 
1.648     raeburn  14890: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14891: 
                   14892: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14893: 
                   14894: $r is an Apache Request ref,
                   14895: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14896: $d is an array of 2 element arrays (internal name, displayed name)
                   14897: 
                   14898: =cut
                   14899: 
1.144     matthew  14900: ######################################################
                   14901: ######################################################
1.31      albertel 14902: sub csv_samples_select_table {
                   14903:     my ($r,$records,$d) = @_;
                   14904:     my $i=0;
1.144     matthew  14905:     #
1.662     bisitz   14906:     my $max_samples = 5;
                   14907:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14908:     $r->print(&start_data_table().
                   14909:               &start_data_table_header_row().'<th>'.
                   14910:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14911:               &end_data_table_header_row());
1.301     albertel 14912: 
                   14913:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14914: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14915: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14916: 	foreach my $option (@$d) {
                   14917: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14918: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14919:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14920:                       $display.'</option>');
1.31      albertel 14921: 	}
                   14922: 	$r->print('</select></td><td>');
1.662     bisitz   14923: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14924: 	    if (defined($samples->[$line]{$key})) { 
                   14925: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14926: 	    }
                   14927: 	}
1.594     raeburn  14928: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14929: 	$i++;
                   14930:     }
1.594     raeburn  14931:     $r->print(&end_data_table());
1.31      albertel 14932:     $i--;
                   14933:     return($i);
1.115     matthew  14934: }
                   14935: 
1.144     matthew  14936: ######################################################
                   14937: ######################################################
                   14938: 
1.115     matthew  14939: =pod
                   14940: 
1.648     raeburn  14941: =item * &clean_excel_name($name)
1.115     matthew  14942: 
                   14943: Returns a replacement for $name which does not contain any illegal characters.
                   14944: 
                   14945: =cut
                   14946: 
1.144     matthew  14947: ######################################################
                   14948: ######################################################
1.115     matthew  14949: sub clean_excel_name {
                   14950:     my ($name) = @_;
                   14951:     $name =~ s/[:\*\?\/\\]//g;
                   14952:     if (length($name) > 31) {
                   14953:         $name = substr($name,0,31);
                   14954:     }
                   14955:     return $name;
1.25      albertel 14956: }
1.84      albertel 14957: 
1.85      albertel 14958: =pod
                   14959: 
1.648     raeburn  14960: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14961: 
                   14962: Returns either 1 or undef
                   14963: 
                   14964: 1 if the part is to be hidden, undef if it is to be shown
                   14965: 
                   14966: Arguments are:
                   14967: 
                   14968: $id the id of the part to be checked
                   14969: $symb, optional the symb of the resource to check
                   14970: $udom, optional the domain of the user to check for
                   14971: $uname, optional the username of the user to check for
                   14972: 
                   14973: =cut
1.84      albertel 14974: 
                   14975: sub check_if_partid_hidden {
                   14976:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14977:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14978: 					 $symb,$udom,$uname);
1.141     albertel 14979:     my $truth=1;
                   14980:     #if the string starts with !, then the list is the list to show not hide
                   14981:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14982:     my @hiddenlist=split(/,/,$hiddenparts);
                   14983:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14984: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14985:     }
1.141     albertel 14986:     return !$truth;
1.84      albertel 14987: }
1.127     matthew  14988: 
1.138     matthew  14989: 
                   14990: ############################################################
                   14991: ############################################################
                   14992: 
                   14993: =pod
                   14994: 
1.157     matthew  14995: =back 
                   14996: 
1.138     matthew  14997: =head1 cgi-bin script and graphing routines
                   14998: 
1.157     matthew  14999: =over 4
                   15000: 
1.648     raeburn  15001: =item * &get_cgi_id()
1.138     matthew  15002: 
                   15003: Inputs: none
                   15004: 
                   15005: Returns an id which can be used to pass environment variables
                   15006: to various cgi-bin scripts.  These environment variables will
                   15007: be removed from the users environment after a given time by
                   15008: the routine &Apache::lonnet::transfer_profile_to_env.
                   15009: 
                   15010: =cut
                   15011: 
                   15012: ############################################################
                   15013: ############################################################
1.152     albertel 15014: my $uniq=0;
1.136     matthew  15015: sub get_cgi_id {
1.154     albertel 15016:     $uniq=($uniq+1)%100000;
1.280     albertel 15017:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15018: }
                   15019: 
1.127     matthew  15020: ############################################################
                   15021: ############################################################
                   15022: 
                   15023: =pod
                   15024: 
1.648     raeburn  15025: =item * &DrawBarGraph()
1.127     matthew  15026: 
1.138     matthew  15027: Facilitates the plotting of data in a (stacked) bar graph.
                   15028: Puts plot definition data into the users environment in order for 
                   15029: graph.png to plot it.  Returns an <img> tag for the plot.
                   15030: The bars on the plot are labeled '1','2',...,'n'.
                   15031: 
                   15032: Inputs:
                   15033: 
                   15034: =over 4
                   15035: 
                   15036: =item $Title: string, the title of the plot
                   15037: 
                   15038: =item $xlabel: string, text describing the X-axis of the plot
                   15039: 
                   15040: =item $ylabel: string, text describing the Y-axis of the plot
                   15041: 
                   15042: =item $Max: scalar, the maximum Y value to use in the plot
                   15043: If $Max is < any data point, the graph will not be rendered.
                   15044: 
1.140     matthew  15045: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15046: they are plotted.  If undefined, default values will be used.
                   15047: 
1.178     matthew  15048: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15049: 
1.138     matthew  15050: =item @Values: An array of array references.  Each array reference holds data
                   15051: to be plotted in a stacked bar chart.
                   15052: 
1.239     matthew  15053: =item If the final element of @Values is a hash reference the key/value
                   15054: pairs will be added to the graph definition.
                   15055: 
1.138     matthew  15056: =back
                   15057: 
                   15058: Returns:
                   15059: 
                   15060: An <img> tag which references graph.png and the appropriate identifying
                   15061: information for the plot.
                   15062: 
1.127     matthew  15063: =cut
                   15064: 
                   15065: ############################################################
                   15066: ############################################################
1.134     matthew  15067: sub DrawBarGraph {
1.178     matthew  15068:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15069:     #
                   15070:     if (! defined($colors)) {
                   15071:         $colors = ['#33ff00', 
                   15072:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15073:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15074:                   ]; 
                   15075:     }
1.228     matthew  15076:     my $extra_settings = {};
                   15077:     if (ref($Values[-1]) eq 'HASH') {
                   15078:         $extra_settings = pop(@Values);
                   15079:     }
1.127     matthew  15080:     #
1.136     matthew  15081:     my $identifier = &get_cgi_id();
                   15082:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15083:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15084:         return '';
                   15085:     }
1.225     matthew  15086:     #
                   15087:     my @Labels;
                   15088:     if (defined($labels)) {
                   15089:         @Labels = @$labels;
                   15090:     } else {
                   15091:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15092:             push(@Labels,$i+1);
1.225     matthew  15093:         }
                   15094:     }
                   15095:     #
1.129     matthew  15096:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15097:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15098:     my %ValuesHash;
                   15099:     my $NumSets=1;
                   15100:     foreach my $array (@Values) {
                   15101:         next if (! ref($array));
1.136     matthew  15102:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15103:             join(',',@$array);
1.129     matthew  15104:     }
1.127     matthew  15105:     #
1.136     matthew  15106:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15107:     if ($NumBars < 3) {
                   15108:         $width = 120+$NumBars*32;
1.220     matthew  15109:         $xskip = 1;
1.225     matthew  15110:         $bar_width = 30;
                   15111:     } elsif ($NumBars < 5) {
                   15112:         $width = 120+$NumBars*20;
                   15113:         $xskip = 1;
                   15114:         $bar_width = 20;
1.220     matthew  15115:     } elsif ($NumBars < 10) {
1.136     matthew  15116:         $width = 120+$NumBars*15;
                   15117:         $xskip = 1;
                   15118:         $bar_width = 15;
                   15119:     } elsif ($NumBars <= 25) {
                   15120:         $width = 120+$NumBars*11;
                   15121:         $xskip = 5;
                   15122:         $bar_width = 8;
                   15123:     } elsif ($NumBars <= 50) {
                   15124:         $width = 120+$NumBars*8;
                   15125:         $xskip = 5;
                   15126:         $bar_width = 4;
                   15127:     } else {
                   15128:         $width = 120+$NumBars*8;
                   15129:         $xskip = 5;
                   15130:         $bar_width = 4;
                   15131:     }
                   15132:     #
1.137     matthew  15133:     $Max = 1 if ($Max < 1);
                   15134:     if ( int($Max) < $Max ) {
                   15135:         $Max++;
                   15136:         $Max = int($Max);
                   15137:     }
1.127     matthew  15138:     $Title  = '' if (! defined($Title));
                   15139:     $xlabel = '' if (! defined($xlabel));
                   15140:     $ylabel = '' if (! defined($ylabel));
1.369     www      15141:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15142:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15143:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15144:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15145:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15146:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15147:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15148:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15149:     $ValuesHash{$id.'.height'}   = $height;
                   15150:     $ValuesHash{$id.'.width'}    = $width;
                   15151:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15152:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15153:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15154:     #
1.228     matthew  15155:     # Deal with other parameters
                   15156:     while (my ($key,$value) = each(%$extra_settings)) {
                   15157:         $ValuesHash{$id.'.'.$key} = $value;
                   15158:     }
                   15159:     #
1.646     raeburn  15160:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15161:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15162: }
                   15163: 
                   15164: ############################################################
                   15165: ############################################################
                   15166: 
                   15167: =pod
                   15168: 
1.648     raeburn  15169: =item * &DrawXYGraph()
1.137     matthew  15170: 
1.138     matthew  15171: Facilitates the plotting of data in an XY graph.
                   15172: Puts plot definition data into the users environment in order for 
                   15173: graph.png to plot it.  Returns an <img> tag for the plot.
                   15174: 
                   15175: Inputs:
                   15176: 
                   15177: =over 4
                   15178: 
                   15179: =item $Title: string, the title of the plot
                   15180: 
                   15181: =item $xlabel: string, text describing the X-axis of the plot
                   15182: 
                   15183: =item $ylabel: string, text describing the Y-axis of the plot
                   15184: 
                   15185: =item $Max: scalar, the maximum Y value to use in the plot
                   15186: If $Max is < any data point, the graph will not be rendered.
                   15187: 
                   15188: =item $colors: Array ref containing the hex color codes for the data to be 
                   15189: plotted in.  If undefined, default values will be used.
                   15190: 
                   15191: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15192: 
                   15193: =item $Ydata: Array ref containing Array refs.  
1.185     www      15194: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15195: 
                   15196: =item %Values: hash indicating or overriding any default values which are 
                   15197: passed to graph.png.  
                   15198: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15199: 
                   15200: =back
                   15201: 
                   15202: Returns:
                   15203: 
                   15204: An <img> tag which references graph.png and the appropriate identifying
                   15205: information for the plot.
                   15206: 
1.137     matthew  15207: =cut
                   15208: 
                   15209: ############################################################
                   15210: ############################################################
                   15211: sub DrawXYGraph {
                   15212:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15213:     #
                   15214:     # Create the identifier for the graph
                   15215:     my $identifier = &get_cgi_id();
                   15216:     my $id = 'cgi.'.$identifier;
                   15217:     #
                   15218:     $Title  = '' if (! defined($Title));
                   15219:     $xlabel = '' if (! defined($xlabel));
                   15220:     $ylabel = '' if (! defined($ylabel));
                   15221:     my %ValuesHash = 
                   15222:         (
1.369     www      15223:          $id.'.title'  => &escape($Title),
                   15224:          $id.'.xlabel' => &escape($xlabel),
                   15225:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15226:          $id.'.y_max_value'=> $Max,
                   15227:          $id.'.labels'     => join(',',@$Xlabels),
                   15228:          $id.'.PlotType'   => 'XY',
                   15229:          );
                   15230:     #
                   15231:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15232:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15233:     }
                   15234:     #
                   15235:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15236:         return '';
                   15237:     }
                   15238:     my $NumSets=1;
1.138     matthew  15239:     foreach my $array (@{$Ydata}){
1.137     matthew  15240:         next if (! ref($array));
                   15241:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15242:     }
1.138     matthew  15243:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15244:     #
                   15245:     # Deal with other parameters
                   15246:     while (my ($key,$value) = each(%Values)) {
                   15247:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15248:     }
                   15249:     #
1.646     raeburn  15250:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15251:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15252: }
                   15253: 
                   15254: ############################################################
                   15255: ############################################################
                   15256: 
                   15257: =pod
                   15258: 
1.648     raeburn  15259: =item * &DrawXYYGraph()
1.138     matthew  15260: 
                   15261: Facilitates the plotting of data in an XY graph with two Y axes.
                   15262: Puts plot definition data into the users environment in order for 
                   15263: graph.png to plot it.  Returns an <img> tag for the plot.
                   15264: 
                   15265: Inputs:
                   15266: 
                   15267: =over 4
                   15268: 
                   15269: =item $Title: string, the title of the plot
                   15270: 
                   15271: =item $xlabel: string, text describing the X-axis of the plot
                   15272: 
                   15273: =item $ylabel: string, text describing the Y-axis of the plot
                   15274: 
                   15275: =item $colors: Array ref containing the hex color codes for the data to be 
                   15276: plotted in.  If undefined, default values will be used.
                   15277: 
                   15278: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15279: 
                   15280: =item $Ydata1: The first data set
                   15281: 
                   15282: =item $Min1: The minimum value of the left Y-axis
                   15283: 
                   15284: =item $Max1: The maximum value of the left Y-axis
                   15285: 
                   15286: =item $Ydata2: The second data set
                   15287: 
                   15288: =item $Min2: The minimum value of the right Y-axis
                   15289: 
                   15290: =item $Max2: The maximum value of the left Y-axis
                   15291: 
                   15292: =item %Values: hash indicating or overriding any default values which are 
                   15293: passed to graph.png.  
                   15294: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15295: 
                   15296: =back
                   15297: 
                   15298: Returns:
                   15299: 
                   15300: An <img> tag which references graph.png and the appropriate identifying
                   15301: information for the plot.
1.136     matthew  15302: 
                   15303: =cut
                   15304: 
                   15305: ############################################################
                   15306: ############################################################
1.137     matthew  15307: sub DrawXYYGraph {
                   15308:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15309:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15310:     #
                   15311:     # Create the identifier for the graph
                   15312:     my $identifier = &get_cgi_id();
                   15313:     my $id = 'cgi.'.$identifier;
                   15314:     #
                   15315:     $Title  = '' if (! defined($Title));
                   15316:     $xlabel = '' if (! defined($xlabel));
                   15317:     $ylabel = '' if (! defined($ylabel));
                   15318:     my %ValuesHash = 
                   15319:         (
1.369     www      15320:          $id.'.title'  => &escape($Title),
                   15321:          $id.'.xlabel' => &escape($xlabel),
                   15322:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15323:          $id.'.labels' => join(',',@$Xlabels),
                   15324:          $id.'.PlotType' => 'XY',
                   15325:          $id.'.NumSets' => 2,
1.137     matthew  15326:          $id.'.two_axes' => 1,
                   15327:          $id.'.y1_max_value' => $Max1,
                   15328:          $id.'.y1_min_value' => $Min1,
                   15329:          $id.'.y2_max_value' => $Max2,
                   15330:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15331:          );
                   15332:     #
1.137     matthew  15333:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15334:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15335:     }
                   15336:     #
                   15337:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15338:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15339:         return '';
                   15340:     }
                   15341:     my $NumSets=1;
1.137     matthew  15342:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15343:         next if (! ref($array));
                   15344:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15345:     }
                   15346:     #
                   15347:     # Deal with other parameters
                   15348:     while (my ($key,$value) = each(%Values)) {
                   15349:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15350:     }
                   15351:     #
1.646     raeburn  15352:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15353:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15354: }
                   15355: 
                   15356: ############################################################
                   15357: ############################################################
                   15358: 
                   15359: =pod
                   15360: 
1.157     matthew  15361: =back 
                   15362: 
1.139     matthew  15363: =head1 Statistics helper routines?  
                   15364: 
                   15365: Bad place for them but what the hell.
                   15366: 
1.157     matthew  15367: =over 4
                   15368: 
1.648     raeburn  15369: =item * &chartlink()
1.139     matthew  15370: 
                   15371: Returns a link to the chart for a specific student.  
                   15372: 
                   15373: Inputs:
                   15374: 
                   15375: =over 4
                   15376: 
                   15377: =item $linktext: The text of the link
                   15378: 
                   15379: =item $sname: The students username
                   15380: 
                   15381: =item $sdomain: The students domain
                   15382: 
                   15383: =back
                   15384: 
1.157     matthew  15385: =back
                   15386: 
1.139     matthew  15387: =cut
                   15388: 
                   15389: ############################################################
                   15390: ############################################################
                   15391: sub chartlink {
                   15392:     my ($linktext, $sname, $sdomain) = @_;
                   15393:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15394:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15395:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15396:        '">'.$linktext.'</a>';
1.153     matthew  15397: }
                   15398: 
                   15399: #######################################################
                   15400: #######################################################
                   15401: 
                   15402: =pod
                   15403: 
                   15404: =head1 Course Environment Routines
1.157     matthew  15405: 
                   15406: =over 4
1.153     matthew  15407: 
1.648     raeburn  15408: =item * &restore_course_settings()
1.153     matthew  15409: 
1.648     raeburn  15410: =item * &store_course_settings()
1.153     matthew  15411: 
                   15412: Restores/Store indicated form parameters from the course environment.
                   15413: Will not overwrite existing values of the form parameters.
                   15414: 
                   15415: Inputs: 
                   15416: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15417: 
                   15418: a hash ref describing the data to be stored.  For example:
                   15419:    
                   15420: %Save_Parameters = ('Status' => 'scalar',
                   15421:     'chartoutputmode' => 'scalar',
                   15422:     'chartoutputdata' => 'scalar',
                   15423:     'Section' => 'array',
1.373     raeburn  15424:     'Group' => 'array',
1.153     matthew  15425:     'StudentData' => 'array',
                   15426:     'Maps' => 'array');
                   15427: 
                   15428: Returns: both routines return nothing
                   15429: 
1.631     raeburn  15430: =back
                   15431: 
1.153     matthew  15432: =cut
                   15433: 
                   15434: #######################################################
                   15435: #######################################################
                   15436: sub store_course_settings {
1.496     albertel 15437:     return &store_settings($env{'request.course.id'},@_);
                   15438: }
                   15439: 
                   15440: sub store_settings {
1.153     matthew  15441:     # save to the environment
                   15442:     # appenv the same items, just to be safe
1.300     albertel 15443:     my $udom  = $env{'user.domain'};
                   15444:     my $uname = $env{'user.name'};
1.496     albertel 15445:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15446:     my %SaveHash;
                   15447:     my %AppHash;
                   15448:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15449:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15450:         my $envname = 'environment.'.$basename;
1.258     albertel 15451:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15452:             # Save this value away
                   15453:             if ($type eq 'scalar' &&
1.258     albertel 15454:                 (! exists($env{$envname}) || 
                   15455:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15456:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15457:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15458:             } elsif ($type eq 'array') {
                   15459:                 my $stored_form;
1.258     albertel 15460:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15461:                     $stored_form = join(',',
                   15462:                                         map {
1.369     www      15463:                                             &escape($_);
1.258     albertel 15464:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15465:                 } else {
                   15466:                     $stored_form = 
1.369     www      15467:                         &escape($env{'form.'.$setting});
1.153     matthew  15468:                 }
                   15469:                 # Determine if the array contents are the same.
1.258     albertel 15470:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  15471:                     $SaveHash{$basename} = $stored_form;
                   15472:                     $AppHash{$envname}   = $stored_form;
                   15473:                 }
                   15474:             }
                   15475:         }
                   15476:     }
                   15477:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 15478:                                           $udom,$uname);
1.153     matthew  15479:     if ($put_result !~ /^(ok|delayed)/) {
                   15480:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   15481:                                  'got error:'.$put_result);
                   15482:     }
                   15483:     # Make sure these settings stick around in this session, too
1.646     raeburn  15484:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15485:     return;
                   15486: }
                   15487: 
                   15488: sub restore_course_settings {
1.499     albertel 15489:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15490: }
                   15491: 
                   15492: sub restore_settings {
                   15493:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15494:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15495:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15496:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15497:             '.'.$setting;
1.258     albertel 15498:         if (exists($env{$envname})) {
1.153     matthew  15499:             if ($type eq 'scalar') {
1.258     albertel 15500:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15501:             } elsif ($type eq 'array') {
1.258     albertel 15502:                 $env{'form.'.$setting} = [ 
1.153     matthew  15503:                                            map { 
1.369     www      15504:                                                &unescape($_); 
1.258     albertel 15505:                                            } split(',',$env{$envname})
1.153     matthew  15506:                                            ];
                   15507:             }
                   15508:         }
                   15509:     }
1.127     matthew  15510: }
                   15511: 
1.618     raeburn  15512: #######################################################
                   15513: #######################################################
                   15514: 
                   15515: =pod
                   15516: 
                   15517: =head1 Domain E-mail Routines  
                   15518: 
                   15519: =over 4
                   15520: 
1.648     raeburn  15521: =item * &build_recipient_list()
1.618     raeburn  15522: 
1.1144    raeburn  15523: Build recipient lists for following types of e-mail:
1.766     raeburn  15524: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  15525: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15526: module change checking, student/employee ID conflict checks, as
                   15527: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15528: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15529: 
                   15530: Inputs:
1.619     raeburn  15531: defmail (scalar - email address of default recipient), 
1.1144    raeburn  15532: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15533: requestsmail, updatesmail, or idconflictsmail).
                   15534: 
1.619     raeburn  15535: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  15536: 
1.619     raeburn  15537: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  15538: i.e., predates configuration by DC via domainprefs.pm
                   15539: 
                   15540: $requname username of requester (if mailing type is helpdeskmail)
                   15541: 
                   15542: $requdom domain of requester (if mailing type is helpdeskmail)
                   15543: 
                   15544: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15545: 
1.618     raeburn  15546: 
1.655     raeburn  15547: Returns: comma separated list of addresses to which to send e-mail.
                   15548: 
                   15549: =back
1.618     raeburn  15550: 
                   15551: =cut
                   15552: 
                   15553: ############################################################
                   15554: ############################################################
                   15555: sub build_recipient_list {
1.1297    raeburn  15556:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15557:     my @recipients;
1.1270    raeburn  15558:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15559:     my %domconfig =
1.1270    raeburn  15560:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15561:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15562:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15563:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15564:                 my @contacts = ('adminemail','supportemail');
                   15565:                 foreach my $item (@contacts) {
                   15566:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15567:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15568:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15569:                             push(@recipients,$addr);
                   15570:                         }
1.619     raeburn  15571:                     }
1.1270    raeburn  15572:                 }
                   15573:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15574:                 if ($mailing eq 'helpdeskmail') {
                   15575:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15576:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15577:                         my @ok_bccs;
                   15578:                         foreach my $bcc (@bccs) {
                   15579:                             $bcc =~ s/^\s+//g;
                   15580:                             $bcc =~ s/\s+$//g;
                   15581:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15582:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15583:                                     push(@ok_bccs,$bcc);
                   15584:                                 }
                   15585:                             }
                   15586:                         }
                   15587:                         if (@ok_bccs > 0) {
                   15588:                             $allbcc = join(', ',@ok_bccs);
                   15589:                         }
                   15590:                     }
                   15591:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15592:                 }
                   15593:             }
1.766     raeburn  15594:         } elsif ($origmail ne '') {
1.1270    raeburn  15595:             $lastresort = $origmail;
1.618     raeburn  15596:         }
1.1297    raeburn  15597:         if ($mailing eq 'helpdeskmail') {
                   15598:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15599:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15600:                 my ($inststatus,$inststatus_checked);
                   15601:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15602:                     ($env{'user.domain'} ne 'public')) {
                   15603:                     $inststatus_checked = 1;
                   15604:                     $inststatus = $env{'environment.inststatus'};
                   15605:                 }
                   15606:                 unless ($inststatus_checked) {
                   15607:                     if (($requname ne '') && ($requdom ne '')) {
                   15608:                         if (($requname =~ /^$match_username$/) &&
                   15609:                             ($requdom =~ /^$match_domain$/) &&
                   15610:                             (&Apache::lonnet::domain($requdom))) {
                   15611:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15612:                                                                       $requdom);
                   15613:                             unless ($requhome eq 'no_host') {
                   15614:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15615:                                 $inststatus = $userenv{'inststatus'};
                   15616:                                 $inststatus_checked = 1;
                   15617:                             }
                   15618:                         }
                   15619:                     }
                   15620:                 }
                   15621:                 unless ($inststatus_checked) {
                   15622:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15623:                         my %srch = (srchby     => 'email',
                   15624:                                     srchdomain => $defdom,
                   15625:                                     srchterm   => $reqemail,
                   15626:                                     srchtype   => 'exact');
                   15627:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15628:                         foreach my $uname (keys(%srch_results)) {
                   15629:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15630:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15631:                                 $inststatus_checked = 1;
                   15632:                                 last;
                   15633:                             }
                   15634:                         }
                   15635:                         unless ($inststatus_checked) {
                   15636:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15637:                             if ($dirsrchres eq 'ok') {
                   15638:                                 foreach my $uname (keys(%srch_results)) {
                   15639:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15640:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15641:                                         $inststatus_checked = 1;
                   15642:                                         last;
                   15643:                                     }
                   15644:                                 }
                   15645:                             }
                   15646:                         }
                   15647:                     }
                   15648:                 }
                   15649:                 if ($inststatus ne '') {
                   15650:                     foreach my $status (split(/\:/,$inststatus)) {
                   15651:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15652:                             my @contacts = ('adminemail','supportemail');
                   15653:                             foreach my $item (@contacts) {
                   15654:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15655:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15656:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15657:                                         push(@recipients,$addr);
                   15658:                                     }
                   15659:                                 }
                   15660:                             }
                   15661:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15662:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15663:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15664:                                 my @ok_bccs;
                   15665:                                 foreach my $bcc (@bccs) {
                   15666:                                     $bcc =~ s/^\s+//g;
                   15667:                                     $bcc =~ s/\s+$//g;
                   15668:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15669:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15670:                                             push(@ok_bccs,$bcc);
                   15671:                                         }
                   15672:                                     }
                   15673:                                 }
                   15674:                                 if (@ok_bccs > 0) {
                   15675:                                     $allbcc = join(', ',@ok_bccs);
                   15676:                                 }
                   15677:                             }
                   15678:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15679:                             last;
                   15680:                         }
                   15681:                     }
                   15682:                 }
                   15683:             }
                   15684:         }
1.619     raeburn  15685:     } elsif ($origmail ne '') {
1.1270    raeburn  15686:         $lastresort = $origmail;
                   15687:     }
1.1297    raeburn  15688:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  15689:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15690:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15691:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15692:             my %what = (
                   15693:                           perlvar => 1,
                   15694:                        );
                   15695:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15696:             if ($primary) {
                   15697:                 my $gotaddr;
                   15698:                 my ($result,$returnhash) =
                   15699:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15700:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15701:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15702:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15703:                         $gotaddr = 1;
                   15704:                     }
                   15705:                 }
                   15706:                 unless ($gotaddr) {
                   15707:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15708:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15709:                     unless ($uintdom eq $intdom) {
                   15710:                         my %domconfig =
                   15711:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15712:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15713:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15714:                                 my @contacts = ('adminemail','supportemail');
                   15715:                                 foreach my $item (@contacts) {
                   15716:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15717:                                         my $addr = $domconfig{'contacts'}{$item};
                   15718:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15719:                                             push(@recipients,$addr);
                   15720:                                         }
                   15721:                                     }
                   15722:                                 }
                   15723:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15724:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15725:                                 }
                   15726:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15727:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15728:                                     my @ok_bccs;
                   15729:                                     foreach my $bcc (@bccs) {
                   15730:                                         $bcc =~ s/^\s+//g;
                   15731:                                         $bcc =~ s/\s+$//g;
                   15732:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15733:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15734:                                                 push(@ok_bccs,$bcc);
                   15735:                                             }
                   15736:                                         }
                   15737:                                     }
                   15738:                                     if (@ok_bccs > 0) {
                   15739:                                         $allbcc = join(', ',@ok_bccs);
                   15740:                                     }
                   15741:                                 }
                   15742:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15743:                             }
                   15744:                         }
                   15745:                     }
                   15746:                 }
                   15747:             }
                   15748:         }
1.618     raeburn  15749:     }
1.688     raeburn  15750:     if (defined($defmail)) {
                   15751:         if ($defmail ne '') {
                   15752:             push(@recipients,$defmail);
                   15753:         }
1.618     raeburn  15754:     }
                   15755:     if ($otheremails) {
1.619     raeburn  15756:         my @others;
                   15757:         if ($otheremails =~ /,/) {
                   15758:             @others = split(/,/,$otheremails);
1.618     raeburn  15759:         } else {
1.619     raeburn  15760:             push(@others,$otheremails);
                   15761:         }
                   15762:         foreach my $addr (@others) {
                   15763:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15764:                 push(@recipients,$addr);
                   15765:             }
1.618     raeburn  15766:         }
                   15767:     }
1.1298    raeburn  15768:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  15769:         if ((!@recipients) && ($lastresort ne '')) {
                   15770:             push(@recipients,$lastresort);
                   15771:         }
                   15772:     } elsif ($lastresort ne '') {
                   15773:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15774:             push(@recipients,$lastresort);
                   15775:         }
                   15776:     }
1.1271    raeburn  15777:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  15778:     if (wantarray) {
                   15779:         return ($recipientlist,$allbcc,$addtext);
                   15780:     } else {
                   15781:         return $recipientlist;
                   15782:     }
1.618     raeburn  15783: }
                   15784: 
1.127     matthew  15785: ############################################################
                   15786: ############################################################
1.154     albertel 15787: 
1.655     raeburn  15788: =pod
                   15789: 
1.1224    musolffc 15790: =over 4
                   15791: 
1.1223    musolffc 15792: =item * &mime_email()
                   15793: 
                   15794: Sends an email with a possible attachment
                   15795: 
                   15796: Inputs:
                   15797: 
                   15798: =over 4
                   15799: 
                   15800: from -              Sender's email address
                   15801: 
1.1343    raeburn  15802: replyto -           Reply-To email address
                   15803: 
1.1223    musolffc 15804: to -                Email address of recipient
                   15805: 
                   15806: subject -           Subject of email
                   15807: 
                   15808: body -              Body of email
                   15809: 
                   15810: cc_string -         Carbon copy email address
                   15811: 
                   15812: bcc -               Blind carbon copy email address
                   15813: 
                   15814: attachment_path -   Path of file to be attached
                   15815: 
                   15816: file_name -         Name of file to be attached
                   15817: 
                   15818: attachment_text -   The body of an attachment of type "TEXT"
                   15819: 
                   15820: =back
                   15821: 
                   15822: =back
                   15823: 
                   15824: =cut
                   15825: 
                   15826: ############################################################
                   15827: ############################################################
                   15828: 
                   15829: sub mime_email {
1.1343    raeburn  15830:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   15831:         $file_name,$attachment_text) = @_;
                   15832:  
1.1223    musolffc 15833:     my $msg = MIME::Lite->new(
                   15834:              From    => $from,
                   15835:              To      => $to,
                   15836:              Subject => $subject,
                   15837:              Type    =>'TEXT',
                   15838:              Data    => $body,
                   15839:              );
1.1343    raeburn  15840:     if ($replyto ne '') {
                   15841:         $msg->add("Reply-To" => $replyto);
                   15842:     }
1.1223    musolffc 15843:     if ($cc_string ne '') {
                   15844:         $msg->add("Cc" => $cc_string);
                   15845:     }
                   15846:     if ($bcc ne '') {
                   15847:         $msg->add("Bcc" => $bcc);
                   15848:     }
                   15849:     $msg->attr("content-type"         => "text/plain");
                   15850:     $msg->attr("content-type.charset" => "UTF-8");
                   15851:     # Attach file if given
                   15852:     if ($attachment_path) {
                   15853:         unless ($file_name) {
                   15854:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   15855:         }
                   15856:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   15857:         $msg->attach(Type     => $type,
                   15858:                      Path     => $attachment_path,
                   15859:                      Filename => $file_name
                   15860:                      );
                   15861:     # Otherwise attach text if given
                   15862:     } elsif ($attachment_text) {
                   15863:         $msg->attach(Type => 'TEXT',
                   15864:                      Data => $attachment_text);
                   15865:     }
                   15866:     # Send it
                   15867:     $msg->send('sendmail');
                   15868: }
                   15869: 
                   15870: ############################################################
                   15871: ############################################################
                   15872: 
                   15873: =pod
                   15874: 
1.655     raeburn  15875: =head1 Course Catalog Routines
                   15876: 
                   15877: =over 4
                   15878: 
                   15879: =item * &gather_categories()
                   15880: 
                   15881: Converts category definitions - keys of categories hash stored in  
                   15882: coursecategories in configuration.db on the primary library server in a 
                   15883: domain - to an array.  Also generates javascript and idx hash used to 
                   15884: generate Domain Coordinator interface for editing Course Categories.
                   15885: 
                   15886: Inputs:
1.663     raeburn  15887: 
1.655     raeburn  15888: categories (reference to hash of category definitions).
1.663     raeburn  15889: 
1.655     raeburn  15890: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15891:       categories and subcategories).
1.663     raeburn  15892: 
1.655     raeburn  15893: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15894:       editing Course Categories).
1.663     raeburn  15895: 
1.655     raeburn  15896: jsarray (reference to array of categories used to create Javascript arrays for
                   15897:          Domain Coordinator interface for editing Course Categories).
                   15898: 
                   15899: Returns: nothing
                   15900: 
                   15901: Side effects: populates cats, idx and jsarray. 
                   15902: 
                   15903: =cut
                   15904: 
                   15905: sub gather_categories {
                   15906:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15907:     my %counters;
                   15908:     my $num = 0;
                   15909:     foreach my $item (keys(%{$categories})) {
                   15910:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15911:         if ($container eq '' && $depth == 0) {
                   15912:             $cats->[$depth][$categories->{$item}] = $cat;
                   15913:         } else {
                   15914:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15915:         }
                   15916:         my ($escitem,$tail) = split(/:/,$item,2);
                   15917:         if ($counters{$tail} eq '') {
                   15918:             $counters{$tail} = $num;
                   15919:             $num ++;
                   15920:         }
                   15921:         if (ref($idx) eq 'HASH') {
                   15922:             $idx->{$item} = $counters{$tail};
                   15923:         }
                   15924:         if (ref($jsarray) eq 'ARRAY') {
                   15925:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15926:         }
                   15927:     }
                   15928:     return;
                   15929: }
                   15930: 
                   15931: =pod
                   15932: 
                   15933: =item * &extract_categories()
                   15934: 
                   15935: Used to generate breadcrumb trails for course categories.
                   15936: 
                   15937: Inputs:
1.663     raeburn  15938: 
1.655     raeburn  15939: categories (reference to hash of category definitions).
1.663     raeburn  15940: 
1.655     raeburn  15941: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15942:       categories and subcategories).
1.663     raeburn  15943: 
1.655     raeburn  15944: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15945: 
1.655     raeburn  15946: allitems (reference to hash - key is category key 
                   15947:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15948: 
1.655     raeburn  15949: idx (reference to hash of counters used in Domain Coordinator interface for
                   15950:       editing Course Categories).
1.663     raeburn  15951: 
1.655     raeburn  15952: jsarray (reference to array of categories used to create Javascript arrays for
                   15953:          Domain Coordinator interface for editing Course Categories).
                   15954: 
1.665     raeburn  15955: subcats (reference to hash of arrays containing all subcategories within each 
                   15956:          category, -recursive)
                   15957: 
1.1321    raeburn  15958: maxd (reference to hash used to hold max depth for all top-level categories).
                   15959: 
1.655     raeburn  15960: Returns: nothing
                   15961: 
                   15962: Side effects: populates trails and allitems hash references.
                   15963: 
                   15964: =cut
                   15965: 
                   15966: sub extract_categories {
1.1321    raeburn  15967:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15968:     if (ref($categories) eq 'HASH') {
                   15969:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15970:         if (ref($cats->[0]) eq 'ARRAY') {
                   15971:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15972:                 my $name = $cats->[0][$i];
                   15973:                 my $item = &escape($name).'::0';
                   15974:                 my $trailstr;
                   15975:                 if ($name eq 'instcode') {
                   15976:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15977:                 } elsif ($name eq 'communities') {
                   15978:                     $trailstr = &mt('Communities');
1.1239    raeburn  15979:                 } elsif ($name eq 'placement') {
                   15980:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  15981:                 } else {
                   15982:                     $trailstr = $name;
                   15983:                 }
                   15984:                 if ($allitems->{$item} eq '') {
                   15985:                     push(@{$trails},$trailstr);
                   15986:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15987:                 }
                   15988:                 my @parents = ($name);
                   15989:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15990:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15991:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15992:                         if (ref($subcats) eq 'HASH') {
                   15993:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15994:                         }
1.1321    raeburn  15995:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15996:                     }
                   15997:                 } else {
                   15998:                     if (ref($subcats) eq 'HASH') {
                   15999:                         $subcats->{$item} = [];
1.655     raeburn  16000:                     }
1.1321    raeburn  16001:                     if (ref($maxd) eq 'HASH') {
                   16002:                         $maxd->{$name} = 1;
                   16003:                     }
1.655     raeburn  16004:                 }
                   16005:             }
                   16006:         }
                   16007:     }
                   16008:     return;
                   16009: }
                   16010: 
                   16011: =pod
                   16012: 
1.1162    raeburn  16013: =item * &recurse_categories()
1.655     raeburn  16014: 
                   16015: Recursively used to generate breadcrumb trails for course categories.
                   16016: 
                   16017: Inputs:
1.663     raeburn  16018: 
1.655     raeburn  16019: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16020:       categories and subcategories).
1.663     raeburn  16021: 
1.655     raeburn  16022: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16023: 
                   16024: category (current course category, for which breadcrumb trail is being generated).
                   16025: 
                   16026: trails (reference to array of breadcrumb trails for each category).
                   16027: 
1.655     raeburn  16028: allitems (reference to hash - key is category key
                   16029:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16030: 
1.655     raeburn  16031: parents (array containing containers directories for current category, 
                   16032:          back to top level). 
                   16033: 
                   16034: Returns: nothing
                   16035: 
                   16036: Side effects: populates trails and allitems hash references
                   16037: 
                   16038: =cut
                   16039: 
                   16040: sub recurse_categories {
1.1321    raeburn  16041:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16042:     my $shallower = $depth - 1;
                   16043:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16044:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16045:             my $name = $cats->[$depth]{$category}[$k];
                   16046:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16047:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16048:             if ($allitems->{$item} eq '') {
                   16049:                 push(@{$trails},$trailstr);
                   16050:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16051:             }
                   16052:             my $deeper = $depth+1;
                   16053:             push(@{$parents},$category);
1.665     raeburn  16054:             if (ref($subcats) eq 'HASH') {
                   16055:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16056:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16057:                     my $higher;
                   16058:                     if ($j > 0) {
                   16059:                         $higher = &escape($parents->[$j]).':'.
                   16060:                                   &escape($parents->[$j-1]).':'.$j;
                   16061:                     } else {
                   16062:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16063:                     }
                   16064:                     push(@{$subcats->{$higher}},$subcat);
                   16065:                 }
                   16066:             }
                   16067:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16068:                                 $subcats,$maxd);
1.655     raeburn  16069:             pop(@{$parents});
                   16070:         }
                   16071:     } else {
                   16072:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16073:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16074:         if ($allitems->{$item} eq '') {
                   16075:             push(@{$trails},$trailstr);
                   16076:             $allitems->{$item} = scalar(@{$trails})-1;
                   16077:         }
1.1321    raeburn  16078:         if (ref($maxd) eq 'HASH') {
                   16079:             if ($depth > $maxd->{$parents->[0]}) {
                   16080:                 $maxd->{$parents->[0]} = $depth;
                   16081:             }
                   16082:         }
1.655     raeburn  16083:     }
                   16084:     return;
                   16085: }
                   16086: 
1.663     raeburn  16087: =pod
                   16088: 
1.1162    raeburn  16089: =item * &assign_categories_table()
1.663     raeburn  16090: 
                   16091: Create a datatable for display of hierarchical categories in a domain,
                   16092: with checkboxes to allow a course to be categorized. 
                   16093: 
                   16094: Inputs:
                   16095: 
                   16096: cathash - reference to hash of categories defined for the domain (from
                   16097:           configuration.db)
                   16098: 
                   16099: currcat - scalar with an & separated list of categories assigned to a course. 
                   16100: 
1.919     raeburn  16101: type    - scalar contains course type (Course or Community).
                   16102: 
1.1260    raeburn  16103: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16104:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16105: 
1.663     raeburn  16106: Returns: $output (markup to be displayed) 
                   16107: 
                   16108: =cut
                   16109: 
                   16110: sub assign_categories_table {
1.1259    raeburn  16111:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16112:     my $output;
                   16113:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16114:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16115:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16116:         $maxdepth = scalar(@cats);
                   16117:         if (@cats > 0) {
                   16118:             my $itemcount = 0;
                   16119:             if (ref($cats[0]) eq 'ARRAY') {
                   16120:                 my @currcategories;
                   16121:                 if ($currcat ne '') {
                   16122:                     @currcategories = split('&',$currcat);
                   16123:                 }
1.919     raeburn  16124:                 my $table;
1.663     raeburn  16125:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16126:                     my $parent = $cats[0][$i];
1.919     raeburn  16127:                     next if ($parent eq 'instcode');
                   16128:                     if ($type eq 'Community') {
                   16129:                         next unless ($parent eq 'communities');
1.1239    raeburn  16130:                     } elsif ($type eq 'Placement') {
                   16131:                         next unless ($parent eq 'placement');
1.919     raeburn  16132:                     } else {
1.1239    raeburn  16133:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16134:                     }
1.663     raeburn  16135:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16136:                     my $item = &escape($parent).'::0';
                   16137:                     my $checked = '';
                   16138:                     if (@currcategories > 0) {
                   16139:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16140:                             $checked = ' checked="checked"';
1.663     raeburn  16141:                         }
                   16142:                     }
1.919     raeburn  16143:                     my $parent_title = $parent;
                   16144:                     if ($parent eq 'communities') {
                   16145:                         $parent_title = &mt('Communities');
1.1239    raeburn  16146:                     } elsif ($parent eq 'placement') {
                   16147:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16148:                     }
                   16149:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16150:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16151:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16152:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16153:                     my $depth = 1;
                   16154:                     push(@path,$parent);
1.1259    raeburn  16155:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16156:                     pop(@path);
1.919     raeburn  16157:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16158:                     $itemcount ++;
                   16159:                 }
1.919     raeburn  16160:                 if ($itemcount) {
                   16161:                     $output = &Apache::loncommon::start_data_table().
                   16162:                               $table.
                   16163:                               &Apache::loncommon::end_data_table();
                   16164:                 }
1.663     raeburn  16165:             }
                   16166:         }
                   16167:     }
                   16168:     return $output;
                   16169: }
                   16170: 
                   16171: =pod
                   16172: 
1.1162    raeburn  16173: =item * &assign_category_rows()
1.663     raeburn  16174: 
                   16175: Create a datatable row for display of nested categories in a domain,
                   16176: with checkboxes to allow a course to be categorized,called recursively.
                   16177: 
                   16178: Inputs:
                   16179: 
                   16180: itemcount - track row number for alternating colors
                   16181: 
                   16182: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16183:       categories and subcategories.
                   16184: 
                   16185: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16186: 
                   16187: parent - parent of current category item
                   16188: 
                   16189: path - Array containing all categories back up through the hierarchy from the
                   16190:        current category to the top level.
                   16191: 
                   16192: currcategories - reference to array of current categories assigned to the course
                   16193: 
1.1260    raeburn  16194: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16195:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16196: 
1.663     raeburn  16197: Returns: $output (markup to be displayed).
                   16198: 
                   16199: =cut
                   16200: 
                   16201: sub assign_category_rows {
1.1259    raeburn  16202:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16203:     my ($text,$name,$item,$chgstr);
                   16204:     if (ref($cats) eq 'ARRAY') {
                   16205:         my $maxdepth = scalar(@{$cats});
                   16206:         if (ref($cats->[$depth]) eq 'HASH') {
                   16207:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16208:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16209:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16210:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16211:                 for (my $j=0; $j<$numchildren; $j++) {
                   16212:                     $name = $cats->[$depth]{$parent}[$j];
                   16213:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16214:                     my $deeper = $depth+1;
                   16215:                     my $checked = '';
                   16216:                     if (ref($currcategories) eq 'ARRAY') {
                   16217:                         if (@{$currcategories} > 0) {
                   16218:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16219:                                 $checked = ' checked="checked"';
1.663     raeburn  16220:                             }
                   16221:                         }
                   16222:                     }
1.664     raeburn  16223:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16224:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16225:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16226:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16227:                              '</td><td>';
1.663     raeburn  16228:                     if (ref($path) eq 'ARRAY') {
                   16229:                         push(@{$path},$name);
1.1259    raeburn  16230:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16231:                         pop(@{$path});
                   16232:                     }
                   16233:                     $text .= '</td></tr>';
                   16234:                 }
                   16235:                 $text .= '</table></td>';
                   16236:             }
                   16237:         }
                   16238:     }
                   16239:     return $text;
                   16240: }
                   16241: 
1.1181    raeburn  16242: =pod
                   16243: 
                   16244: =back
                   16245: 
                   16246: =cut
                   16247: 
1.655     raeburn  16248: ############################################################
                   16249: ############################################################
                   16250: 
                   16251: 
1.443     albertel 16252: sub commit_customrole {
1.664     raeburn  16253:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  16254:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16255:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   16256:                          ($end?', ending '.localtime($end):'').': <b>'.
                   16257:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  16258:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 16259:                  '</b><br />';
                   16260:     return $output;
                   16261: }
                   16262: 
                   16263: sub commit_standardrole {
1.1116    raeburn  16264:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  16265:     my ($output,$logmsg,$linefeed);
                   16266:     if ($context eq 'auto') {
                   16267:         $linefeed = "\n";
                   16268:     } else {
                   16269:         $linefeed = "<br />\n";
                   16270:     }  
1.443     albertel 16271:     if ($three eq 'st') {
1.541     raeburn  16272:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  16273:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  16274:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16275:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16276:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16277:         } else {
1.541     raeburn  16278:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16279:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16280:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16281:             if ($context eq 'auto') {
                   16282:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16283:             } else {
                   16284:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16285:                &mt('Add to classlist').': <b>ok</b>';
                   16286:             }
                   16287:             $output .= $linefeed;
1.443     albertel 16288:         }
                   16289:     } else {
                   16290:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16291:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16292:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  16293:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  16294:         if ($context eq 'auto') {
                   16295:             $output .= $result.$linefeed;
                   16296:         } else {
                   16297:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16298:         }
1.443     albertel 16299:     }
                   16300:     return $output;
                   16301: }
                   16302: 
                   16303: sub commit_studentrole {
1.1116    raeburn  16304:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   16305:         $credits) = @_;
1.626     raeburn  16306:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16307:     if ($context eq 'auto') {
                   16308:         $linefeed = "\n";
                   16309:     } else {
                   16310:         $linefeed = '<br />'."\n";
                   16311:     }
1.443     albertel 16312:     if (defined($one) && defined($two)) {
                   16313:         my $cid=$one.'_'.$two;
                   16314:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16315:         my $secchange = 0;
                   16316:         my $expire_role_result;
                   16317:         my $modify_section_result;
1.628     raeburn  16318:         if ($oldsec ne '-1') { 
                   16319:             if ($oldsec ne $sec) {
1.443     albertel 16320:                 $secchange = 1;
1.628     raeburn  16321:                 my $now = time;
1.443     albertel 16322:                 my $uurl='/'.$cid;
                   16323:                 $uurl=~s/\_/\//g;
                   16324:                 if ($oldsec) {
                   16325:                     $uurl.='/'.$oldsec;
                   16326:                 }
1.626     raeburn  16327:                 $oldsecurl = $uurl;
1.628     raeburn  16328:                 $expire_role_result = 
1.652     raeburn  16329:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  16330:                 if ($env{'request.course.sec'} ne '') { 
                   16331:                     if ($expire_role_result eq 'refused') {
                   16332:                         my @roles = ('st');
                   16333:                         my @statuses = ('previous');
                   16334:                         my @roledoms = ($one);
                   16335:                         my $withsec = 1;
                   16336:                         my %roleshash = 
                   16337:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16338:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16339:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16340:                             my ($oldstart,$oldend) = 
                   16341:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16342:                             if ($oldend > 0 && $oldend <= $now) {
                   16343:                                 $expire_role_result = 'ok';
                   16344:                             }
                   16345:                         }
                   16346:                     }
                   16347:                 }
1.443     albertel 16348:                 $result = $expire_role_result;
                   16349:             }
                   16350:         }
                   16351:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16352:             $modify_section_result = 
                   16353:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16354:                                                            undef,undef,undef,$sec,
                   16355:                                                            $end,$start,'','',$cid,
                   16356:                                                            '',$context,$credits);
1.443     albertel 16357:             if ($modify_section_result =~ /^ok/) {
                   16358:                 if ($secchange == 1) {
1.628     raeburn  16359:                     if ($sec eq '') {
                   16360:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16361:                     } else {
                   16362:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16363:                     }
1.443     albertel 16364:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16365:                     if ($sec eq '') {
                   16366:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16367:                     } else {
                   16368:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16369:                     }
1.443     albertel 16370:                 } else {
1.628     raeburn  16371:                     if ($sec eq '') {
                   16372:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16373:                     } else {
                   16374:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16375:                     }
1.443     albertel 16376:                 }
                   16377:             } else {
1.1115    raeburn  16378:                 if ($secchange) { 
1.628     raeburn  16379:                     $$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;
                   16380:                 } else {
                   16381:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16382:                 }
1.443     albertel 16383:             }
                   16384:             $result = $modify_section_result;
                   16385:         } elsif ($secchange == 1) {
1.628     raeburn  16386:             if ($oldsec eq '') {
1.1103    raeburn  16387:                 $$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  16388:             } else {
                   16389:                 $$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;
                   16390:             }
1.626     raeburn  16391:             if ($expire_role_result eq 'refused') {
                   16392:                 my $newsecurl = '/'.$cid;
                   16393:                 $newsecurl =~ s/\_/\//g;
                   16394:                 if ($sec ne '') {
                   16395:                     $newsecurl.='/'.$sec;
                   16396:                 }
                   16397:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16398:                     if ($sec eq '') {
                   16399:                         $$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;
                   16400:                     } else {
                   16401:                         $$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;
                   16402:                     }
                   16403:                 }
                   16404:             }
1.443     albertel 16405:         }
                   16406:     } else {
1.626     raeburn  16407:         $$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 16408:         $result = "error: incomplete course id\n";
                   16409:     }
                   16410:     return $result;
                   16411: }
                   16412: 
1.1108    raeburn  16413: sub show_role_extent {
                   16414:     my ($scope,$context,$role) = @_;
                   16415:     $scope =~ s{^/}{};
                   16416:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16417:     push(@courseroles,'co');
                   16418:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16419:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16420:         $scope =~ s{/}{_};
                   16421:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16422:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16423:         my ($audom,$auname) = split(/\//,$scope);
                   16424:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16425:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16426:     } else {
                   16427:         $scope =~ s{/$}{};
                   16428:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16429:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16430:     }
                   16431: }
                   16432: 
1.443     albertel 16433: ############################################################
                   16434: ############################################################
                   16435: 
1.566     albertel 16436: sub check_clone {
1.578     raeburn  16437:     my ($args,$linefeed) = @_;
1.566     albertel 16438:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16439:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16440:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16441:     my $clonetitle;
                   16442:     my @clonemsg;
1.566     albertel 16443:     my $can_clone = 0;
1.944     raeburn  16444:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16445:     if ($lctype ne 'community') {
                   16446:         $lctype = 'course';
                   16447:     }
1.566     albertel 16448:     if ($clonehome eq 'no_host') {
1.944     raeburn  16449:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16450:             push(@clonemsg,({
                   16451:                               mt => 'No new community created.',
                   16452:                               args => [],
                   16453:                             },
                   16454:                             {
                   16455:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16456:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   16457:                             }));
1.908     raeburn  16458:         } else {
1.1344    raeburn  16459:             push(@clonemsg,({
                   16460:                               mt => 'No new course created.',
                   16461:                               args => [],
                   16462:                             },
                   16463:                             {
                   16464:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   16465:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16466:                             }));
                   16467:         }
1.566     albertel 16468:     } else {
                   16469: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  16470:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  16471:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  16472:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  16473:                 push(@clonemsg,({
                   16474:                                   mt => 'No new community created.',
                   16475:                                   args => [],
                   16476:                                 },
                   16477:                                 {
                   16478:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   16479:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   16480:                                 }));
                   16481:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  16482:             }
                   16483:         }
1.1262    raeburn  16484: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  16485:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 16486: 	    $can_clone = 1;
                   16487: 	} else {
1.1221    raeburn  16488: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 16489: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  16490:             if ($clonehash{'cloners'} eq '') {
                   16491:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   16492:                 if ($domdefs{'canclone'}) {
                   16493:                     unless ($domdefs{'canclone'} eq 'none') {
                   16494:                         if ($domdefs{'canclone'} eq 'domain') {
                   16495:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   16496:                                 $can_clone = 1;
                   16497:                             }
                   16498:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16499:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   16500:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   16501:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   16502:                                 $can_clone = 1;
                   16503:                             }
                   16504:                         }
                   16505:                     }
                   16506:                 }
1.578     raeburn  16507:             } else {
1.1221    raeburn  16508: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   16509:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  16510:                     $can_clone = 1;
1.1221    raeburn  16511:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  16512:                     $can_clone = 1;
1.1225    raeburn  16513:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   16514:                     $can_clone = 1;
1.1221    raeburn  16515:                 }
                   16516:                 unless ($can_clone) {
1.1225    raeburn  16517:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   16518:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  16519:                         my (%gotdomdefaults,%gotcodedefaults);
                   16520:                         foreach my $cloner (@cloners) {
                   16521:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   16522:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   16523:                                 my (%codedefaults,@code_order);
                   16524:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   16525:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   16526:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   16527:                                     }
                   16528:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   16529:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   16530:                                     }
                   16531:                                 } else {
                   16532:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   16533:                                                                             \%codedefaults,
                   16534:                                                                             \@code_order);
                   16535:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   16536:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   16537:                                 }
                   16538:                                 if (@code_order > 0) {
                   16539:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   16540:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   16541:                                                                                 $args->{'crscode'})) {
                   16542:                                         $can_clone = 1;
                   16543:                                         last;
                   16544:                                     }
                   16545:                                 }
                   16546:                             }
                   16547:                         }
                   16548:                     }
1.1225    raeburn  16549:                 }
                   16550:             }
                   16551:             unless ($can_clone) {
                   16552:                 my $ccrole = 'cc';
                   16553:                 if ($args->{'crstype'} eq 'Community') {
                   16554:                     $ccrole = 'co';
                   16555:                 }
                   16556: 	        my %roleshash =
                   16557: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   16558: 					          $args->{'ccdomain'},
                   16559:                                                   'userroles',['active'],[$ccrole],
                   16560: 					          [$args->{'clonedomain'}]);
                   16561: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   16562:                     $can_clone = 1;
                   16563:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   16564:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   16565:                     $can_clone = 1;
1.1221    raeburn  16566:                 }
                   16567:             }
                   16568:             unless ($can_clone) {
                   16569:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16570:                     push(@clonemsg,({
                   16571:                                       mt => 'No new community created.',
                   16572:                                       args => [],
                   16573:                                     },
                   16574:                                     {
                   16575:                                       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]).',
                   16576:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16577:                                     }));
1.942     raeburn  16578:                 } else {
1.1344    raeburn  16579:                     push(@clonemsg,({
                   16580:                                       mt => 'No new course created.',
                   16581:                                       args => [],
                   16582:                                     },
                   16583:                                     {
                   16584:                                       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]).',
                   16585:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16586:                                     }));
1.1221    raeburn  16587:                 }
1.566     albertel 16588: 	    }
1.578     raeburn  16589:         }
1.566     albertel 16590:     }
1.1344    raeburn  16591:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16592: }
                   16593: 
1.444     albertel 16594: sub construct_course {
1.1262    raeburn  16595:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  16596:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16597:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16598:     my $linefeed =  '<br />'."\n";
                   16599:     if ($context eq 'auto') {
                   16600:         $linefeed = "\n";
                   16601:     }
1.566     albertel 16602: 
                   16603: #
                   16604: # Are we cloning?
                   16605: #
1.1344    raeburn  16606:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16607:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  16608: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16609:         if (!$can_clone) {
1.1344    raeburn  16610: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16611: 	}
                   16612:     }
                   16613: 
1.444     albertel 16614: #
                   16615: # Open course
                   16616: #
1.1239    raeburn  16617:     my $showncrstype;
                   16618:     if ($args->{'crstype'} eq 'Placement') {
                   16619:         $showncrstype = 'placement test'; 
                   16620:     } else {  
                   16621:         $showncrstype = lc($args->{'crstype'});
                   16622:     }
1.444     albertel 16623:     my %cenv=();
                   16624:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16625:                                              $args->{'cdescr'},
                   16626:                                              $args->{'curl'},
                   16627:                                              $args->{'course_home'},
                   16628:                                              $args->{'nonstandard'},
                   16629:                                              $args->{'crscode'},
                   16630:                                              $args->{'ccuname'}.':'.
                   16631:                                              $args->{'ccdomain'},
1.882     raeburn  16632:                                              $args->{'crstype'},
1.1344    raeburn  16633:                                              $cnum,$context,$category,
                   16634:                                              $callercontext);
1.444     albertel 16635: 
                   16636:     # Note: The testing routines depend on this being output; see 
                   16637:     # Utils::Course. This needs to at least be output as a comment
                   16638:     # if anyone ever decides to not show this, and Utils::Course::new
                   16639:     # will need to be suitably modified.
1.1344    raeburn  16640:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16641:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16642:     } else {
                   16643:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   16644:     }
1.943     raeburn  16645:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  16646:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16647:     }
                   16648: 
1.444     albertel 16649: #
                   16650: # Check if created correctly
                   16651: #
1.479     albertel 16652:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16653:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16654:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  16655:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16656:             $outcome .= &mt_user($user_lh,
                   16657:                             'Course creation failed, unrecognized course home server.');
                   16658:         } else {
                   16659:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16660:         }
                   16661:         $outcome .= $linefeed;
                   16662:         return (0,$outcome,$clonemsgref);
1.943     raeburn  16663:     }
1.541     raeburn  16664:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16665: 
1.444     albertel 16666: #
1.566     albertel 16667: # Do the cloning
                   16668: #   
1.1344    raeburn  16669:     my @clonemsg;
1.566     albertel 16670:     if ($can_clone && $cloneid) {
1.1344    raeburn  16671:         push(@clonemsg,
                   16672:                       {
                   16673:                           mt => 'Created [_1] by cloning from [_2]',
                   16674:                           args => [$showncrstype,$clonetitle],
                   16675:                       });
1.566     albertel 16676: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16677: # Copy all files
1.1344    raeburn  16678:         my @info =
                   16679: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16680: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   16681:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16682:                                                      $args->{'tinyurls'});
                   16683:         if (@info) {
                   16684:             push(@clonemsg,@info);
                   16685:         }
1.444     albertel 16686: # Restore URL
1.566     albertel 16687: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16688: # Restore title
1.566     albertel 16689: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16690: # Restore creation date, creator and creation context.
                   16691:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16692:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16693:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16694: # Mark as cloned
1.566     albertel 16695: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16696: # Need to clone grading mode
                   16697:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16698:         $cenv{'grading'}=$newenv{'grading'};
                   16699: # Do not clone these environment entries
                   16700:         &Apache::lonnet::del('environment',
                   16701:                   ['default_enrollment_start_date',
                   16702:                    'default_enrollment_end_date',
                   16703:                    'question.email',
                   16704:                    'policy.email',
                   16705:                    'comment.email',
                   16706:                    'pch.users.denied',
1.725     raeburn  16707:                    'plc.users.denied',
                   16708:                    'hidefromcat',
1.1121    raeburn  16709:                    'checkforpriv',
1.1355    raeburn  16710:                    'categories'],
1.638     www      16711:                    $$crsudom,$$crsunum);
1.1170    raeburn  16712:         if ($args->{'textbook'}) {
                   16713:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16714:         }
1.444     albertel 16715:     }
1.566     albertel 16716: 
1.444     albertel 16717: #
                   16718: # Set environment (will override cloned, if existing)
                   16719: #
                   16720:     my @sections = ();
                   16721:     my @xlists = ();
                   16722:     if ($args->{'crstype'}) {
                   16723:         $cenv{'type'}=$args->{'crstype'};
                   16724:     }
1.1371    raeburn  16725:     if ($args->{'lti'}) {
                   16726:         $cenv{'internal.lti'}=$args->{'lti'};
                   16727:     }
1.444     albertel 16728:     if ($args->{'crsid'}) {
                   16729:         $cenv{'courseid'}=$args->{'crsid'};
                   16730:     }
                   16731:     if ($args->{'crscode'}) {
                   16732:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16733:     }
                   16734:     if ($args->{'crsquota'} ne '') {
                   16735:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16736:     } else {
                   16737:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16738:     }
                   16739:     if ($args->{'ccuname'}) {
                   16740:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16741:                                         ':'.$args->{'ccdomain'};
                   16742:     } else {
                   16743:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16744:     }
1.1116    raeburn  16745:     if ($args->{'defaultcredits'}) {
                   16746:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16747:     }
1.444     albertel 16748:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16749:     if ($args->{'crssections'}) {
                   16750:         $cenv{'internal.sectionnums'} = '';
                   16751:         if ($args->{'crssections'} =~ m/,/) {
                   16752:             @sections = split/,/,$args->{'crssections'};
                   16753:         } else {
                   16754:             $sections[0] = $args->{'crssections'};
                   16755:         }
                   16756:         if (@sections > 0) {
                   16757:             foreach my $item (@sections) {
                   16758:                 my ($sec,$gp) = split/:/,$item;
                   16759:                 my $class = $args->{'crscode'}.$sec;
                   16760:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16761:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16762:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16763:                     push(@badclasses,$class);
1.444     albertel 16764:                 }
                   16765:             }
                   16766:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16767:         }
                   16768:     }
                   16769: # do not hide course coordinator from staff listing, 
                   16770: # even if privileged
                   16771:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  16772: # add course coordinator's domain to domains to check for privileged users
                   16773: # if different to course domain
                   16774:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16775:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16776:     }
1.444     albertel 16777: # add crosslistings
                   16778:     if ($args->{'crsxlist'}) {
                   16779:         $cenv{'internal.crosslistings'}='';
                   16780:         if ($args->{'crsxlist'} =~ m/,/) {
                   16781:             @xlists = split/,/,$args->{'crsxlist'};
                   16782:         } else {
                   16783:             $xlists[0] = $args->{'crsxlist'};
                   16784:         }
                   16785:         if (@xlists > 0) {
                   16786:             foreach my $item (@xlists) {
                   16787:                 my ($xl,$gp) = split/:/,$item;
                   16788:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16789:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16790:                 unless ($addcheck eq 'ok') {
1.1263    raeburn  16791:                     push(@badclasses,$xl);
1.444     albertel 16792:                 }
                   16793:             }
                   16794:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16795:         }
                   16796:     }
                   16797:     if ($args->{'autoadds'}) {
                   16798:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16799:     }
                   16800:     if ($args->{'autodrops'}) {
                   16801:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16802:     }
                   16803: # check for notification of enrollment changes
                   16804:     my @notified = ();
                   16805:     if ($args->{'notify_owner'}) {
                   16806:         if ($args->{'ccuname'} ne '') {
                   16807:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16808:         }
                   16809:     }
                   16810:     if ($args->{'notify_dc'}) {
                   16811:         if ($uname ne '') { 
1.630     raeburn  16812:             push(@notified,$uname.':'.$udom);
1.444     albertel 16813:         }
                   16814:     }
                   16815:     if (@notified > 0) {
                   16816:         my $notifylist;
                   16817:         if (@notified > 1) {
                   16818:             $notifylist = join(',',@notified);
                   16819:         } else {
                   16820:             $notifylist = $notified[0];
                   16821:         }
                   16822:         $cenv{'internal.notifylist'} = $notifylist;
                   16823:     }
                   16824:     if (@badclasses > 0) {
                   16825:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  16826:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16827:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16828:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16829:         );
1.1264    raeburn  16830:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16831:                            &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  16832:         if ($context eq 'auto') {
                   16833:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  16834:         } else {
1.566     albertel 16835:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  16836:         }
                   16837:         foreach my $item (@badclasses) {
1.541     raeburn  16838:             if ($context eq 'auto') {
1.1261    raeburn  16839:                 $outcome .= " - $item\n";
1.541     raeburn  16840:             } else {
1.1261    raeburn  16841:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16842:             }
1.1261    raeburn  16843:         }
                   16844:         if ($context eq 'auto') {
                   16845:             $outcome .= $linefeed;
                   16846:         } else {
                   16847:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  16848:         } 
1.444     albertel 16849:     }
                   16850:     if ($args->{'no_end_date'}) {
                   16851:         $args->{'endaccess'} = 0;
                   16852:     }
                   16853:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16854:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16855:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16856:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16857:     if ($args->{'showphotos'}) {
                   16858:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16859:     }
                   16860:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16861:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16862:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16863:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16864:             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'); 
                   16865:             if ($context eq 'auto') {
                   16866:                 $outcome .= $krb_msg;
                   16867:             } else {
1.566     albertel 16868:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16869:             }
                   16870:             $outcome .= $linefeed;
1.444     albertel 16871:         }
                   16872:     }
                   16873:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16874:        if ($args->{'setpolicy'}) {
                   16875:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16876:        }
                   16877:        if ($args->{'setcontent'}) {
                   16878:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16879:        }
1.1251    raeburn  16880:        if ($args->{'setcomment'}) {
                   16881:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16882:        }
1.444     albertel 16883:     }
                   16884:     if ($args->{'reshome'}) {
                   16885: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16886: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16887:     }
                   16888: #
                   16889: # course has keyed access
                   16890: #
                   16891:     if ($args->{'setkeys'}) {
                   16892:        $cenv{'keyaccess'}='yes';
                   16893:     }
                   16894: # if specified, key authority is not course, but user
                   16895: # only active if keyaccess is yes
                   16896:     if ($args->{'keyauth'}) {
1.487     albertel 16897: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16898: 	$user = &LONCAPA::clean_username($user);
                   16899: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16900: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16901: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16902: 	}
                   16903:     }
                   16904: 
1.1166    raeburn  16905: #
1.1167    raeburn  16906: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  16907: #
                   16908:     if ($args->{'uniquecode'}) {
                   16909:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16910:         if ($code) {
                   16911:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  16912:             my %crsinfo =
                   16913:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16914:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16915:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16916:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16917:             } 
1.1166    raeburn  16918:             if (ref($coderef)) {
                   16919:                 $$coderef = $code;
                   16920:             }
                   16921:         }
                   16922:     }
                   16923: 
1.444     albertel 16924:     if ($args->{'disresdis'}) {
                   16925:         $cenv{'pch.roles.denied'}='st';
                   16926:     }
                   16927:     if ($args->{'disablechat'}) {
                   16928:         $cenv{'plc.roles.denied'}='st';
                   16929:     }
                   16930: 
                   16931:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16932:     # course
                   16933:     $cenv{'course.helper.not.run'} = 1;
                   16934:     #
                   16935:     # Use new Randomseed
                   16936:     #
                   16937:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16938:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16939:     #
                   16940:     # The encryption code and receipt prefix for this course
                   16941:     #
                   16942:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16943:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16944:     #
                   16945:     # By default, use standard grading
                   16946:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16947: 
1.541     raeburn  16948:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16949:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16950: #
                   16951: # Open all assignments
                   16952: #
                   16953:     if ($args->{'openall'}) {
1.1341    raeburn  16954:        my $opendate = time;
                   16955:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16956:            $opendate = $args->{'openallfrom'};
                   16957:        }
1.444     albertel 16958:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  16959:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16960:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  16961:        $outcome .= &mt('All assignments open starting [_1]',
                   16962:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16963:                    &Apache::lonnet::cput
                   16964:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16965:    }
                   16966: #
                   16967: # Set first page
                   16968: #
                   16969:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16970: 	    || ($cloneid)) {
1.445     albertel 16971: 	use LONCAPA::map;
1.444     albertel 16972: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16973: 
                   16974: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16975:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16976: 
1.444     albertel 16977:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16978:         my $title; my $url;
                   16979:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16980: 	    $title=&mt('Syllabus');
1.444     albertel 16981:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16982:         } else {
1.963     raeburn  16983:             $title=&mt('Table of Contents');
1.444     albertel 16984:             $url='/adm/navmaps';
                   16985:         }
1.445     albertel 16986: 
                   16987:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16988: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16989: 
                   16990: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16991:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16992:     }
1.566     albertel 16993: 
1.1237    raeburn  16994: # 
                   16995: # Set params for Placement Tests
                   16996: #
1.1239    raeburn  16997:     if ($args->{'crstype'} eq 'Placement') {
                   16998:        my %storecontent; 
                   16999:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17000:        my %defaults = (
                   17001:                         buttonshide   => { value => 'yes',
                   17002:                                            type => 'string_yesno',},
                   17003:                         type          => { value => 'randomizetry',
                   17004:                                            type  => 'string_questiontype',},
                   17005:                         maxtries      => { value => 1,
                   17006:                                            type => 'int_pos',},
                   17007:                         problemstatus => { value => 'no',
                   17008:                                            type  => 'string_problemstatus',},
                   17009:                       );
                   17010:        foreach my $key (keys(%defaults)) {
                   17011:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17012:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17013:        }
1.1237    raeburn  17014:        &Apache::lonnet::cput
                   17015:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17016:     }
                   17017: 
1.1344    raeburn  17018:     return (1,$outcome,\@clonemsg);
1.444     albertel 17019: }
                   17020: 
1.1166    raeburn  17021: sub make_unique_code {
                   17022:     my ($cdom,$cnum) = @_;
                   17023:     # get lock on uniquecodes db
                   17024:     my $lockhash = {
                   17025:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17026:                                                   ':'.$env{'user.domain'},
                   17027:                    };
                   17028:     my $tries = 0;
                   17029:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17030:     my ($code,$error);
                   17031:   
                   17032:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17033:         $tries ++;
                   17034:         sleep 1;
                   17035:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17036:     }
                   17037:     if ($gotlock eq 'ok') {
                   17038:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17039:         my $gotcode;
                   17040:         my $attempts = 0;
                   17041:         while ((!$gotcode) && ($attempts < 100)) {
                   17042:             $code = &generate_code();
                   17043:             if (!exists($currcodes{$code})) {
                   17044:                 $gotcode = 1;
                   17045:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17046:                     $error = 'nostore';
                   17047:                 }
                   17048:             }
                   17049:             $attempts ++;
                   17050:         }
                   17051:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17052:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17053:     } else {
                   17054:         $error = 'nolock';
                   17055:     }
                   17056:     return ($code,$error);
                   17057: }
                   17058: 
                   17059: sub generate_code {
                   17060:     my $code;
                   17061:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17062:     for (my $i=0; $i<6; $i++) {
                   17063:         my $lettnum = int (rand 2);
                   17064:         my $item = '';
                   17065:         if ($lettnum) {
                   17066:             $item = $letts[int( rand(18) )];
                   17067:         } else {
                   17068:             $item = 1+int( rand(8) );
                   17069:         }
                   17070:         $code .= $item;
                   17071:     }
                   17072:     return $code;
                   17073: }
                   17074: 
1.444     albertel 17075: ############################################################
                   17076: ############################################################
                   17077: 
1.1237    raeburn  17078: # Community, Course and Placement Test
1.378     raeburn  17079: sub course_type {
                   17080:     my ($cid) = @_;
                   17081:     if (!defined($cid)) {
                   17082:         $cid = $env{'request.course.id'};
                   17083:     }
1.404     albertel 17084:     if (defined($env{'course.'.$cid.'.type'})) {
                   17085:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17086:     } else {
                   17087:         return 'Course';
1.377     raeburn  17088:     }
                   17089: }
1.156     albertel 17090: 
1.406     raeburn  17091: sub group_term {
                   17092:     my $crstype = &course_type();
                   17093:     my %names = (
                   17094:                   'Course' => 'group',
1.865     raeburn  17095:                   'Community' => 'group',
1.1237    raeburn  17096:                   'Placement' => 'group',
1.406     raeburn  17097:                 );
                   17098:     return $names{$crstype};
                   17099: }
                   17100: 
1.902     raeburn  17101: sub course_types {
1.1310    raeburn  17102:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17103:     my %typename = (
                   17104:                          official   => 'Official course',
                   17105:                          unofficial => 'Unofficial course',
                   17106:                          community  => 'Community',
1.1165    raeburn  17107:                          textbook   => 'Textbook course',
1.1237    raeburn  17108:                          placement  => 'Placement test',
1.1310    raeburn  17109:                          lti        => 'LTI provider',
1.902     raeburn  17110:                    );
                   17111:     return (\@types,\%typename);
                   17112: }
                   17113: 
1.156     albertel 17114: sub icon {
                   17115:     my ($file)=@_;
1.505     albertel 17116:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17117:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17118:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17119:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17120: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17121: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17122: 	            $curfext.".gif") {
                   17123: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17124: 		$curfext.".gif";
                   17125: 	}
                   17126:     }
1.249     albertel 17127:     return &lonhttpdurl($iconname);
1.154     albertel 17128: } 
1.84      albertel 17129: 
1.575     albertel 17130: sub lonhttpdurl {
1.692     www      17131: #
                   17132: # Had been used for "small fry" static images on separate port 8080.
                   17133: # Modify here if lightweight http functionality desired again.
                   17134: # Currently eliminated due to increasing firewall issues.
                   17135: #
1.575     albertel 17136:     my ($url)=@_;
1.692     www      17137:     return $url;
1.215     albertel 17138: }
                   17139: 
1.213     albertel 17140: sub connection_aborted {
                   17141:     my ($r)=@_;
                   17142:     $r->print(" ");$r->rflush();
                   17143:     my $c = $r->connection;
                   17144:     return $c->aborted();
                   17145: }
                   17146: 
1.221     foxr     17147: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17148: #    strings as 'strings'.
                   17149: sub escape_single {
1.221     foxr     17150:     my ($input) = @_;
1.223     albertel 17151:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17152:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17153:     return $input;
                   17154: }
1.223     albertel 17155: 
1.222     foxr     17156: #  Same as escape_single, but escape's "'s  This 
                   17157: #  can be used for  "strings"
                   17158: sub escape_double {
                   17159:     my ($input) = @_;
                   17160:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17161:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17162:     return $input;
                   17163: }
1.223     albertel 17164:  
1.222     foxr     17165: #   Escapes the last element of a full URL.
                   17166: sub escape_url {
                   17167:     my ($url)   = @_;
1.238     raeburn  17168:     my @urlslices = split(/\//, $url,-1);
1.369     www      17169:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17170:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17171: }
1.462     albertel 17172: 
1.820     raeburn  17173: sub compare_arrays {
                   17174:     my ($arrayref1,$arrayref2) = @_;
                   17175:     my (@difference,%count);
                   17176:     @difference = ();
                   17177:     %count = ();
                   17178:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17179:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17180:         foreach my $element (keys(%count)) {
                   17181:             if ($count{$element} == 1) {
                   17182:                 push(@difference,$element);
                   17183:             }
                   17184:         }
                   17185:     }
                   17186:     return @difference;
                   17187: }
                   17188: 
1.1322    raeburn  17189: sub lon_status_items {
                   17190:     my %defaults = (
                   17191:                      E         => 100,
                   17192:                      W         => 4,
                   17193:                      N         => 1,
1.1324    raeburn  17194:                      U         => 5,
1.1322    raeburn  17195:                      threshold => 200,
                   17196:                      sysmail   => 2500,
                   17197:                    );
                   17198:     my %names = (
                   17199:                    E => 'Errors',
                   17200:                    W => 'Warnings',
                   17201:                    N => 'Notices',
1.1324    raeburn  17202:                    U => 'Unsent',
1.1322    raeburn  17203:                 );
                   17204:     return (\%defaults,\%names);
                   17205: }
                   17206: 
1.817     bisitz   17207: # -------------------------------------------------------- Initialize user login
1.462     albertel 17208: sub init_user_environment {
1.463     albertel 17209:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17210:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17211: 
                   17212:     my $public=($username eq 'public' && $domain eq 'public');
                   17213: 
1.1062    raeburn  17214:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 17215:     my $now=time;
                   17216: 
                   17217:     if ($public) {
                   17218: 	my $max_public=100;
                   17219: 	my $oldest;
                   17220: 	my $oldest_time=0;
                   17221: 	for(my $next=1;$next<=$max_public;$next++) {
                   17222: 	    if (-e $lonids."/publicuser_$next.id") {
                   17223: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17224: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17225: 		    $oldest_time=$mtime;
                   17226: 		    $oldest=$next;
                   17227: 		}
                   17228: 	    } else {
                   17229: 		$cookie="publicuser_$next";
                   17230: 		last;
                   17231: 	    }
                   17232: 	}
                   17233: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17234:     } else {
1.1275    raeburn  17235: 	# See if old ID present, if so, remove if this isn't a robot,
                   17236: 	# killing any existing non-robot sessions
1.463     albertel 17237: 	if (!$args->{'robot'}) {
                   17238: 	    opendir(DIR,$lonids);
                   17239: 	    while ($filename=readdir(DIR)) {
                   17240: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17241:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17242:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17243:                         my $linkedfile;
1.1320    raeburn  17244:                         if (exists($oldenv{'user.linkedenv'})) {
                   17245:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17246:                         }
1.1320    raeburn  17247:                         untie(%oldenv);
                   17248:                         if (unlink("$lonids/$filename")) {
                   17249:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17250:                                 if (-l "$lonids/$linkedfile.id") {
                   17251:                                     unlink("$lonids/$linkedfile.id");
                   17252:                                 }
1.1295    raeburn  17253:                             }
                   17254:                         }
                   17255:                     } else {
                   17256:                         unlink($lonids.'/'.$filename);
                   17257:                     }
1.463     albertel 17258: 		}
1.462     albertel 17259: 	    }
1.463     albertel 17260: 	    closedir(DIR);
1.1204    raeburn  17261: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17262:             my $namespace = 'nohist_courseeditor';
                   17263:             my $lockingkey = 'paste'."\0".'locked_num';
                   17264:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17265:                                                 $domain,$username);
                   17266:             if (exists($lockhash{$lockingkey})) {
                   17267:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17268:                 unless ($delresult eq 'ok') {
                   17269:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17270:                 }
                   17271:             }
1.462     albertel 17272: 	}
                   17273: # Give them a new cookie
1.463     albertel 17274: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17275: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17276: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17277:     
                   17278: # Initialize roles
                   17279: 
1.1062    raeburn  17280: 	($userroles,$firstaccenv,$timerintenv) = 
                   17281:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17282:     }
                   17283: # ------------------------------------ Check browser type and MathML capability
                   17284: 
1.1194    raeburn  17285:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17286:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17287: 
                   17288: # ------------------------------------------------------------- Get environment
                   17289: 
                   17290:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17291:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17292:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17293: 	undef(%userenv);
                   17294:     }
                   17295:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17296: 	$form->{'interface'}=$userenv{'interface'};
                   17297:     }
                   17298:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17299: 
                   17300: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17301:     foreach my $option ('interface','localpath','localres') {
                   17302:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17303:     }
                   17304: # --------------------------------------------------------- Write first profile
                   17305: 
                   17306:     {
1.1350    raeburn  17307:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17308: 	my %initial_env = 
                   17309: 	    ("user.name"          => $username,
                   17310: 	     "user.domain"        => $domain,
                   17311: 	     "user.home"          => $authhost,
                   17312: 	     "browser.type"       => $clientbrowser,
                   17313: 	     "browser.version"    => $clientversion,
                   17314: 	     "browser.mathml"     => $clientmathml,
                   17315: 	     "browser.unicode"    => $clientunicode,
                   17316: 	     "browser.os"         => $clientos,
1.1137    raeburn  17317:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17318:              "browser.info"       => $clientinfo,
1.1194    raeburn  17319:              "browser.osversion"  => $clientosversion,
1.462     albertel 17320: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17321: 	     "request.course.fn"  => '',
                   17322: 	     "request.course.uri" => '',
                   17323: 	     "request.course.sec" => '',
                   17324: 	     "request.role"       => 'cm',
                   17325: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17326: 	     "request.host"       => $ip,);
1.462     albertel 17327: 
                   17328:         if ($form->{'localpath'}) {
                   17329: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17330: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17331:         }
                   17332: 	
                   17333: 	if ($form->{'interface'}) {
                   17334: 	    $form->{'interface'}=~s/\W//gs;
                   17335: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17336: 	    $env{'browser.interface'}=$form->{'interface'};
                   17337: 	}
                   17338: 
1.1157    raeburn  17339:         if ($form->{'iptoken'}) {
                   17340:             my $lonhost = $r->dir_config('lonHostID');
                   17341:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17342:             $env{'user.noloadbalance'} = $lonhost;
                   17343:         }
                   17344: 
1.1268    raeburn  17345:         if ($form->{'noloadbalance'}) {
                   17346:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17347:             my $hosthere = $form->{'noloadbalance'};
                   17348:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17349:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17350:                 $env{'user.noloadbalance'} = $hosthere;
                   17351:             }
                   17352:         }
                   17353: 
1.1016    raeburn  17354:         unless ($domain eq 'public') {
1.1273    raeburn  17355:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17356:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17357: 
                   17358:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   17359:                 $userenv{'availabletools.'.$tool} = 
                   17360:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17361:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17362:             }
1.980     raeburn  17363: 
1.1311    raeburn  17364:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17365:                 $userenv{'canrequest.'.$crstype} =
                   17366:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17367:                                                       'reload','requestcourses',
                   17368:                                                       \%userenv,\%domdef,\%is_adv);
                   17369:             }
1.724     raeburn  17370: 
1.1273    raeburn  17371:             $userenv{'canrequest.author'} =
                   17372:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17373:                                                   'reload','requestauthor',
1.980     raeburn  17374:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17375:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17376:                                                  $domain,$username);
                   17377:             my $reqstatus = $reqauthor{'author_status'};
                   17378:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17379:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17380:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17381:                                                       $reqauthor{'author'}{'timestamp'};
                   17382:                 }
1.1092    raeburn  17383:             }
1.1287    raeburn  17384:             my ($types,$typename) = &course_types();
                   17385:             if (ref($types) eq 'ARRAY') {
                   17386:                 my @options = ('approval','validate','autolimit');
                   17387:                 my $optregex = join('|',@options);
                   17388:                 my (%willtrust,%trustchecked);
                   17389:                 foreach my $type (@{$types}) {
                   17390:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17391:                     if ($dom_str ne '') {
                   17392:                         my $updatedstr = '';
                   17393:                         my @possdomains = split(',',$dom_str);
                   17394:                         foreach my $entry (@possdomains) {
                   17395:                             my ($extdom,$extopt) = split(':',$entry);
                   17396:                             unless ($trustchecked{$extdom}) {
                   17397:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17398:                                 $trustchecked{$extdom} = 1;
                   17399:                             }
                   17400:                             if ($willtrust{$extdom}) {
                   17401:                                 $updatedstr .= $entry.',';
                   17402:                             }
                   17403:                         }
                   17404:                         $updatedstr =~ s/,$//;
                   17405:                         if ($updatedstr) {
                   17406:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   17407:                         } else {
                   17408:                             delete($userenv{'reqcrsotherdom.'.$type});
                   17409:                         }
                   17410:                     }
                   17411:                 }
                   17412:             }
1.1092    raeburn  17413:         }
1.462     albertel 17414: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  17415: 
1.462     albertel 17416: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   17417: 		 &GDBM_WRCREAT(),0640)) {
                   17418: 	    &_add_to_env(\%disk_env,\%initial_env);
                   17419: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   17420: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  17421:             if (ref($firstaccenv) eq 'HASH') {
                   17422:                 &_add_to_env(\%disk_env,$firstaccenv);
                   17423:             }
                   17424:             if (ref($timerintenv) eq 'HASH') {
                   17425:                 &_add_to_env(\%disk_env,$timerintenv);
                   17426:             }
1.463     albertel 17427: 	    if (ref($args->{'extra_env'})) {
                   17428: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   17429: 	    }
1.462     albertel 17430: 	    untie(%disk_env);
                   17431: 	} else {
1.705     tempelho 17432: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   17433: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 17434: 	    return 'error: '.$!;
                   17435: 	}
                   17436:     }
                   17437:     $env{'request.role'}='cm';
                   17438:     $env{'request.role.adv'}=$env{'user.adv'};
                   17439:     $env{'browser.type'}=$clientbrowser;
                   17440: 
                   17441:     return $cookie;
                   17442: 
                   17443: }
                   17444: 
                   17445: sub _add_to_env {
                   17446:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  17447:     if (ref($env_data) eq 'HASH') {
                   17448:         while (my ($key,$value) = each(%$env_data)) {
                   17449: 	    $idf->{$prefix.$key} = $value;
                   17450: 	    $env{$prefix.$key}   = $value;
                   17451:         }
1.462     albertel 17452:     }
                   17453: }
                   17454: 
1.685     tempelho 17455: # --- Get the symbolic name of a problem and the url
                   17456: sub get_symb {
                   17457:     my ($request,$silent) = @_;
1.726     raeburn  17458:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 17459:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   17460:     if ($symb eq '') {
                   17461:         if (!$silent) {
1.1071    raeburn  17462:             if (ref($request)) { 
                   17463:                 $request->print("Unable to handle ambiguous references:$url:.");
                   17464:             }
1.685     tempelho 17465:             return ();
                   17466:         }
                   17467:     }
                   17468:     &Apache::lonenc::check_decrypt(\$symb);
                   17469:     return ($symb);
                   17470: }
                   17471: 
                   17472: # --------------------------------------------------------------Get annotation
                   17473: 
                   17474: sub get_annotation {
                   17475:     my ($symb,$enc) = @_;
                   17476: 
                   17477:     my $key = $symb;
                   17478:     if (!$enc) {
                   17479:         $key =
                   17480:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   17481:     }
                   17482:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   17483:     return $annotation{$key};
                   17484: }
                   17485: 
                   17486: sub clean_symb {
1.731     raeburn  17487:     my ($symb,$delete_enc) = @_;
1.685     tempelho 17488: 
                   17489:     &Apache::lonenc::check_decrypt(\$symb);
                   17490:     my $enc = $env{'request.enc'};
1.731     raeburn  17491:     if ($delete_enc) {
1.730     raeburn  17492:         delete($env{'request.enc'});
                   17493:     }
1.685     tempelho 17494: 
                   17495:     return ($symb,$enc);
                   17496: }
1.462     albertel 17497: 
1.1181    raeburn  17498: ############################################################
                   17499: ############################################################
                   17500: 
                   17501: =pod
                   17502: 
                   17503: =head1 Routines for building display used to search for courses
                   17504: 
                   17505: 
                   17506: =over 4
                   17507: 
                   17508: =item * &build_filters()
                   17509: 
                   17510: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  17511: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   17512: and quotacheck.pl
                   17513: 
1.1181    raeburn  17514: 
                   17515: Inputs:
                   17516: 
                   17517: filterlist - anonymous array of fields to include as potential filters 
                   17518: 
                   17519: crstype - course type
                   17520: 
                   17521: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   17522:               to pop-open a course selector (will contain "extra element"). 
                   17523: 
                   17524: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   17525: 
                   17526: filter - anonymous hash of criteria and their values
                   17527: 
                   17528: action - form action
                   17529: 
                   17530: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   17531: 
1.1182    raeburn  17532: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  17533: 
                   17534: cloneruname - username of owner of new course who wants to clone
                   17535: 
                   17536: clonerudom - domain of owner of new course who wants to clone
                   17537: 
                   17538: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   17539: 
                   17540: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   17541: 
                   17542: codedom - domain
                   17543: 
                   17544: formname - value of form element named "form". 
                   17545: 
                   17546: fixeddom - domain, if fixed.
                   17547: 
                   17548: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   17549: 
                   17550: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   17551: 
                   17552: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   17553: 
                   17554: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   17555: 
                   17556: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   17557: 
                   17558: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   17559: 
                   17560: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   17561: 
1.1182    raeburn  17562: 
1.1181    raeburn  17563: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   17564: 
1.1182    raeburn  17565: 
1.1181    raeburn  17566: Side Effects: None
                   17567: 
                   17568: =cut
                   17569: 
                   17570: # ---------------------------------------------- search for courses based on last activity etc.
                   17571: 
                   17572: sub build_filters {
                   17573:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   17574:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   17575:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   17576:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   17577:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  17578:     my ($list,$jscript);
1.1181    raeburn  17579:     my $onchange = 'javascript:updateFilters(this)';
                   17580:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   17581:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   17582:         $typeselectform,$instcodetitle);
                   17583:     if ($formname eq '') {
                   17584:         $formname = $caller;
                   17585:     }
                   17586:     foreach my $item (@{$filterlist}) {
                   17587:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   17588:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   17589:             if ($item eq 'domainfilter') {
                   17590:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   17591:             } elsif ($item eq 'coursefilter') {
                   17592:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   17593:             } elsif ($item eq 'ownerfilter') {
                   17594:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17595:             } elsif ($item eq 'ownerdomfilter') {
                   17596:                 $filter->{'ownerdomfilter'} =
                   17597:                     &LONCAPA::clean_domain($filter->{$item});
                   17598:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   17599:                                                        'ownerdomfilter',1);
                   17600:             } elsif ($item eq 'personfilter') {
                   17601:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   17602:             } elsif ($item eq 'persondomfilter') {
                   17603:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   17604:                                                         'persondomfilter',1);
                   17605:             } else {
                   17606:                 $filter->{$item} =~ s/\W//g;
                   17607:             }
                   17608:             if (!$filter->{$item}) {
                   17609:                 $filter->{$item} = '';
                   17610:             }
                   17611:         }
                   17612:         if ($item eq 'domainfilter') {
                   17613:             my $allow_blank = 1;
                   17614:             if ($formname eq 'portform') {
                   17615:                 $allow_blank=0;
                   17616:             } elsif ($formname eq 'studentform') {
                   17617:                 $allow_blank=0;
                   17618:             }
                   17619:             if ($fixeddom) {
                   17620:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   17621:                                     ' value="'.$codedom.'" />'.
                   17622:                                     &Apache::lonnet::domain($codedom,'description');
                   17623:             } else {
                   17624:                 $domainselectform = &select_dom_form($filter->{$item},
                   17625:                                                      'domainfilter',
                   17626:                                                       $allow_blank,'',$onchange);
                   17627:             }
                   17628:         } else {
                   17629:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   17630:         }
                   17631:     }
                   17632: 
                   17633:     # last course activity filter and selection
                   17634:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17635: 
                   17636:     # course created filter and selection
                   17637:     if (exists($filter->{'createdfilter'})) {
                   17638:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17639:     }
                   17640: 
1.1239    raeburn  17641:     my $prefix = $crstype;
                   17642:     if ($crstype eq 'Placement') {
                   17643:         $prefix = 'Placement Test'
                   17644:     }
1.1181    raeburn  17645:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  17646:                 'cac' => "$prefix Activity",
                   17647:                 'ccr' => "$prefix Created",
                   17648:                 'cde' => "$prefix Title",
                   17649:                 'cdo' => "$prefix Domain",
1.1181    raeburn  17650:                 'ins' => 'Institutional Code',
                   17651:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  17652:                 'cow' => "$prefix Owner/Co-owner",
                   17653:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  17654:                 'cog' => 'Type',
                   17655:              );
                   17656: 
                   17657:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17658:         my $typeval = 'Course';
                   17659:         if ($crstype eq 'Community') {
                   17660:             $typeval = 'Community';
1.1239    raeburn  17661:         } elsif ($crstype eq 'Placement') {
                   17662:             $typeval = 'Placement';
1.1181    raeburn  17663:         }
                   17664:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17665:     } else {
                   17666:         $typeselectform =  '<select name="type" size="1"';
                   17667:         if ($onchange) {
                   17668:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17669:         }
                   17670:         $typeselectform .= '>'."\n";
1.1237    raeburn  17671:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  17672:             my $shown;
                   17673:             if ($posstype eq 'Placement') {
                   17674:                 $shown = &mt('Placement Test');
                   17675:             } else {
                   17676:                 $shown = &mt($posstype);
                   17677:             }
1.1181    raeburn  17678:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  17679:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  17680:         }
                   17681:         $typeselectform.="</select>";
                   17682:     }
                   17683: 
                   17684:     my ($cloneableonlyform,$cloneabletitle);
                   17685:     if (exists($filter->{'cloneableonly'})) {
                   17686:         my $cloneableon = '';
                   17687:         my $cloneableoff = ' checked="checked"';
                   17688:         if ($filter->{'cloneableonly'}) {
                   17689:             $cloneableon = $cloneableoff;
                   17690:             $cloneableoff = '';
                   17691:         }
                   17692:         $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>';
                   17693:         if ($formname eq 'ccrs') {
1.1187    bisitz   17694:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  17695:         } else {
                   17696:             $cloneabletitle = &mt('Cloneable by you');
                   17697:         }
                   17698:     }
                   17699:     my $officialjs;
                   17700:     if ($crstype eq 'Course') {
                   17701:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  17702: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17703: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17704:             if ($codedom) { 
1.1181    raeburn  17705:                 $officialjs = 1;
                   17706:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17707:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17708:                                                                   $officialjs,$codetitlesref);
                   17709:                 if ($jscript) {
1.1182    raeburn  17710:                     $jscript = '<script type="text/javascript">'."\n".
                   17711:                                '// <![CDATA['."\n".
                   17712:                                $jscript."\n".
                   17713:                                '// ]]>'."\n".
                   17714:                                '</script>'."\n";
1.1181    raeburn  17715:                 }
                   17716:             }
                   17717:             if ($instcodeform eq '') {
                   17718:                 $instcodeform =
                   17719:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17720:                     $list->{'instcodefilter'}.'" />';
                   17721:                 $instcodetitle = $lt{'ins'};
                   17722:             } else {
                   17723:                 $instcodetitle = $lt{'inc'};
                   17724:             }
                   17725:             if ($fixeddom) {
                   17726:                 $instcodetitle .= '<br />('.$codedom.')';
                   17727:             }
                   17728:         }
                   17729:     }
                   17730:     my $output = qq|
                   17731: <form method="post" name="filterpicker" action="$action">
                   17732: <input type="hidden" name="form" value="$formname" />
                   17733: |;
                   17734:     if ($formname eq 'modifycourse') {
                   17735:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17736:                    '<input type="hidden" name="prevphase" value="'.
                   17737:                    $prevphase.'" />'."\n";
1.1198    musolffc 17738:     } elsif ($formname eq 'quotacheck') {
                   17739:         $output .= qq|
                   17740: <input type="hidden" name="sortby" value="" />
                   17741: <input type="hidden" name="sortorder" value="" />
                   17742: |;
                   17743:     } else {
1.1181    raeburn  17744:         my $name_input;
                   17745:         if ($cnameelement ne '') {
                   17746:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17747:                           $cnameelement.'" />';
                   17748:         }
                   17749:         $output .= qq|
1.1182    raeburn  17750: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17751: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  17752: $name_input
                   17753: $roleelement
                   17754: $multelement
                   17755: $typeelement
                   17756: |;
                   17757:         if ($formname eq 'portform') {
                   17758:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17759:         }
                   17760:     }
                   17761:     if ($fixeddom) {
                   17762:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17763:     }
                   17764:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17765:     if ($sincefilterform) {
                   17766:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17767:                   .$sincefilterform
                   17768:                   .&Apache::lonhtmlcommon::row_closure();
                   17769:     }
                   17770:     if ($createdfilterform) {
                   17771:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17772:                   .$createdfilterform
                   17773:                   .&Apache::lonhtmlcommon::row_closure();
                   17774:     }
                   17775:     if ($domainselectform) {
                   17776:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17777:                   .$domainselectform
                   17778:                   .&Apache::lonhtmlcommon::row_closure();
                   17779:     }
                   17780:     if ($typeselectform) {
                   17781:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17782:             $output .= $typeselectform;
                   17783:         } else {
                   17784:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17785:                       .$typeselectform
                   17786:                       .&Apache::lonhtmlcommon::row_closure();
                   17787:         }
                   17788:     }
                   17789:     if ($instcodeform) {
                   17790:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17791:                   .$instcodeform
                   17792:                   .&Apache::lonhtmlcommon::row_closure();
                   17793:     }
                   17794:     if (exists($filter->{'ownerfilter'})) {
                   17795:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17796:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17797:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17798:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17799:                    $ownerdomselectform.'</td></tr></table>'.
                   17800:                    &Apache::lonhtmlcommon::row_closure();
                   17801:     }
                   17802:     if (exists($filter->{'personfilter'})) {
                   17803:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17804:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17805:                    '<input type="text" name="personfilter" size="20" value="'.
                   17806:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17807:                    $persondomselectform.'</td></tr></table>'.
                   17808:                    &Apache::lonhtmlcommon::row_closure();
                   17809:     }
                   17810:     if (exists($filter->{'coursefilter'})) {
                   17811:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17812:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17813:                   .$list->{'coursefilter'}.'" />'
                   17814:                   .&Apache::lonhtmlcommon::row_closure();
                   17815:     }
                   17816:     if ($cloneableonlyform) {
                   17817:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17818:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17819:     }
                   17820:     if (exists($filter->{'descriptfilter'})) {
                   17821:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17822:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17823:                   .$list->{'descriptfilter'}.'" />'
                   17824:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17825:     }
                   17826:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17827:                '<input type="hidden" name="updater" value="" />'."\n".
                   17828:                '<input type="submit" name="gosearch" value="'.
                   17829:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17830:     return $jscript.$clonewarning.$output;
                   17831: }
                   17832: 
                   17833: =pod 
                   17834: 
                   17835: =item * &timebased_select_form()
                   17836: 
1.1182    raeburn  17837: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  17838: filter e.g., Course Activity, Course Created, when searching for courses
                   17839: or communities
                   17840: 
                   17841: Inputs:
                   17842: 
                   17843: item - name of form element (sincefilter or createdfilter)
                   17844: 
                   17845: filter - anonymous hash of criteria and their values
                   17846: 
                   17847: Returns: HTML for a select box contained a blank, then six time selections,
                   17848:          with value set in incoming form variables currently selected. 
                   17849: 
                   17850: Side Effects: None
                   17851: 
                   17852: =cut
                   17853: 
                   17854: sub timebased_select_form {
                   17855:     my ($item,$filter) = @_;
                   17856:     if (ref($filter) eq 'HASH') {
                   17857:         $filter->{$item} =~ s/[^\d-]//g;
                   17858:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17859:         return &select_form(
                   17860:                             $filter->{$item},
                   17861:                             $item,
                   17862:                             {      '-1' => '',
                   17863:                                 '86400' => &mt('today'),
                   17864:                                '604800' => &mt('last week'),
                   17865:                               '2592000' => &mt('last month'),
                   17866:                               '7776000' => &mt('last three months'),
                   17867:                              '15552000' => &mt('last six months'),
                   17868:                              '31104000' => &mt('last year'),
                   17869:                     'select_form_order' =>
                   17870:                            ['-1','86400','604800','2592000','7776000',
                   17871:                             '15552000','31104000']});
                   17872:     }
                   17873: }
                   17874: 
                   17875: =pod
                   17876: 
                   17877: =item * &js_changer()
                   17878: 
                   17879: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  17880: when course type or domain is changed, and also to hide 'Searching ...' on
                   17881: page load completion for page showing search result.
1.1181    raeburn  17882: 
                   17883: Inputs: None
                   17884: 
1.1183    raeburn  17885: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  17886: 
                   17887: Side Effects: None
                   17888: 
                   17889: =cut
                   17890: 
                   17891: sub js_changer {
                   17892:     return <<ENDJS;
                   17893: <script type="text/javascript">
                   17894: // <![CDATA[
                   17895: function updateFilters(caller) {
                   17896:     if (typeof(caller) != "undefined") {
                   17897:         document.filterpicker.updater.value = caller.name;
                   17898:     }
                   17899:     document.filterpicker.submit();
                   17900: }
1.1183    raeburn  17901: 
                   17902: function hideSearching() {
                   17903:     if (document.getElementById('searching')) {
                   17904:         document.getElementById('searching').style.display = 'none';
                   17905:     }
                   17906:     return;
                   17907: }
                   17908: 
1.1181    raeburn  17909: // ]]>
                   17910: </script>
                   17911: 
                   17912: ENDJS
                   17913: }
                   17914: 
                   17915: =pod
                   17916: 
1.1182    raeburn  17917: =item * &search_courses()
                   17918: 
                   17919: Process selected filters form course search form and pass to lonnet::courseiddump
                   17920: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17921: 
                   17922: Inputs:
                   17923: 
                   17924: dom - domain being searched 
                   17925: 
                   17926: type - course type ('Course' or 'Community' or '.' if any).
                   17927: 
                   17928: filter - anonymous hash of criteria and their values
                   17929: 
                   17930: numtitles - for institutional codes - number of categories
                   17931: 
                   17932: cloneruname - optional username of new course owner
                   17933: 
                   17934: clonerudom - optional domain of new course owner
                   17935: 
1.1221    raeburn  17936: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  17937:             (used when DC is using course creation form)
                   17938: 
                   17939: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17940: 
1.1221    raeburn  17941: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17942:            (and so can clone automatically)
                   17943: 
                   17944: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17945: 
                   17946: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   17947:               courses to clone 
1.1182    raeburn  17948: 
                   17949: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17950: 
                   17951: 
                   17952: Side Effects: None
                   17953: 
                   17954: =cut
                   17955: 
                   17956: 
                   17957: sub search_courses {
1.1221    raeburn  17958:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17959:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  17960:     my (%courses,%showcourses,$cloner);
                   17961:     if (($filter->{'ownerfilter'} ne '') ||
                   17962:         ($filter->{'ownerdomfilter'} ne '')) {
                   17963:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17964:                                        $filter->{'ownerdomfilter'};
                   17965:     }
                   17966:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17967:         if (!$filter->{$item}) {
                   17968:             $filter->{$item}='.';
                   17969:         }
                   17970:     }
                   17971:     my $now = time;
                   17972:     my $timefilter =
                   17973:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17974:     my ($createdbefore,$createdafter);
                   17975:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17976:         $createdbefore = $now;
                   17977:         $createdafter = $now-$filter->{'createdfilter'};
                   17978:     }
                   17979:     my ($instcodefilter,$regexpok);
                   17980:     if ($numtitles) {
                   17981:         if ($env{'form.official'} eq 'on') {
                   17982:             $instcodefilter =
                   17983:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17984:             $regexpok = 1;
                   17985:         } elsif ($env{'form.official'} eq 'off') {
                   17986:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17987:             unless ($instcodefilter eq '') {
                   17988:                 $regexpok = -1;
                   17989:             }
                   17990:         }
                   17991:     } else {
                   17992:         $instcodefilter = $filter->{'instcodefilter'};
                   17993:     }
                   17994:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17995:     if ($type eq '') { $type = '.'; }
                   17996: 
                   17997:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17998:         $cloner = $cloneruname.':'.$clonerudom;
                   17999:     }
                   18000:     %courses = &Apache::lonnet::courseiddump($dom,
                   18001:                                              $filter->{'descriptfilter'},
                   18002:                                              $timefilter,
                   18003:                                              $instcodefilter,
                   18004:                                              $filter->{'combownerfilter'},
                   18005:                                              $filter->{'coursefilter'},
                   18006:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18007:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18008:                                              $filter->{'cloneableonly'},
                   18009:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18010:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18011:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18012:         my $ccrole;
                   18013:         if ($type eq 'Community') {
                   18014:             $ccrole = 'co';
                   18015:         } else {
                   18016:             $ccrole = 'cc';
                   18017:         }
                   18018:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18019:                                                      $filter->{'persondomfilter'},
                   18020:                                                      'userroles',undef,
                   18021:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18022:                                                      $dom);
                   18023:         foreach my $role (keys(%rolehash)) {
                   18024:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18025:             my $cid = $cdom.'_'.$cnum;
                   18026:             if (exists($courses{$cid})) {
                   18027:                 if (ref($courses{$cid}) eq 'HASH') {
                   18028:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18029:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18030:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18031:                         }
                   18032:                     } else {
                   18033:                         $courses{$cid}{roles} = [$courserole];
                   18034:                     }
                   18035:                     $showcourses{$cid} = $courses{$cid};
                   18036:                 }
                   18037:             }
                   18038:         }
                   18039:         %courses = %showcourses;
                   18040:     }
                   18041:     return %courses;
                   18042: }
                   18043: 
                   18044: =pod
                   18045: 
1.1181    raeburn  18046: =back
                   18047: 
1.1207    raeburn  18048: =head1 Routines for version requirements for current course.
                   18049: 
                   18050: =over 4
                   18051: 
                   18052: =item * &check_release_required()
                   18053: 
                   18054: Compares required LON-CAPA version with version on server, and
                   18055: if required version is newer looks for a server with the required version.
                   18056: 
                   18057: Looks first at servers in user's owen domain; if none suitable, looks at
                   18058: servers in course's domain are permitted to host sessions for user's domain.
                   18059: 
                   18060: Inputs:
                   18061: 
                   18062: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18063: 
                   18064: $courseid - Course ID of current course
                   18065: 
                   18066: $rolecode - User's current role in course (for switchserver query string).
                   18067: 
                   18068: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18069: 
                   18070: 
                   18071: Returns:
                   18072: 
                   18073: $switchserver - query string tp append to /adm/switchserver call (if 
                   18074:                 current server's LON-CAPA version is too old. 
                   18075: 
                   18076: $warning - Message is displayed if no suitable server could be found.
                   18077: 
                   18078: =cut
                   18079: 
                   18080: sub check_release_required {
                   18081:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18082:     my ($switchserver,$warning);
                   18083:     if ($required ne '') {
                   18084:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18085:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18086:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18087:             my $otherserver;
                   18088:             if (($major eq '' && $minor eq '') ||
                   18089:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18090:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18091:                 my $switchlcrev =
                   18092:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18093:                                                            $userdomserver);
                   18094:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18095:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18096:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18097:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18098:                     if ($cdom ne $env{'user.domain'}) {
                   18099:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18100:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18101:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18102:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18103:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18104:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18105:                         my $canhost =
                   18106:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18107:                                                               $coursedomserver,
                   18108:                                                               $remoterev,
                   18109:                                                               $udomdefaults{'remotesessions'},
                   18110:                                                               $defdomdefaults{'hostedsessions'});
                   18111: 
                   18112:                         if ($canhost) {
                   18113:                             $otherserver = $coursedomserver;
                   18114:                         } else {
                   18115:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   18116:                         }
                   18117:                     } else {
                   18118:                         $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).");
                   18119:                     }
                   18120:                 } else {
                   18121:                     $otherserver = $userdomserver;
                   18122:                 }
                   18123:             }
                   18124:             if ($otherserver ne '') {
                   18125:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18126:             }
                   18127:         }
                   18128:     }
                   18129:     return ($switchserver,$warning);
                   18130: }
                   18131: 
                   18132: =pod
                   18133: 
                   18134: =item * &check_release_result()
                   18135: 
                   18136: Inputs:
                   18137: 
                   18138: $switchwarning - Warning message if no suitable server found to host session.
                   18139: 
                   18140: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18141:                 and current role.
                   18142: 
                   18143: Returns: HTML to display with information about requirement to switch server.
                   18144:          Either displaying warning with link to Roles/Courses screen or
                   18145:          display link to switchserver.
                   18146: 
1.1181    raeburn  18147: =cut
                   18148: 
1.1207    raeburn  18149: sub check_release_result {
                   18150:     my ($switchwarning,$switchserver) = @_;
                   18151:     my $output = &start_page('Selected course unavailable on this server').
                   18152:                  '<p class="LC_warning">';
                   18153:     if ($switchwarning) {
                   18154:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18155:         if (&show_course()) {
                   18156:             $output .= &mt('Display courses');
                   18157:         } else {
                   18158:             $output .= &mt('Display roles');
                   18159:         }
                   18160:         $output .= '</a>';
                   18161:     } elsif ($switchserver) {
                   18162:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18163:                    '<br />'.
                   18164:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18165:                    &mt('Switch Server').
                   18166:                    '</a>';
                   18167:     }
                   18168:     $output .= '</p>'.&end_page();
                   18169:     return $output;
                   18170: }
                   18171: 
                   18172: =pod
                   18173: 
                   18174: =item * &needs_coursereinit()
                   18175: 
                   18176: Determine if course contents stored for user's session needs to be
                   18177: refreshed, because content has changed since "Big Hash" last tied.
                   18178: 
                   18179: Check for change is made if time last checked is more than 10 minutes ago
                   18180: (by default).
                   18181: 
                   18182: Inputs:
                   18183: 
                   18184: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18185: 
                   18186: $interval (optional) - Time which may elapse (in s) between last check for content
                   18187:                        change in current course. (default: 600 s).  
                   18188: 
                   18189: Returns: an array; first element is:
                   18190: 
                   18191: =over 4
                   18192: 
                   18193: 'switch' - if content updates mean user's session
                   18194:            needs to be switched to a server running a newer LON-CAPA version
                   18195:  
                   18196: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18197:            on current server hosting user's session                
                   18198: 
                   18199: ''       - if no action required.
                   18200: 
                   18201: =back
                   18202: 
                   18203: If first item element is 'switch':
                   18204: 
                   18205: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18206: 
                   18207: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18208:                               and current role. 
                   18209: 
                   18210: otherwise: no other elements returned.
                   18211: 
                   18212: =back
                   18213: 
                   18214: =cut
                   18215: 
                   18216: sub needs_coursereinit {
                   18217:     my ($loncaparev,$interval) = @_;
                   18218:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18219:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18221:     my $now = time;
                   18222:     if ($interval eq '') {
                   18223:         $interval = 600;
                   18224:     }
                   18225:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18226:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18227:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18228:         if ($blocked) {
                   18229:             return ();
                   18230:         }
1.1207    raeburn  18231:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18232:         if ($lastchange > $env{'request.course.tied'}) {
                   18233:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18234:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18235:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18236:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18237:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18238:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   18239:                     my ($switchserver,$switchwarning) =
                   18240:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18241:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   18242:                     if ($switchwarning ne '' || $switchserver ne '') {
                   18243:                         return ('switch',$switchwarning,$switchserver);
                   18244:                     }
                   18245:                 }
                   18246:             }
                   18247:             return ('update');
                   18248:         }
                   18249:     }
                   18250:     return ();
                   18251: }
1.1181    raeburn  18252: 
1.1083    raeburn  18253: sub update_content_constraints {
1.1326    raeburn  18254:     my ($cdom,$cnum,$chome,$cid,$keeporder) = @_;
1.1083    raeburn  18255:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18256:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18257:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18258:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18259:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18260:         if ($item eq 'resourcetag') {
                   18261:             if ($name eq 'responsetype') {
                   18262:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18263:             }
1.1307    raeburn  18264:         } elsif ($item eq 'course') {
                   18265:             if ($name eq 'courserestype') {
                   18266:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18267:             }
1.1083    raeburn  18268:         }
                   18269:     }
                   18270:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18271:     if (defined($navmap)) {
1.1307    raeburn  18272:         my (%allresponses,%allcrsrestypes);
                   18273:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18274:             if ($res->is_tool()) {
                   18275:                 if ($allcrsrestypes{'exttool'}) {
                   18276:                     $allcrsrestypes{'exttool'} ++;
                   18277:                 } else {
                   18278:                     $allcrsrestypes{'exttool'} = 1;
                   18279:                 }
                   18280:                 next;
                   18281:             }
1.1083    raeburn  18282:             my %responses = $res->responseTypes();
                   18283:             foreach my $key (keys(%responses)) {
                   18284:                 next unless(exists($checkresponsetypes{$key}));
                   18285:                 $allresponses{$key} += $responses{$key};
                   18286:             }
                   18287:         }
                   18288:         foreach my $key (keys(%allresponses)) {
                   18289:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18290:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18291:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18292:             }
                   18293:         }
1.1307    raeburn  18294:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18295:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18296:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18297:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18298:             }
                   18299:         }
1.1083    raeburn  18300:         undef($navmap);
                   18301:     }
1.1326    raeburn  18302:     my (@resources,@order,@resparms,@zombies);
                   18303:     if ($keeporder) {
                   18304:         use LONCAPA::map;
                   18305:         @resources = @LONCAPA::map::resources;
                   18306:         @order = @LONCAPA::map::order;
                   18307:         @resparms = @LONCAPA::map::resparms;
                   18308:         @zombies = @LONCAPA::map::zombies;
                   18309:     }
1.1308    raeburn  18310:     my $suppmap = 'supplemental.sequence';
                   18311:     my ($suppcount,$supptools,$errors) = (0,0,0);
                   18312:     ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
                   18313:                                                             $suppcount,$supptools,$errors);
1.1326    raeburn  18314:     if ($keeporder) {
                   18315:         @LONCAPA::map::resources = @resources;
                   18316:         @LONCAPA::map::order = @order;
                   18317:         @LONCAPA::map::resparms = @resparms;
                   18318:         @LONCAPA::map::zombies = @zombies;
                   18319:     }
1.1308    raeburn  18320:     if ($supptools) {
                   18321:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18322:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18323:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18324:         }
                   18325:     }
1.1083    raeburn  18326:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18327:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18328:     }
                   18329:     return;
                   18330: }
                   18331: 
1.1110    raeburn  18332: sub allmaps_incourse {
                   18333:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18334:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18335:         $cid = $env{'request.course.id'};
                   18336:         $cdom = $env{'course.'.$cid.'.domain'};
                   18337:         $cnum = $env{'course.'.$cid.'.num'};
                   18338:         $chome = $env{'course.'.$cid.'.home'};
                   18339:     }
                   18340:     my %allmaps = ();
                   18341:     my $lastchange =
                   18342:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18343:     if ($lastchange > $env{'request.course.tied'}) {
                   18344:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18345:         unless ($ferr) {
1.1326    raeburn  18346:             &update_content_constraints($cdom,$cnum,$chome,$cid,1);
1.1110    raeburn  18347:         }
                   18348:     }
                   18349:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18350:     if (defined($navmap)) {
                   18351:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18352:             $allmaps{$res->src()} = 1;
                   18353:         }
                   18354:     }
                   18355:     return \%allmaps;
                   18356: }
                   18357: 
1.1083    raeburn  18358: sub parse_supplemental_title {
                   18359:     my ($title) = @_;
                   18360: 
                   18361:     my ($foldertitle,$renametitle);
                   18362:     if ($title =~ /&amp;&amp;&amp;/) {
                   18363:         $title = &HTML::Entites::decode($title);
                   18364:     }
                   18365:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18366:         $renametitle=$4;
                   18367:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18368:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18369:         my $name =  &plainname($uname,$udom);
                   18370:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18371:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   18372:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   18373:             $name.': <br />'.$foldertitle;
                   18374:     }
                   18375:     if (wantarray) {
                   18376:         return ($title,$foldertitle,$renametitle);
                   18377:     }
                   18378:     return $title;
                   18379: }
                   18380: 
1.1143    raeburn  18381: sub recurse_supplemental {
1.1308    raeburn  18382:     my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
1.1143    raeburn  18383:     if ($suppmap) {
                   18384:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   18385:         if ($fatal) {
                   18386:             $errors ++;
                   18387:         } else {
                   18388:             if ($#LONCAPA::map::resources > 0) {
                   18389:                 foreach my $res (@LONCAPA::map::resources) {
                   18390:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   18391:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  18392:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1308    raeburn  18393:                             ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
                   18394:                                                                    $numfiles,$numexttools,$errors);
1.1143    raeburn  18395:                         } else {
1.1308    raeburn  18396:                             if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   18397:                                 $numexttools ++;
                   18398:                             }
1.1143    raeburn  18399:                             $numfiles ++;
                   18400:                         }
                   18401:                     }
                   18402:                 }
                   18403:             }
                   18404:         }
                   18405:     }
1.1308    raeburn  18406:     return ($numfiles,$numexttools,$errors);
1.1143    raeburn  18407: }
                   18408: 
1.1101    raeburn  18409: sub symb_to_docspath {
1.1267    raeburn  18410:     my ($symb,$navmapref) = @_;
                   18411:     return unless ($symb && ref($navmapref));
1.1101    raeburn  18412:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   18413:     if ($resurl=~/\.(sequence|page)$/) {
                   18414:         $mapurl=$resurl;
                   18415:     } elsif ($resurl eq 'adm/navmaps') {
                   18416:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   18417:     }
                   18418:     my $mapresobj;
1.1267    raeburn  18419:     unless (ref($$navmapref)) {
                   18420:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   18421:     }
                   18422:     if (ref($$navmapref)) {
                   18423:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  18424:     }
                   18425:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   18426:     my $type=$2;
                   18427:     my $path;
                   18428:     if (ref($mapresobj)) {
                   18429:         my $pcslist = $mapresobj->map_hierarchy();
                   18430:         if ($pcslist ne '') {
                   18431:             foreach my $pc (split(/,/,$pcslist)) {
                   18432:                 next if ($pc <= 1);
1.1267    raeburn  18433:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  18434:                 if (ref($res)) {
                   18435:                     my $thisurl = $res->src();
                   18436:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   18437:                     my $thistitle = $res->title();
                   18438:                     $path .= '&'.
                   18439:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  18440:                              &escape($thistitle).
1.1101    raeburn  18441:                              ':'.$res->randompick().
                   18442:                              ':'.$res->randomout().
                   18443:                              ':'.$res->encrypted().
                   18444:                              ':'.$res->randomorder().
                   18445:                              ':'.$res->is_page();
                   18446:                 }
                   18447:             }
                   18448:         }
                   18449:         $path =~ s/^\&//;
                   18450:         my $maptitle = $mapresobj->title();
                   18451:         if ($mapurl eq 'default') {
1.1129    raeburn  18452:             $maptitle = 'Main Content';
1.1101    raeburn  18453:         }
                   18454:         $path .= (($path ne '')? '&' : '').
                   18455:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18456:                  &escape($maptitle).
1.1101    raeburn  18457:                  ':'.$mapresobj->randompick().
                   18458:                  ':'.$mapresobj->randomout().
                   18459:                  ':'.$mapresobj->encrypted().
                   18460:                  ':'.$mapresobj->randomorder().
                   18461:                  ':'.$mapresobj->is_page();
                   18462:     } else {
                   18463:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   18464:         my $ispage = (($type eq 'page')? 1 : '');
                   18465:         if ($mapurl eq 'default') {
1.1129    raeburn  18466:             $maptitle = 'Main Content';
1.1101    raeburn  18467:         }
                   18468:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  18469:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  18470:     }
                   18471:     unless ($mapurl eq 'default') {
                   18472:         $path = 'default&'.
1.1146    raeburn  18473:                 &escape('Main Content').
1.1101    raeburn  18474:                 ':::::&'.$path;
                   18475:     }
                   18476:     return $path;
                   18477: }
                   18478: 
1.1094    raeburn  18479: sub captcha_display {
1.1327    raeburn  18480:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18481:     my ($output,$error);
1.1234    raeburn  18482:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  18483:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18484:     if ($captcha eq 'original') {
1.1094    raeburn  18485:         $output = &create_captcha();
                   18486:         unless ($output) {
1.1172    raeburn  18487:             $error = 'captcha';
1.1094    raeburn  18488:         }
                   18489:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18490:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  18491:         unless ($output) {
1.1172    raeburn  18492:             $error = 'recaptcha';
1.1094    raeburn  18493:         }
                   18494:     }
1.1234    raeburn  18495:     return ($output,$error,$captcha,$version);
1.1094    raeburn  18496: }
                   18497: 
                   18498: sub captcha_response {
1.1327    raeburn  18499:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  18500:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  18501:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  18502:     if ($captcha eq 'original') {
1.1094    raeburn  18503:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18504:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  18505:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  18506:     } else {
                   18507:         $captcha_chk = 1;
                   18508:     }
                   18509:     return ($captcha_chk,$captcha_error);
                   18510: }
                   18511: 
                   18512: sub get_captcha_config {
1.1327    raeburn  18513:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  18514:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  18515:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18516:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18517:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  18518:     if ($context eq 'usercreation') {
                   18519:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18520:         if (ref($domconfig{$context}) eq 'HASH') {
                   18521:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18522:             if (ref($hashtocheck) eq 'HASH') {
                   18523:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18524:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18525:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18526:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18527:                     }
                   18528:                     if ($privkey && $pubkey) {
                   18529:                         $captcha = 'recaptcha';
1.1234    raeburn  18530:                         $version = $hashtocheck->{'recaptchaversion'};
                   18531:                         if ($version ne '2') {
                   18532:                             $version = 1;
                   18533:                         }
1.1095    raeburn  18534:                     } else {
                   18535:                         $captcha = 'original';
                   18536:                     }
                   18537:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18538:                     $captcha = 'original';
                   18539:                 }
1.1094    raeburn  18540:             }
1.1095    raeburn  18541:         } else {
                   18542:             $captcha = 'captcha';
                   18543:         }
                   18544:     } elsif ($context eq 'login') {
                   18545:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18546:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18547:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18548:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  18549:             if ($privkey && $pubkey) {
                   18550:                 $captcha = 'recaptcha';
1.1234    raeburn  18551:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18552:                 if ($version ne '2') {
                   18553:                     $version = 1; 
                   18554:                 }
1.1095    raeburn  18555:             } else {
                   18556:                 $captcha = 'original';
1.1094    raeburn  18557:             }
1.1095    raeburn  18558:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18559:             $captcha = 'original';
1.1094    raeburn  18560:         }
1.1327    raeburn  18561:     } elsif ($context eq 'passwords') {
                   18562:         if ($dom_in_effect) {
                   18563:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18564:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18565:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18566:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18567:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18568:                 }
                   18569:                 if ($privkey && $pubkey) {
                   18570:                     $captcha = 'recaptcha';
                   18571:                     $version = $passwdconf{'recaptchaversion'};
                   18572:                     if ($version ne '2') {
                   18573:                         $version = 1;
                   18574:                     }
                   18575:                 } else {
                   18576:                     $captcha = 'original';
                   18577:                 }
                   18578:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18579:                 $captcha = 'original';
                   18580:             }
                   18581:         }
                   18582:     } 
1.1234    raeburn  18583:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  18584: }
                   18585: 
                   18586: sub create_captcha {
                   18587:     my %captcha_params = &captcha_settings();
                   18588:     my ($output,$maxtries,$tries) = ('',10,0);
                   18589:     while ($tries < $maxtries) {
                   18590:         $tries ++;
                   18591:         my $captcha = Authen::Captcha->new (
                   18592:                                            output_folder => $captcha_params{'output_dir'},
                   18593:                                            data_folder   => $captcha_params{'db_dir'},
                   18594:                                           );
                   18595:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18596: 
                   18597:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18598:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  18599:                       '<span class="LC_nobreak">'.
1.1094    raeburn  18600:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  18601:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1367    raeburn  18602:                       '</span><br />'.
1.1176    raeburn  18603:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  18604:             last;
                   18605:         }
                   18606:     }
1.1323    raeburn  18607:     if ($output eq '') {
                   18608:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18609:     }
1.1094    raeburn  18610:     return $output;
                   18611: }
                   18612: 
                   18613: sub captcha_settings {
                   18614:     my %captcha_params = (
                   18615:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18616:                            www_output_dir => "/captchaspool",
                   18617:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18618:                            numchars       => '5',
                   18619:                          );
                   18620:     return %captcha_params;
                   18621: }
                   18622: 
                   18623: sub check_captcha {
                   18624:     my ($captcha_chk,$captcha_error);
                   18625:     my $code = $env{'form.code'};
                   18626:     my $md5sum = $env{'form.crypt'};
                   18627:     my %captcha_params = &captcha_settings();
                   18628:     my $captcha = Authen::Captcha->new(
                   18629:                       output_folder => $captcha_params{'output_dir'},
                   18630:                       data_folder   => $captcha_params{'db_dir'},
                   18631:                   );
1.1109    raeburn  18632:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  18633:     my %captcha_hash = (
                   18634:                         0       => 'Code not checked (file error)',
                   18635:                        -1      => 'Failed: code expired',
                   18636:                        -2      => 'Failed: invalid code (not in database)',
                   18637:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18638:     );
                   18639:     if ($captcha_chk != 1) {
                   18640:         $captcha_error = $captcha_hash{$captcha_chk}
                   18641:     }
                   18642:     return ($captcha_chk,$captcha_error);
                   18643: }
                   18644: 
                   18645: sub create_recaptcha {
1.1234    raeburn  18646:     my ($pubkey,$version) = @_;
                   18647:     if ($version >= 2) {
1.1367    raeburn  18648:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18649:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  18650:     } else {
                   18651:         my $use_ssl;
                   18652:         if ($ENV{'SERVER_PORT'} == 443) {
                   18653:             $use_ssl = 1;
                   18654:         }
                   18655:         my $captcha = Captcha::reCAPTCHA->new;
                   18656:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18657:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18658:                &mt('If the text is hard to read, [_1] will replace them.',
                   18659:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18660:                '<br /><br />';
                   18661:     }
1.1094    raeburn  18662: }
                   18663: 
                   18664: sub check_recaptcha {
1.1234    raeburn  18665:     my ($privkey,$version) = @_;
1.1094    raeburn  18666:     my $captcha_chk;
1.1350    raeburn  18667:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  18668:     if ($version >= 2) {
                   18669:         my %info = (
                   18670:                      secret   => $privkey, 
                   18671:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  18672:                      remoteip => $ip,
1.1234    raeburn  18673:                    );
1.1280    raeburn  18674:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   18675:         $request->content(join('&',map {
                   18676:                          my $name = escape($_);
                   18677:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   18678:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   18679:                          : &escape($info{$_}) );
                   18680:         } keys(%info)));
                   18681:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  18682:         if ($response->is_success)  {
                   18683:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18684:             if (ref($data) eq 'HASH') {
                   18685:                 if ($data->{'success'}) {
                   18686:                     $captcha_chk = 1;
                   18687:                 }
                   18688:             }
                   18689:         }
                   18690:     } else {
                   18691:         my $captcha = Captcha::reCAPTCHA->new;
                   18692:         my $captcha_result =
                   18693:             $captcha->check_answer(
                   18694:                                     $privkey,
1.1350    raeburn  18695:                                     $ip,
1.1234    raeburn  18696:                                     $env{'form.recaptcha_challenge_field'},
                   18697:                                     $env{'form.recaptcha_response_field'},
                   18698:                                   );
                   18699:         if ($captcha_result->{is_valid}) {
                   18700:             $captcha_chk = 1;
                   18701:         }
1.1094    raeburn  18702:     }
                   18703:     return $captcha_chk;
                   18704: }
                   18705: 
1.1174    raeburn  18706: sub emailusername_info {
1.1244    raeburn  18707:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  18708:     my %titles = &Apache::lonlocal::texthash (
                   18709:                      lastname      => 'Last Name',
                   18710:                      firstname     => 'First Name',
                   18711:                      institution   => 'School/college/university',
                   18712:                      location      => "School's city, state/province, country",
                   18713:                      web           => "School's web address",
                   18714:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  18715:                      id            => 'Student/Employee ID',
1.1174    raeburn  18716:                  );
                   18717:     return (\@fields,\%titles);
                   18718: }
                   18719: 
1.1161    raeburn  18720: sub cleanup_html {
                   18721:     my ($incoming) = @_;
                   18722:     my $outgoing;
                   18723:     if ($incoming ne '') {
                   18724:         $outgoing = $incoming;
                   18725:         $outgoing =~ s/;/&#059;/g;
                   18726:         $outgoing =~ s/\#/&#035;/g;
                   18727:         $outgoing =~ s/\&/&#038;/g;
                   18728:         $outgoing =~ s/</&#060;/g;
                   18729:         $outgoing =~ s/>/&#062;/g;
                   18730:         $outgoing =~ s/\(/&#040/g;
                   18731:         $outgoing =~ s/\)/&#041;/g;
                   18732:         $outgoing =~ s/"/&#034;/g;
                   18733:         $outgoing =~ s/'/&#039;/g;
                   18734:         $outgoing =~ s/\$/&#036;/g;
                   18735:         $outgoing =~ s{/}{&#047;}g;
                   18736:         $outgoing =~ s/=/&#061;/g;
                   18737:         $outgoing =~ s/\\/&#092;/g
                   18738:     }
                   18739:     return $outgoing;
                   18740: }
                   18741: 
1.1190    musolffc 18742: # Checks for critical messages and returns a redirect url if one exists.
                   18743: # $interval indicates how often to check for messages.
1.1282    raeburn  18744: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 18745: sub critical_redirect {
1.1282    raeburn  18746:     my ($interval,$context) = @_;
1.1356    raeburn  18747:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18748:         return ();
                   18749:     }
1.1190    musolffc 18750:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  18751:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18752:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18753:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  18754:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18755:             if ($blocked) {
                   18756:                 my $checkrole = "cm./$cdom/$cnum";
                   18757:                 if ($env{'request.course.sec'} ne '') {
                   18758:                     $checkrole .= "/$env{'request.course.sec'}";
                   18759:                 }
                   18760:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18761:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18762:                     return;
                   18763:                 }
                   18764:             }
                   18765:         }
1.1190    musolffc 18766:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   18767:                                         $env{'user.name'});
                   18768:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  18769:         my $redirecturl;
1.1190    musolffc 18770:         if ($what[0]) {
1.1356    raeburn  18771: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 18772: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  18773: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18774:                 return (1, $url);
1.1190    musolffc 18775:             }
1.1191    raeburn  18776:         }
                   18777:     } 
                   18778:     return ();
1.1190    musolffc 18779: }
                   18780: 
1.1174    raeburn  18781: # Use:
                   18782: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18783: #
                   18784: ##################################################
                   18785: #          password associated functions         #
                   18786: ##################################################
                   18787: sub des_keys {
                   18788:     # Make a new key for DES encryption.
                   18789:     # Each key has two parts which are returned separately.
                   18790:     # Please note:  Each key must be passed through the &hex function
                   18791:     # before it is output to the web browser.  The hex versions cannot
                   18792:     # be used to decrypt.
                   18793:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18794:                 '8','9','a','b','c','d','e','f');
                   18795:     my $lkey='';
                   18796:     for (0..7) {
                   18797:         $lkey.=$hexstr[rand(15)];
                   18798:     }
                   18799:     my $ukey='';
                   18800:     for (0..7) {
                   18801:         $ukey.=$hexstr[rand(15)];
                   18802:     }
                   18803:     return ($lkey,$ukey);
                   18804: }
                   18805: 
                   18806: sub des_decrypt {
                   18807:     my ($key,$cyphertext) = @_;
                   18808:     my $keybin=pack("H16",$key);
                   18809:     my $cypher;
                   18810:     if ($Crypt::DES::VERSION>=2.03) {
                   18811:         $cypher=new Crypt::DES $keybin;
                   18812:     } else {
                   18813:         $cypher=new DES $keybin;
                   18814:     }
1.1233    raeburn  18815:     my $plaintext='';
                   18816:     my $cypherlength = length($cyphertext);
                   18817:     my $numchunks = int($cypherlength/32);
                   18818:     for (my $j=0; $j<$numchunks; $j++) {
                   18819:         my $start = $j*32;
                   18820:         my $cypherblock = substr($cyphertext,$start,32);
                   18821:         my $chunk =
                   18822:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18823:         $chunk .=
                   18824:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18825:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18826:         $plaintext .= $chunk;
                   18827:     }
1.1174    raeburn  18828:     return $plaintext;
                   18829: }
                   18830: 
1.1344    raeburn  18831: sub get_requested_shorturls {
1.1309    raeburn  18832:     my ($cdom,$cnum,$navmap) = @_;
                   18833:     return unless (ref($navmap));
1.1344    raeburn  18834:     my ($numnew,$errors);
1.1309    raeburn  18835:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18836:     if (@toshorten) {
                   18837:         my (%maps,%resources,%titles);
                   18838:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18839:                                                                'shorturls',$cdom,$cnum);
                   18840:         if (keys(%resources)) {
1.1344    raeburn  18841:             my %tocreate;
1.1309    raeburn  18842:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18843:                 my $symb = $resources{$item};
                   18844:                 if ($symb) {
                   18845:                     $tocreate{$cnum.'&'.$symb} = 1;
                   18846:                 }
                   18847:             }
1.1344    raeburn  18848:             if (keys(%tocreate)) {
                   18849:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18850:                                                       \%tocreate);
                   18851:             }
1.1309    raeburn  18852:         }
1.1344    raeburn  18853:     }
                   18854:     return ($numnew,$errors);
                   18855: }
                   18856: 
                   18857: sub make_short_symbs {
                   18858:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18859:     my ($numnew,@errors);
                   18860:     if (ref($tocreateref) eq 'HASH') {
                   18861:         my %tocreate = %{$tocreateref};
1.1309    raeburn  18862:         if (keys(%tocreate)) {
                   18863:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18864:             my $su = Short::URL->new(no_vowels => 1);
                   18865:             my $init = '';
                   18866:             my (%newunique,%addcourse,%courseonly,%failed);
                   18867:             # get lock on tiny db
                   18868:             my $now = time;
1.1344    raeburn  18869:             if ($lockuser eq '') {
                   18870:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18871:             }
1.1309    raeburn  18872:             my $lockhash = {
1.1344    raeburn  18873:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  18874:                             };
                   18875:             my $tries = 0;
                   18876:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18877:             my ($code,$error);
                   18878:             while (($gotlock ne 'ok') && ($tries<3)) {
                   18879:                 $tries ++;
                   18880:                 sleep 1;
1.1319    raeburn  18881:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  18882:             }
                   18883:             if ($gotlock eq 'ok') {
                   18884:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18885:                                        \%addcourse,\%courseonly,\%failed);
                   18886:                 if (keys(%failed)) {
                   18887:                     my $numfailed = scalar(keys(%failed));
                   18888:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18889:                 }
                   18890:                 if (keys(%newunique)) {
                   18891:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18892:                     if ($putres eq 'ok') {
                   18893:                         $numnew = scalar(keys(%newunique));
                   18894:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18895:                         unless ($newputres eq 'ok') {
                   18896:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18897:                         }
                   18898:                     } else {
                   18899:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18900:                     }
                   18901:                 }
                   18902:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18903:                 unless ($dellockres eq 'ok') {
                   18904:                     push(@errors,&mt('error: could not release lockfile'));
                   18905:                 }
                   18906:             } else {
                   18907:                 push(@errors,&mt('error: could not obtain lockfile'));
                   18908:             }
                   18909:             if (keys(%courseonly)) {
                   18910:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18911:                 if ($result ne 'ok') {
                   18912:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18913:                 }
                   18914:             }
                   18915:         }
                   18916:     }
                   18917:     return ($numnew,\@errors);
                   18918: }
                   18919: 
                   18920: sub shorten_symbs {
                   18921:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18922:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18923:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18924:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18925:     my (%possibles,%collisions);
                   18926:     foreach my $key (keys(%{$tocreate})) {
                   18927:         my $num = String::CRC32::crc32($key);
                   18928:         my $tiny = $su->encode($num,$init);
                   18929:         if ($tiny) {
                   18930:             $possibles{$tiny} = $key;
                   18931:         }
                   18932:     }
                   18933:     if (!$init) {
                   18934:         $init = 1;
                   18935:     } else {
                   18936:         $init ++;
                   18937:     }
                   18938:     if (keys(%possibles)) {
                   18939:         my @posstiny = keys(%possibles);
                   18940:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18941:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18942:         if (keys(%currtiny)) {
                   18943:             foreach my $key (keys(%currtiny)) {
                   18944:                 next if ($currtiny{$key} eq '');
                   18945:                 if ($currtiny{$key} eq $possibles{$key}) {
                   18946:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18947:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18948:                         $courseonly->{$tsymb} = $key;
                   18949:                     }
                   18950:                 } else {
                   18951:                     $collisions{$possibles{$key}} = 1;
                   18952:                 }
                   18953:                 delete($possibles{$key});
                   18954:             }
                   18955:         }
                   18956:         foreach my $key (keys(%possibles)) {
                   18957:             $newunique->{$key} = $possibles{$key};
                   18958:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18959:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18960:                 $addcourse->{$tsymb} = $key;
                   18961:             }
                   18962:         }
                   18963:     }
                   18964:     if (keys(%collisions)) {
                   18965:         if ($init <5) {
                   18966:             if (!$init) {
                   18967:                 $init = 1;
                   18968:             } else {
                   18969:                 $init ++;
                   18970:             }
                   18971:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18972:                                    $newunique,$addcourse,$courseonly,$failed);
                   18973:         } else {
                   18974:             foreach my $key (keys(%collisions)) {
                   18975:                 $failed->{$key} = 1;
                   18976:             }
                   18977:         }
                   18978:     }
                   18979:     return $init;
                   18980: }
                   18981: 
1.1328    raeburn  18982: sub is_nonframeable {
1.1329    raeburn  18983:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18984:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  18985:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  18986: 
                   18987:     $remprotocol = lc($remprotocol);
                   18988:     $remhost = lc($remhost);
                   18989:     my $remport = 80;
                   18990:     if ($remprotocol eq 'https') {
                   18991:         $remport = 443;
                   18992:     }
1.1330    raeburn  18993:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  18994:     if ($cached) {
                   18995:         unless ($nocache) {
                   18996:             if ($result) {
                   18997:                 return 1;
                   18998:             } else {
                   18999:                 return 0;
                   19000:             }
                   19001:         }
                   19002:     }
1.1328    raeburn  19003:     my $uselink;
                   19004:     my $request = new HTTP::Request('HEAD',$url);
                   19005:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19006:     if ($response->is_success()) {
                   19007:         my $secpolicy = lc($response->header('content-security-policy'));
                   19008:         my $xframeop = lc($response->header('x-frame-options'));
                   19009:         $secpolicy =~ s/^\s+|\s+$//g;
                   19010:         $xframeop =~ s/^\s+|\s+$//g;
                   19011:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19012:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19013:             my ($origin,$protocol,$port);
                   19014:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19015:                 $port = $ENV{'SERVER_PORT'};
                   19016:             } else {
                   19017:                 $port = 80;
                   19018:             }
                   19019:             if ($absolute eq '') {
                   19020:                 $protocol = 'http:';
                   19021:                 if ($port == 443) {
                   19022:                     $protocol = 'https:';
                   19023:                 }
                   19024:                 $origin = $protocol.'//'.lc($hostname);
                   19025:             } else {
                   19026:                 $origin = lc($absolute);
                   19027:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19028:             }
                   19029:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19030:                 my $framepolicy = $1;
                   19031:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19032:                 my @policies = split(/\s+/,$framepolicy);
                   19033:                 if (@policies) {
                   19034:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19035:                         $uselink = 1;
                   19036:                     } else {
                   19037:                         $uselink = 1;
                   19038:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19039:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19040:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19041:                             undef($uselink);
                   19042:                         }
                   19043:                         if ($uselink) {
                   19044:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19045:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19046:                                     undef($uselink);
                   19047:                                 }
                   19048:                             }
                   19049:                         }
                   19050:                         if ($uselink) {
                   19051:                             my @possok;
                   19052:                             if ($ip ne '') {
                   19053:                                 push(@possok,$ip);
                   19054:                             }
                   19055:                             my $hoststr = '';
                   19056:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19057:                                 if ($hoststr eq '') {
                   19058:                                     $hoststr = $part;
                   19059:                                 } else {
                   19060:                                     $hoststr = "$part.$hoststr";
                   19061:                                 }
                   19062:                                 if ($hoststr eq $hostname) {
                   19063:                                     push(@possok,$hostname);
                   19064:                                 } else {
                   19065:                                     push(@possok,"*.$hoststr");
                   19066:                                 }
                   19067:                             }
                   19068:                             if (@possok) {
                   19069:                                 foreach my $poss (@possok) {
                   19070:                                     last if (!$uselink);
                   19071:                                     foreach my $policy (@policies) {
                   19072:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19073:                                             undef($uselink);
                   19074:                                             last;
                   19075:                                         }
                   19076:                                     }
                   19077:                                 }
                   19078:                             }
                   19079:                         }
                   19080:                     }
                   19081:                 }
                   19082:             } elsif ($xframeop ne '') {
                   19083:                 $uselink = 1;
                   19084:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19085:                 if (@policies) {
                   19086:                     unless (grep(/^deny$/,@policies)) {
                   19087:                         if ($origin ne '') {
                   19088:                             if (grep(/^sameorigin$/,@policies)) {
                   19089:                                 if ($remotehost eq $origin) {
                   19090:                                     undef($uselink);
                   19091:                                 }
                   19092:                             }
                   19093:                             if ($uselink) {
                   19094:                                 foreach my $policy (@policies) {
                   19095:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19096:                                         my $allowfrom = $1;
                   19097:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19098:                                             undef($uselink);
                   19099:                                             last;
                   19100:                                         }
                   19101:                                     }
                   19102:                                 }
                   19103:                             }
                   19104:                         }
                   19105:                     }
                   19106:                 }
                   19107:             }
                   19108:         }
                   19109:     }
1.1329    raeburn  19110:     if ($nocache) {
                   19111:         if ($cached) {
                   19112:             my $devalidate;
                   19113:             if ($uselink && !$result) {
                   19114:                 $devalidate = 1;
                   19115:             } elsif (!$uselink && $result) {
                   19116:                 $devalidate = 1;
                   19117:             }
                   19118:             if ($devalidate) {
                   19119:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19120:             }
                   19121:         }
                   19122:     } else {
                   19123:         if ($uselink) {
                   19124:             $result = 1;
                   19125:         } else {
                   19126:             $result = 0;
                   19127:         }
                   19128:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19129:     }
1.1328    raeburn  19130:     return $uselink;
                   19131: }
                   19132: 
1.1359    raeburn  19133: sub page_menu {
                   19134:     my ($menucolls,$menunum) = @_;
                   19135:     my %menu;
                   19136:     foreach my $item (split(/;/,$menucolls)) {
                   19137:         my ($num,$value) = split(/\%/,$item);
                   19138:         if ($num eq $menunum) {
                   19139:             my @entries = split(/\&/,$value);
                   19140:             foreach my $entry (@entries) {
                   19141:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19142:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19143:                     $menu{$name} = $fields;
                   19144:                 } else {
                   19145:                     my @shown;
                   19146:                     if ($fields =~ /,/) {
                   19147:                         @shown = split(/,/,$fields);
                   19148:                     } else {
                   19149:                         @shown = ($fields);
                   19150:                     }
                   19151:                     if (@shown) {
                   19152:                         foreach my $field (@shown) {
                   19153:                             next if ($field eq '');
                   19154:                             $menu{$field} = 1;
                   19155:                         }
                   19156:                     }
                   19157:                 }
                   19158:             }
                   19159:         }
                   19160:     }
                   19161:     return %menu;
                   19162: }
                   19163: 
1.112     bowersj2 19164: 1;
                   19165: __END__;
1.41      ng       19166: 

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