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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1473  ! raeburn     4: # $Id: loncommon.pm,v 1.1472 2025/03/19 15:18:59 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.1409    raeburn    74: use LONCAPA::ltiutils;
1.1280    raeburn    75: use LONCAPA::LWPReq;
1.1395    raeburn    76: use LONCAPA::map();
1.1328    raeburn    77: use HTTP::Request;
1.657     raeburn    78: use DateTime::TimeZone;
1.1241    raeburn    79: use DateTime::Locale;
1.1220    raeburn    80: use Encode();
1.1091    foxr       81: use Text::Aspell;
1.1094    raeburn    82: use Authen::Captcha;
                     83: use Captcha::reCAPTCHA;
1.1234    raeburn    84: use JSON::DWIW;
1.1174    raeburn    85: use Crypt::DES;
                     86: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   87: use MIME::Lite;
                     88: use MIME::Types;
1.1292    raeburn    89: use File::Copy();
1.1300    raeburn    90: use File::Path();
1.1309    raeburn    91: use String::CRC32();
                     92: use Short::URL();
1.117     www        93: 
1.517     raeburn    94: # ---------------------------------------------- Designs
                     95: use vars qw(%defaultdesign);
                     96: 
1.22      www        97: my $readit;
                     98: 
1.517     raeburn    99: 
1.157     matthew   100: ##
                    101: ## Global Variables
                    102: ##
1.46      matthew   103: 
1.643     foxr      104: 
                    105: # ----------------------------------------------- SSI with retries:
                    106: #
                    107: 
                    108: =pod
                    109: 
1.648     raeburn   110: =head1 Server Side include with retries:
1.643     foxr      111: 
                    112: =over 4
                    113: 
1.648     raeburn   114: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      115: 
                    116: Performs an ssi with some number of retries.  Retries continue either
                    117: until the result is ok or until the retry count supplied by the
                    118: caller is exhausted.  
                    119: 
                    120: Inputs:
1.648     raeburn   121: 
                    122: =over 4
                    123: 
1.643     foxr      124: resource   - Identifies the resource to insert.
1.648     raeburn   125: 
1.643     foxr      126: retries    - Count of the number of retries allowed.
1.648     raeburn   127: 
1.643     foxr      128: form       - Hash that identifies the rendering options.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: Returns:
                    133: 
                    134: =over 4
                    135: 
1.643     foxr      136: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   137: 
1.643     foxr      138: response   - The response from the last attempt (which may or may not have been successful.
                    139: 
1.648     raeburn   140: =back
                    141: 
                    142: =back
                    143: 
1.643     foxr      144: =cut
                    145: 
                    146: sub ssi_with_retries {
                    147:     my ($resource, $retries, %form) = @_;
                    148: 
                    149: 
                    150:     my $ok = 0;			# True if we got a good response.
                    151:     my $content;
                    152:     my $response;
                    153: 
                    154:     # Try to get the ssi done. within the retries count:
                    155: 
                    156:     do {
                    157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    158: 	$ok      = $response->is_success;
1.650     www       159:         if (!$ok) {
                    160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    161:         }
1.643     foxr      162: 	$retries--;
                    163:     } while (!$ok && ($retries > 0));
                    164: 
                    165:     if (!$ok) {
                    166: 	$content = '';		# On error return an empty content.
                    167:     }
                    168:     return ($content, $response);
                    169: 
                    170: }
                    171: 
                    172: 
                    173: 
1.20      www       174: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  175: my %language;
1.124     www       176: my %supported_language;
1.1088    foxr      177: my %supported_codes;
1.1048    foxr      178: my %latex_language;		# For choosing hyphenation in <transl..>
                    179: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  180: my %cprtag;
1.192     taceyjo1  181: my %scprtag;
1.351     www       182: my %fe; my %fd; my %fm;
1.41      ng        183: my %category_extensions;
1.12      harris41  184: 
1.46      matthew   185: # ---------------------------------------------- Thesaurus variables
1.144     matthew   186: #
                    187: # %Keywords:
                    188: #      A hash used by &keyword to determine if a word is considered a keyword.
                    189: # $thesaurus_db_file 
                    190: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   191: 
                    192: my %Keywords;
                    193: my $thesaurus_db_file;
                    194: 
1.144     matthew   195: #
                    196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    197: # thesaurus.tab, and filecategories.tab.
                    198: #
1.18      www       199: BEGIN {
1.46      matthew   200:     # Variable initialization
                    201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    202:     #
1.22      www       203:     unless ($readit) {
1.12      harris41  204: # ------------------------------------------------------------------- languages
                    205:     {
1.158     raeburn   206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    207:                                    '/language.tab';
1.1317    raeburn   208:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  209:             while (my $line = <$fh>) {
                    210:                 next if ($line=~/^\#/);
                    211:                 chomp($line);
1.1088    foxr      212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   213:                 $language{$key}=$val.' - '.$enc;
                    214:                 if ($sup) {
                    215:                     $supported_language{$key}=$sup;
1.1088    foxr      216: 		    $supported_codes{$key}   = $code;
1.158     raeburn   217:                 }
1.1048    foxr      218: 		if ($latex) {
                    219: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      220: 		    $latex_language{$code} = $latex;
1.1048    foxr      221: 		}
1.158     raeburn   222:             }
                    223:             close($fh);
                    224:         }
1.12      harris41  225:     }
                    226: # ------------------------------------------------------------------ copyrights
                    227:     {
1.158     raeburn   228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    229:                                   '/copyright.tab';
1.1317    raeburn   230:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  231:             while (my $line = <$fh>) {
                    232:                 next if ($line=~/^\#/);
                    233:                 chomp($line);
                    234:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   235:                 $cprtag{$key}=$val;
                    236:             }
                    237:             close($fh);
                    238:         }
1.12      harris41  239:     }
1.351     www       240: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  241:     {
                    242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    243:                                   '/source_copyright.tab';
1.1317    raeburn   244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  245:             while (my $line = <$fh>) {
                    246:                 next if ($line =~ /^\#/);
                    247:                 chomp($line);
                    248:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  249:                 $scprtag{$key}=$val;
                    250:             }
                    251:             close($fh);
                    252:         }
                    253:     }
1.63      www       254: 
1.517     raeburn   255: # -------------------------------------------------------------- default domain designs
1.63      www       256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   257:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   258:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   259:         while (my $line = <$fh>) {
                    260:             next if ($line =~ /^\#/);
                    261:             chomp($line);
                    262:             my ($key,$val)=(split(/\=/,$line));
                    263:             if ($val) { $defaultdesign{$key}=$val; }
                    264:         }
                    265:         close($fh);
1.63      www       266:     }
                    267: 
1.15      harris41  268: # ------------------------------------------------------------- file categories
                    269:     {
1.158     raeburn   270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    271:                                   '/filecategories.tab';
1.1317    raeburn   272:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  273: 	    while (my $line = <$fh>) {
                    274: 		next if ($line =~ /^\#/);
                    275: 		chomp($line);
                    276:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   277:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   278:             }
                    279:             close($fh);
                    280:         }
                    281: 
1.15      harris41  282:     }
1.12      harris41  283: # ------------------------------------------------------------------ file types
                    284:     {
1.158     raeburn   285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    286:                '/filetypes.tab';
1.1317    raeburn   287:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  288:             while (my $line = <$fh>) {
                    289: 		next if ($line =~ /^\#/);
                    290: 		chomp($line);
                    291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   292:                 if ($descr ne '') {
                    293:                     $fe{$ending}=lc($emb);
                    294:                     $fd{$ending}=$descr;
1.351     www       295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   296:                 }
                    297:             }
                    298:             close($fh);
                    299:         }
1.12      harris41  300:     }
1.22      www       301:     &Apache::lonnet::logthis(
1.705     tempelho  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       303:     $readit=1;
1.46      matthew   304:     }  # end of unless($readit) 
1.32      matthew   305:     
                    306: }
1.112     bowersj2  307: 
1.42      matthew   308: ###############################################################
                    309: ##           HTML and Javascript Helper Functions            ##
                    310: ###############################################################
                    311: 
                    312: =pod 
                    313: 
1.112     bowersj2  314: =head1 HTML and Javascript Functions
1.42      matthew   315: 
1.112     bowersj2  316: =over 4
                    317: 
1.648     raeburn   318: =item * &browser_and_searcher_javascript()
1.112     bowersj2  319: 
                    320: X<browsing, javascript>X<searching, javascript>Returns a string
                    321: containing javascript with two functions, C<openbrowser> and
                    322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    323: tags.
1.42      matthew   324: 
1.648     raeburn   325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   326: 
                    327: inputs: formname, elementname, only, omit
                    328: 
                    329: formname and elementname indicate the name of the html form and name of
                    330: the element that the results of the browsing selection are to be placed in. 
                    331: 
                    332: Specifying 'only' will restrict the browser to displaying only files
1.185     www       333: with the given extension.  Can be a comma separated list.
1.42      matthew   334: 
                    335: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       336: with the given extension.  Can be a comma separated list.
1.42      matthew   337: 
1.648     raeburn   338: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   339: 
                    340: Inputs: formname, elementname
                    341: 
                    342: formname and elementname specify the name of the html form and the name
                    343: of the element the selection from the search results will be placed in.
1.542     raeburn   344: 
1.42      matthew   345: =cut
                    346: 
                    347: sub browser_and_searcher_javascript {
1.199     albertel  348:     my ($mode)=@_;
                    349:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  350:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   351:     return <<END;
1.219     albertel  352: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   353:     var editbrowser = null;
1.135     albertel  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       355:         var url = '$resurl/?';
1.42      matthew   356:         if (editbrowser == null) {
                    357:             url += 'launch=1&';
                    358:         }
                    359:         url += 'catalogmode=interactive&';
1.199     albertel  360:         url += 'mode=$mode&';
1.611     albertel  361:         url += 'inhibitmenu=yes&';
1.42      matthew   362:         url += 'form=' + formname + '&';
                    363:         if (only != null) {
                    364:             url += 'only=' + only + '&';
1.217     albertel  365:         } else {
                    366:             url += 'only=&';
                    367: 	}
1.42      matthew   368:         if (omit != null) {
                    369:             url += 'omit=' + omit + '&';
1.217     albertel  370:         } else {
                    371:             url += 'omit=&';
                    372: 	}
1.135     albertel  373:         if (titleelement != null) {
                    374:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  375:         } else {
                    376: 	    url += 'titleelement=&';
                    377: 	}
1.42      matthew   378:         url += 'element=' + elementname + '';
                    379:         var title = 'Browser';
1.435     albertel  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   381:         options += ',width=700,height=600';
                    382:         editbrowser = open(url,title,options,'1');
                    383:         editbrowser.focus();
                    384:     }
                    385:     var editsearcher;
1.135     albertel  386:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   387:         var url = '/adm/searchcat?';
                    388:         if (editsearcher == null) {
                    389:             url += 'launch=1&';
                    390:         }
                    391:         url += 'catalogmode=interactive&';
1.199     albertel  392:         url += 'mode=$mode&';
1.42      matthew   393:         url += 'form=' + formname + '&';
1.135     albertel  394:         if (titleelement != null) {
                    395:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  396:         } else {
                    397: 	    url += 'titleelement=&';
                    398: 	}
1.42      matthew   399:         url += 'element=' + elementname + '';
                    400:         var title = 'Search';
1.435     albertel  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   402:         options += ',width=700,height=600';
                    403:         editsearcher = open(url,title,options,'1');
                    404:         editsearcher.focus();
                    405:     }
1.219     albertel  406: // END LON-CAPA Internal -->
1.42      matthew   407: END
1.170     www       408: }
                    409: 
                    410: sub lastresurl {
1.258     albertel  411:     if ($env{'environment.lastresurl'}) {
                    412: 	return $env{'environment.lastresurl'}
1.170     www       413:     } else {
                    414: 	return '/res';
                    415:     }
                    416: }
                    417: 
                    418: sub storeresurl {
                    419:     my $resurl=&Apache::lonnet::clutter(shift);
                    420:     unless ($resurl=~/^\/res/) { return 0; }
                    421:     $resurl=~s/\/$//;
                    422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       424:     return 1;
1.42      matthew   425: }
                    426: 
1.74      www       427: sub studentbrowser_javascript {
1.111     www       428:    unless (
1.258     albertel  429:             (($env{'request.course.id'}) && 
1.302     albertel  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    432: 					  '/'.$env{'request.course.sec'})
                    433: 	      ))
1.258     albertel  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       435:           ) { return ''; }  
1.74      www       436:    return (<<'ENDSTDBRW');
1.776     bisitz    437: <script type="text/javascript" language="Javascript">
1.824     bisitz    438: // <![CDATA[
1.74      www       439:     var stdeditbrowser;
1.1413    raeburn   440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       441:         var url = '/adm/pickstudent?';
                    442:         var filter;
1.558     albertel  443: 	if (!ignorefilter) {
                    444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    445: 	}
1.74      www       446:         if (filter != null) {
                    447:            if (filter != '') {
                    448:                url += 'filter='+filter+'&';
                    449: 	   }
                    450:         }
                    451:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       452:                                     '&udomelement='+udom+
                    453:                                     '&clicker='+clicker;
1.111     www       454: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   455:         if (courseadv == 'condition') {
                    456:             if (document.getElementById('courseadv')) {
                    457:                 courseadv = document.getElementById('courseadv').value;
                    458:             }
                    459:         }
                    460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1413    raeburn   461:         if (uident !== '') { url+="&identelement="+uident; } 
1.102     www       462:         var title = 'Student_Browser';
1.74      www       463:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    464:         options += ',width=700,height=600';
                    465:         stdeditbrowser = open(url,title,options,'1');
                    466:         stdeditbrowser.focus();
                    467:     }
1.824     bisitz    468: // ]]>
1.74      www       469: </script>
                    470: ENDSTDBRW
                    471: }
1.42      matthew   472: 
1.1003    www       473: sub resourcebrowser_javascript {
                    474:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       475:    return (<<'ENDRESBRW');
1.1003    www       476: <script type="text/javascript" language="Javascript">
                    477: // <![CDATA[
                    478:     var reseditbrowser;
1.1004    www       479:     function openresbrowser(formname,reslink) {
1.1005    www       480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       481:         var title = 'Resource_Browser';
                    482:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       483:         options += ',width=700,height=500';
1.1004    www       484:         reseditbrowser = open(url,title,options,'1');
                    485:         reseditbrowser.focus();
1.1003    www       486:     }
                    487: // ]]>
                    488: </script>
1.1004    www       489: ENDRESBRW
1.1003    www       490: }
                    491: 
1.74      www       492: sub selectstudent_link {
1.1413    raeburn   493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  497:    if ($env{'request.course.id'}) {  
1.302     albertel  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    500: 					'/'.$env{'request.course.sec'})) {
1.111     www       501: 	   return '';
                    502:        }
1.999     www       503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   504:        if ($courseadv eq 'only') {
                    505:            $callargs .= ",'',1,'$courseadv'";
                    506:        } elsif ($courseadv eq 'none') {
                    507:            $callargs .= ",'','','$courseadv'";
                    508:        } elsif ($courseadv eq 'condition') {
                    509:            $callargs .= ",'','','$courseadv'";
1.1413    raeburn   510:        } elsif ($identelem ne '') {
                    511:            $callargs .= ",'','',''";
                    512:        }
                    513:        if ($identelem ne '') {
                    514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   515:        }
                    516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.74      www       519:    }
1.258     albertel  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       521:        $callargs .= ",'',1"; 
1.793     raeburn   522:        return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    524:               &mt('Select User').'</a></span>';
1.111     www       525:    }
                    526:    return '';
1.91      www       527: }
                    528: 
1.1004    www       529: sub selectresource_link {
                    530:    my ($form,$reslink,$arg)=@_;
                    531:    
                    532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    534:    unless ($env{'request.course.id'}) { return $arg; }
                    535:    return '<span class="LC_nobreak">'.
                    536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    537:               $arg.'</a></span>';
                    538: }
                    539: 
                    540: 
                    541: 
1.653     raeburn   542: sub authorbrowser_javascript {
                    543:     return <<"ENDAUTHORBRW";
1.776     bisitz    544: <script type="text/javascript" language="JavaScript">
1.824     bisitz    545: // <![CDATA[
1.653     raeburn   546: var stdeditbrowser;
                    547: 
                    548: function openauthorbrowser(formname,udom) {
                    549:     var url = '/adm/pickauthor?';
                    550:     url += 'form='+formname+'&roledom='+udom;
                    551:     var title = 'Author_Browser';
                    552:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    553:     options += ',width=700,height=600';
                    554:     stdeditbrowser = open(url,title,options,'1');
                    555:     stdeditbrowser.focus();
                    556: }
                    557: 
1.824     bisitz    558: // ]]>
1.653     raeburn   559: </script>
                    560: ENDAUTHORBRW
                    561: }
                    562: 
1.91      www       563: sub coursebrowser_javascript {
1.1116    raeburn   564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   565:         $credits_element,$instcode) = @_;
1.932     raeburn   566:     my $wintitle = 'Course_Browser';
1.931     raeburn   567:     if ($crstype eq 'Community') {
1.932     raeburn   568:         $wintitle = 'Community_Browser';
1.909     raeburn   569:     }
1.876     raeburn   570:     my $id_functions = &javascript_index_functions();
                    571:     my $output = '
1.776     bisitz    572: <script type="text/javascript" language="JavaScript">
1.824     bisitz    573: // <![CDATA[
1.468     raeburn   574:     var stdeditbrowser;'."\n";
1.876     raeburn   575: 
                    576:     $output .= <<"ENDSTDBRW";
1.909     raeburn   577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       578:         var url = '/adm/pickcourse?';
1.895     raeburn   579:         var formid = getFormIdByName(formname);
1.876     raeburn   580:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  581:         if (domainfilter != null) {
                    582:            if (domainfilter != '') {
                    583:                url += 'domainfilter='+domainfilter+'&';
                    584: 	   }
                    585:         }
1.91      www       586:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  587: 	                            '&cdomelement='+udom+
                    588:                                     '&cnameelement='+desc;
1.468     raeburn   589:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   590:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   591:                 url += '&roleelement='+extra_element;
                    592:                 if (domainfilter == null || domainfilter == '') {
                    593:                     url += '&domainfilter='+extra_element;
                    594:                 }
1.234     raeburn   595:             }
1.468     raeburn   596:             else {
                    597:                 if (formname == 'portform') {
                    598:                     url += '&setroles='+extra_element;
1.800     raeburn   599:                 } else {
                    600:                     if (formname == 'rules') {
                    601:                         url += '&fixeddom='+extra_element; 
                    602:                     }
1.468     raeburn   603:                 }
                    604:             }     
1.230     raeburn   605:         }
1.909     raeburn   606:         if (type != null && type != '') {
                    607:             url += '&type='+type;
                    608:         }
                    609:         if (type_elem != null && type_elem != '') {
                    610:             url += '&typeelement='+type_elem;
                    611:         }
1.872     raeburn   612:         if (formname == 'ccrs') {
                    613:             var ownername = document.forms[formid].ccuname.value;
                    614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   615:             url += '&cloner='+ownername+':'+ownerdom;
                    616:             if (type == 'Course') {
                    617:                 url += '&crscode='+document.forms[formid].crscode.value;
                    618:             }
1.1221    raeburn   619:         }
                    620:         if (formname == 'requestcrs') {
                    621:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   622:         }
1.293     raeburn   623:         if (multflag !=null && multflag != '') {
                    624:             url += '&multiple='+multflag;
                    625:         }
1.909     raeburn   626:         var title = '$wintitle';
1.91      www       627:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    628:         options += ',width=700,height=600';
                    629:         stdeditbrowser = open(url,title,options,'1');
                    630:         stdeditbrowser.focus();
                    631:     }
1.876     raeburn   632: $id_functions
                    633: ENDSTDBRW
1.1116    raeburn   634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    636:                                       $credits_element);
1.876     raeburn   637:     }
                    638:     $output .= '
                    639: // ]]>
                    640: </script>';
                    641:     return $output;
                    642: }
                    643: 
                    644: sub javascript_index_functions {
                    645:     return <<"ENDJS";
                    646: 
                    647: function getFormIdByName(formname) {
                    648:     for (var i=0;i<document.forms.length;i++) {
                    649:         if (document.forms[i].name == formname) {
                    650:             return i;
                    651:         }
                    652:     }
                    653:     return -1;
                    654: }
                    655: 
                    656: function getIndexByName(formid,item) {
                    657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    658:         if (document.forms[formid].elements[i].name == item) {
                    659:             return i;
                    660:         }
                    661:     }
                    662:     return -1;
                    663: }
1.468     raeburn   664: 
1.876     raeburn   665: function getDomainFromSelectbox(formname,udom) {
                    666:     var userdom;
                    667:     var formid = getFormIdByName(formname);
                    668:     if (formid > -1) {
                    669:         var domid = getIndexByName(formid,udom);
                    670:         if (domid > -1) {
                    671:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    673:             }
                    674:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    675:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   676:             }
                    677:         }
                    678:     }
1.876     raeburn   679:     return userdom;
                    680: }
                    681: 
                    682: ENDJS
1.468     raeburn   683: 
1.876     raeburn   684: }
                    685: 
1.1017    raeburn   686: sub javascript_array_indexof {
1.1018    raeburn   687:     return <<ENDJS;
1.1017    raeburn   688: <script type="text/javascript" language="JavaScript">
                    689: // <![CDATA[
                    690: 
                    691: if (!Array.prototype.indexOf) {
                    692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    693:         "use strict";
                    694:         if (this === void 0 || this === null) {
                    695:             throw new TypeError();
                    696:         }
                    697:         var t = Object(this);
                    698:         var len = t.length >>> 0;
                    699:         if (len === 0) {
                    700:             return -1;
                    701:         }
                    702:         var n = 0;
                    703:         if (arguments.length > 0) {
                    704:             n = Number(arguments[1]);
1.1088    foxr      705:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   706:                 n = 0;
                    707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    709:             }
                    710:         }
                    711:         if (n >= len) {
                    712:             return -1;
                    713:         }
                    714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    715:         for (; k < len; k++) {
                    716:             if (k in t && t[k] === searchElement) {
                    717:                 return k;
                    718:             }
                    719:         }
                    720:         return -1;
                    721:     }
                    722: }
                    723: 
                    724: // ]]>
                    725: </script>
                    726: 
                    727: ENDJS
                    728: 
                    729: }
                    730: 
1.876     raeburn   731: sub userbrowser_javascript {
                    732:     my $id_functions = &javascript_index_functions();
                    733:     return <<"ENDUSERBRW";
                    734: 
1.888     raeburn   735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   736:     var url = '/adm/pickuser?';
                    737:     var userdom = getDomainFromSelectbox(formname,udom);
                    738:     if (userdom != null) {
                    739:        if (userdom != '') {
                    740:            url += 'srchdom='+userdom+'&';
                    741:        }
                    742:     }
                    743:     url += 'form=' + formname + '&unameelement='+uname+
                    744:                                 '&udomelement='+udom+
                    745:                                 '&ulastelement='+ulast+
                    746:                                 '&ufirstelement='+ufirst+
                    747:                                 '&uemailelement='+uemail+
1.881     raeburn   748:                                 '&hideudomelement='+hideudom+
                    749:                                 '&coursedom='+crsdom;
1.888     raeburn   750:     if ((caller != null) && (caller != undefined)) {
                    751:         url += '&caller='+caller;
                    752:     }
1.876     raeburn   753:     var title = 'User_Browser';
                    754:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    755:     options += ',width=700,height=600';
                    756:     var stdeditbrowser = open(url,title,options,'1');
                    757:     stdeditbrowser.focus();
                    758: }
                    759: 
1.888     raeburn   760: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   761:     var formid = getFormIdByName(formname);
                    762:     if (formid > -1) {
1.888     raeburn   763:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   764:         var domid = getIndexByName(formid,udom);
                    765:         var hidedomid = getIndexByName(formid,origdom);
                    766:         if (hidedomid > -1) {
                    767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   768:             var unameval = document.forms[formid].elements[unameid].value;
                    769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    770:                 if (domid > -1) {
                    771:                     var slct = document.forms[formid].elements[domid];
                    772:                     if (slct.type == 'select-one') {
                    773:                         var i;
                    774:                         for (i=0;i<slct.length;i++) {
                    775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    776:                         }
                    777:                     }
                    778:                     if (slct.type == 'hidden') {
                    779:                         slct.value = fixeddom;
1.876     raeburn   780:                     }
                    781:                 }
1.468     raeburn   782:             }
                    783:         }
                    784:     }
1.876     raeburn   785:     return;
                    786: }
                    787: 
                    788: $id_functions
                    789: ENDUSERBRW
1.468     raeburn   790: }
                    791: 
                    792: sub setsec_javascript {
1.1116    raeburn   793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    795:         $communityrolestr);
                    796:     if ($role_element ne '') {
                    797:         my @allroles = ('st','ta','ep','in','ad');
                    798:         foreach my $crstype ('Course','Community') {
                    799:             if ($crstype eq 'Community') {
                    800:                 foreach my $role (@allroles) {
                    801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    802:                 }
                    803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    804:             } else {
                    805:                 foreach my $role (@allroles) {
                    806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    807:                 }
                    808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    809:             }
                    810:         }
                    811:         $rolestr = '"'.join('","',@allroles).'"';
                    812:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    814:     }
1.468     raeburn   815:     my $setsections = qq|
                    816: function setSect(sectionlist) {
1.629     raeburn   817:     var sectionsArray = new Array();
                    818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    819:         sectionsArray = sectionlist.split(",");
                    820:     }
1.468     raeburn   821:     var numSections = sectionsArray.length;
                    822:     document.$formname.$sec_element.length = 0;
                    823:     if (numSections == 0) {
                    824:         document.$formname.$sec_element.multiple=false;
                    825:         document.$formname.$sec_element.size=1;
                    826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    827:     } else {
                    828:         if (numSections == 1) {
                    829:             document.$formname.$sec_element.multiple=false;
                    830:             document.$formname.$sec_element.size=1;
                    831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    834:         } else {
                    835:             for (var i=0; i<numSections; i++) {
                    836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    837:             }
                    838:             document.$formname.$sec_element.multiple=true
                    839:             if (numSections < 3) {
                    840:                 document.$formname.$sec_element.size=numSections;
                    841:             } else {
                    842:                 document.$formname.$sec_element.size=3;
                    843:             }
                    844:             document.$formname.$sec_element.options[0].selected = false
                    845:         }
                    846:     }
1.91      www       847: }
1.905     raeburn   848: 
                    849: function setRole(crstype) {
1.468     raeburn   850: |;
1.905     raeburn   851:     if ($role_element eq '') {
                    852:         $setsections .= '    return;
                    853: }
                    854: ';
                    855:     } else {
                    856:         $setsections .= qq|
                    857:     var elementLength = document.$formname.$role_element.length;
                    858:     var allroles = Array($rolestr);
                    859:     var courserolenames = Array($courserolestr);
                    860:     var communityrolenames = Array($communityrolestr);
                    861:     if (elementLength != undefined) {
                    862:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    863:             if (crstype == 'Course') {
                    864:                 return;
                    865:             } else {
                    866:                 allroles[5] = 'co';
                    867:                 for (var i=0; i<6; i++) {
                    868:                     document.$formname.$role_element.options[i].value = allroles[i];
                    869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    870:                 }
                    871:             }
                    872:         } else {
                    873:             if (crstype == 'Community') {
                    874:                 return;
                    875:             } else {
                    876:                 allroles[5] = 'cc';
                    877:                 for (var i=0; i<6; i++) {
                    878:                     document.$formname.$role_element.options[i].value = allroles[i];
                    879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    880:                 }
                    881:             }
                    882:         }
                    883:     }
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.1116    raeburn   888:     if ($credits_element) {
                    889:         $setsections .= qq|
                    890: function setCredits(defaultcredits) {
                    891:     document.$formname.$credits_element.value = defaultcredits;
                    892:     return;
                    893: }
                    894: |;
                    895:     }
1.468     raeburn   896:     return $setsections;
                    897: }
                    898: 
1.91      www       899: sub selectcourse_link {
1.909     raeburn   900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    901:        $typeelement) = @_;
                    902:    my $type = $selecttype;
1.871     raeburn   903:    my $linktext = &mt('Select Course');
                    904:    if ($selecttype eq 'Community') {
1.909     raeburn   905:        $linktext = &mt('Select Community');
1.1239    raeburn   906:    } elsif ($selecttype eq 'Placement') {
                    907:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   908:    } elsif ($selecttype eq 'Course/Community') {
                    909:        $linktext = &mt('Select Course/Community');
1.909     raeburn   910:        $type = '';
1.1019    raeburn   911:    } elsif ($selecttype eq 'Select') {
                    912:        $linktext = &mt('Select');
                    913:        $type = '';
1.871     raeburn   914:    }
1.787     bisitz    915:    return '<span class="LC_nobreak">'
                    916:          ."<a href='"
                    917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   920:          ."'>".$linktext.'</a>'
1.787     bisitz    921:          .'</span>';
1.74      www       922: }
1.42      matthew   923: 
1.653     raeburn   924: sub selectauthor_link {
                    925:    my ($form,$udom)=@_;
                    926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    927:           &mt('Select Author').'</a>';
                    928: }
                    929: 
1.876     raeburn   930: sub selectuser_link {
1.881     raeburn   931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   932:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   935:            ');">'.$linktext.'</a>';
1.876     raeburn   936: }
                    937: 
1.273     raeburn   938: sub check_uncheck_jscript {
                    939:     my $jscript = <<"ENDSCRT";
                    940: function checkAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   943:             if (!field[i].disabled) { 
                    944:                 field[i].checked = true;
                    945:             }
1.273     raeburn   946:         }
                    947:     } else {
1.1093    raeburn   948:         if (!field.disabled) { 
                    949:             field.checked = true;
                    950:         }
1.273     raeburn   951:     }
                    952: }
                    953:  
                    954: function uncheckAll(field) {
                    955:     if (field.length > 0) {
                    956:         for (i = 0; i < field.length; i++) {
                    957:             field[i].checked = false ;
1.543     albertel  958:         }
                    959:     } else {
1.273     raeburn   960:         field.checked = false ;
                    961:     }
                    962: }
                    963: ENDSCRT
                    964:     return $jscript;
                    965: }
                    966: 
1.656     www       967: sub select_timezone {
1.1387    raeburn   968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
1.1469    raeburn   969:    my $labeltext = &HTML::Entities::encode(&mt('Select Time Zone'));
                    970:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.
                    971:               ' aria-label="'.$labeltext.'">'."\n";
1.659     raeburn   972:    if ($includeempty) {
                    973:        $output .= '<option value=""';
                    974:        if (($selected eq '') || ($selected eq 'local')) {
                    975:            $output .= ' selected="selected" ';
                    976:        }
                    977:        $output .= '> </option>';
                    978:    }
1.657     raeburn   979:    my @timezones = DateTime::TimeZone->all_names;
                    980:    foreach my $tzone (@timezones) {
                    981:        $output.= '<option value="'.$tzone.'"';
                    982:        if ($tzone eq $selected) {
                    983:            $output.=' selected="selected"';
                    984:        }
                    985:        $output.=">$tzone</option>\n";
1.656     www       986:    }
                    987:    $output.="</select>";
                    988:    return $output;
                    989: }
1.273     raeburn   990: 
1.687     raeburn   991: sub select_datelocale {
1.1256    raeburn   992:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    993:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   994:     if ($includeempty) {
                    995:         $output .= '<option value=""';
                    996:         if ($selected eq '') {
                    997:             $output .= ' selected="selected" ';
                    998:         }
                    999:         $output .= '> </option>';
                   1000:     }
1.1241    raeburn  1001:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn  1002:     my (@possibles,%locale_names);
1.1241    raeburn  1003:     my @locales = DateTime::Locale->ids();
                   1004:     foreach my $id (@locales) {
                   1005:         if ($id ne '') {
                   1006:             my ($en_terr,$native_terr);
                   1007:             my $loc = DateTime::Locale->load($id);
                   1008:             if (ref($loc)) {
                   1009:                 $en_terr = $loc->name();
                   1010:                 $native_terr = $loc->native_name();
1.687     raeburn  1011:                 if (grep(/^en$/,@languages) || !@languages) {
                   1012:                     if ($en_terr ne '') {
                   1013:                         $locale_names{$id} = '('.$en_terr.')';
                   1014:                     } elsif ($native_terr ne '') {
                   1015:                         $locale_names{$id} = $native_terr;
                   1016:                     }
                   1017:                 } else {
                   1018:                     if ($native_terr ne '') {
                   1019:                         $locale_names{$id} = $native_terr.' ';
                   1020:                     } elsif ($en_terr ne '') {
                   1021:                         $locale_names{$id} = '('.$en_terr.')';
                   1022:                     }
                   1023:                 }
1.1220    raeburn  1024:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1025:                 push(@possibles,$id);
                   1026:             } 
1.687     raeburn  1027:         }
                   1028:     }
                   1029:     foreach my $item (sort(@possibles)) {
                   1030:         $output.= '<option value="'.$item.'"';
                   1031:         if ($item eq $selected) {
                   1032:             $output.=' selected="selected"';
                   1033:         }
                   1034:         $output.=">$item";
                   1035:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1036:             $output.='  '.$locale_names{$item};
1.687     raeburn  1037:         }
                   1038:         $output.="</option>\n";
                   1039:     }
                   1040:     $output.="</select>";
                   1041:     return $output;
                   1042: }
                   1043: 
1.792     raeburn  1044: sub select_language {
1.1256    raeburn  1045:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1046:     my %langchoices;
                   1047:     if ($includeempty) {
1.1117    raeburn  1048:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1049:     }
                   1050:     foreach my $id (&languageids()) {
                   1051:         my $code = &supportedlanguagecode($id);
                   1052:         if ($code) {
                   1053:             $langchoices{$code} = &plainlanguagedescription($id);
                   1054:         }
                   1055:     }
1.1117    raeburn  1056:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1057:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1058: }
                   1059: 
1.42      matthew  1060: =pod
1.36      matthew  1061: 
1.1088    foxr     1062: 
                   1063: =item * &list_languages()
                   1064: 
                   1065: Returns an array reference that is suitable for use in language prompters.
                   1066: Each array element is itself a two element array.  The first element
                   1067: is the language code.  The second element a descsriptiuon of the 
                   1068: language itself.  This is suitable for use in e.g.
                   1069: &Apache::edit::select_arg (once dereferenced that is).
                   1070: 
                   1071: =cut 
                   1072: 
                   1073: sub list_languages {
                   1074:     my @lang_choices;
                   1075: 
                   1076:     foreach my $id (&languageids()) {
                   1077: 	my $code = &supportedlanguagecode($id);
                   1078: 	if ($code) {
                   1079: 	    my $selector    = $supported_codes{$id};
                   1080: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1081: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1082: 	}
                   1083:     }
                   1084:     return \@lang_choices;
                   1085: }
                   1086: 
                   1087: =pod
                   1088: 
1.648     raeburn  1089: =item * &linked_select_forms(...)
1.36      matthew  1090: 
                   1091: linked_select_forms returns a string containing a <script></script> block
                   1092: and html for two <select> menus.  The select menus will be linked in that
                   1093: changing the value of the first menu will result in new values being placed
                   1094: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1095: order unless a defined order is provided.
1.36      matthew  1096: 
                   1097: linked_select_forms takes the following ordered inputs:
                   1098: 
                   1099: =over 4
                   1100: 
1.112     bowersj2 1101: =item * $formname, the name of the <form> tag
1.36      matthew  1102: 
1.112     bowersj2 1103: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1104: 
1.112     bowersj2 1105: =item * $firstdefault, the default value for the first menu
1.36      matthew  1106: 
1.112     bowersj2 1107: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1108: 
1.112     bowersj2 1109: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1110: 
1.112     bowersj2 1111: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1112: 
1.609     raeburn  1113: =item * $menuorder, the order of values in the first menu
                   1114: 
1.1115    raeburn  1115: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1116:         event for the first <select> tag
                   1117: 
                   1118: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1119:         event for the second <select> tag
                   1120: 
1.1245    raeburn  1121: =item * $suffix, to differentiate separate uses of select2data javascript
                   1122:         objects in a page.
                   1123: 
1.41      ng       1124: =back 
                   1125: 
1.36      matthew  1126: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1127: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1128: values for the first select menu.  The text that coincides with the 
1.41      ng       1129: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1130: and text for the second menu are given in the hash pointed to by 
                   1131: $menu{$choice1}->{'select2'}.  
                   1132: 
1.112     bowersj2 1133:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1134:                        default => "B3",
                   1135:                        select2 => { 
                   1136:                            B1 => "Choice B1",
                   1137:                            B2 => "Choice B2",
                   1138:                            B3 => "Choice B3",
                   1139:                            B4 => "Choice B4"
1.609     raeburn  1140:                            },
                   1141:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1142:                    },
                   1143:                A2 => { text =>"Choice A2" ,
                   1144:                        default => "C2",
                   1145:                        select2 => { 
                   1146:                            C1 => "Choice C1",
                   1147:                            C2 => "Choice C2",
                   1148:                            C3 => "Choice C3"
1.609     raeburn  1149:                            },
                   1150:                        order => ['C2','C1','C3'],
1.112     bowersj2 1151:                    },
                   1152:                A3 => { text =>"Choice A3" ,
                   1153:                        default => "D6",
                   1154:                        select2 => { 
                   1155:                            D1 => "Choice D1",
                   1156:                            D2 => "Choice D2",
                   1157:                            D3 => "Choice D3",
                   1158:                            D4 => "Choice D4",
                   1159:                            D5 => "Choice D5",
                   1160:                            D6 => "Choice D6",
                   1161:                            D7 => "Choice D7"
1.609     raeburn  1162:                            },
                   1163:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1164:                    }
                   1165:                );
1.36      matthew  1166: 
                   1167: =cut
                   1168: 
                   1169: sub linked_select_forms {
                   1170:     my ($formname,
                   1171:         $middletext,
                   1172:         $firstdefault,
                   1173:         $firstselectname,
                   1174:         $secondselectname, 
1.609     raeburn  1175:         $hashref,
                   1176:         $menuorder,
1.1115    raeburn  1177:         $onchangefirst,
1.1245    raeburn  1178:         $onchangesecond,
1.1450    raeburn  1179:         $suffix,
                   1180:         $haslabel
1.36      matthew  1181:         ) = @_;
                   1182:     my $second = "document.$formname.$secondselectname";
                   1183:     my $first = "document.$formname.$firstselectname";
                   1184:     # output the javascript to do the changing
                   1185:     my $result = '';
1.776     bisitz   1186:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1187:     $result.="// <![CDATA[\n";
1.1245    raeburn  1188:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1189:     $" = '","';
                   1190:     my $debug = '';
                   1191:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1192:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1193:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1194:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1195:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1196:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1197:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1198:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1199:         }
1.36      matthew  1200:         $result.="\"@s2values\");\n";
1.1245    raeburn  1201:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1202:         my @s2texts;
                   1203:         foreach my $value (@s2values) {
1.1263    raeburn  1204:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1205:         }
                   1206:         $result.="\"@s2texts\");\n";
                   1207:     }
                   1208:     $"=' ';
                   1209:     $result.= <<"END";
                   1210: 
1.1245    raeburn  1211: function select1${suffix}_changed() {
1.36      matthew  1212:     // Determine new choice
1.1245    raeburn  1213:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1214:     // update select2
1.1245    raeburn  1215:     var values     = select2data${suffix}[newvalue].values;
                   1216:     var texts      = select2data${suffix}[newvalue].texts;
                   1217:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1218:     var i;
                   1219:     // out with the old
1.1245    raeburn  1220:     $second.options.length = 0;
                   1221:     // in with the new
1.36      matthew  1222:     for (i=0;i<values.length; i++) {
                   1223:         $second.options[i] = new Option(values[i]);
1.143     matthew  1224:         $second.options[i].value = values[i];
1.36      matthew  1225:         $second.options[i].text = texts[i];
                   1226:         if (values[i] == select2def) {
                   1227:             $second.options[i].selected = true;
                   1228:         }
                   1229:     }
                   1230: }
1.824     bisitz   1231: // ]]>
1.36      matthew  1232: </script>
                   1233: END
                   1234:     # output the initial values for the selection lists
1.1245    raeburn  1235:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1236:     my @order = sort(keys(%{$hashref}));
                   1237:     if (ref($menuorder) eq 'ARRAY') {
                   1238:         @order = @{$menuorder};
                   1239:     }
                   1240:     foreach my $value (@order) {
1.36      matthew  1241:         $result.="    <option value=\"$value\" ";
1.253     albertel 1242:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1243:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1244:     }
                   1245:     $result .= "</select>\n";
1.1450    raeburn  1246:     if ($haslabel) {
                   1247:         $result .= '</label>';
                   1248:     }
1.1400    raeburn  1249:     my %select2;
                   1250:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1251:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1252:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1253:         }
                   1254:     }
1.1450    raeburn  1255:     if ($middletext ne '') {
1.1452    raeburn  1256:         $result .= '<label>'.$middletext;
1.1450    raeburn  1257:     }
1.1115    raeburn  1258:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1259:     if ($onchangesecond) {
                   1260:         $result .= ' onchange="'.$onchangesecond.'"';
                   1261:     }
                   1262:     $result .= ">\n";
1.36      matthew  1263:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1264:     
                   1265:     my @secondorder = sort(keys(%select2));
                   1266:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1267:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1268:     }
                   1269:     foreach my $value (@secondorder) {
1.36      matthew  1270:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1271:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1272:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1273:     }
                   1274:     $result .= "</select>\n";
1.1450    raeburn  1275:     if ($middletext ne '') {
                   1276:         $result .= '</label>';
                   1277:     }
1.36      matthew  1278:     #    return $debug;
                   1279:     return $result;
                   1280: }   #  end of sub linked_select_forms {
                   1281: 
1.45      matthew  1282: =pod
1.44      bowersj2 1283: 
1.1381    raeburn  1284: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1285: 
1.112     bowersj2 1286: Returns a string corresponding to an HTML link to the given help
                   1287: $topic, where $topic corresponds to the name of a .tex file in
                   1288: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1289: spaces. 
                   1290: 
                   1291: $text will optionally be linked to the same topic, allowing you to
                   1292: link text in addition to the graphic. If you do not want to link
                   1293: text, but wish to specify one of the later parameters, pass an
                   1294: empty string. 
                   1295: 
                   1296: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1297: the link will not open a new window. If false, the link will open
                   1298: a new window using Javascript. (Default is false.) 
                   1299: 
                   1300: $width and $height are optional numerical parameters that will
                   1301: override the width and height of the popped up window, which may
1.973     raeburn  1302: be useful for certain help topics with big pictures included.
                   1303: 
                   1304: $imgid is the id of the img tag used for the help icon. This may be
                   1305: used in a javascript call to switch the image src.  See 
                   1306: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1307: 
1.1381    raeburn  1308: $links_target will optionally be set to a target (_top, _parent or _self).
                   1309: 
1.44      bowersj2 1310: =cut
                   1311: 
                   1312: sub help_open_topic {
1.1381    raeburn  1313:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1314:     $text = "" if (not defined $text);
1.44      bowersj2 1315:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1316:     $width = 500 if (not defined $width);
1.44      bowersj2 1317:     $height = 400 if (not defined $height);
                   1318:     my $filename = $topic;
                   1319:     $filename =~ s/ /_/g;
                   1320: 
1.48      bowersj2 1321:     my $template = "";
                   1322:     my $link;
1.572     banghart 1323:     
1.159     www      1324:     $topic=~s/\W/\_/g;
1.44      bowersj2 1325: 
1.572     banghart 1326:     if (!$stayOnPage) {
1.1033    www      1327: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1328:     } elsif ($stayOnPage eq 'popup') {
                   1329:         $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 1330:     } else {
1.48      bowersj2 1331: 	$link = "/adm/help/${filename}.hlp";
                   1332:     }
                   1333: 
                   1334:     # Add the text
1.1314    raeburn  1335:     my $target = ' target="_top"';
1.1381    raeburn  1336:     if ($links_target) {
                   1337:         $target = ' target="'.$links_target.'"';
                   1338:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1339:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1340:         $target = '';
1.1378    raeburn  1341:     }
1.1380    raeburn  1342:     if ($text ne "") {
1.763     bisitz   1343: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1344:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1345:                   .$text.'</a>';
1.48      bowersj2 1346:     }
                   1347: 
1.763     bisitz   1348:     # (Always) Add the graphic
1.179     matthew  1349:     my $title = &mt('Online Help');
1.667     raeburn  1350:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1351:     if ($imgid ne '') {
                   1352:         $imgid = ' id="'.$imgid.'"';
                   1353:     }
1.1314    raeburn  1354:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1355:               .'<img src="'.$helpicon.'" border="0"'
1.1469    raeburn  1356:               .' alt="'.&mt('Help icon').'"'
1.973     raeburn  1357:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1358:               .' /></a>';
                   1359:     if ($text ne "") {	
                   1360:         $template.='</span>';
                   1361:     }
1.44      bowersj2 1362:     return $template;
                   1363: 
1.106     bowersj2 1364: }
                   1365: 
                   1366: # This is a quicky function for Latex cheatsheet editing, since it 
                   1367: # appears in at least four places
                   1368: sub helpLatexCheatsheet {
1.1037    www      1369:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1370:     my $out;
1.106     bowersj2 1371:     my $addOther = '';
1.732     raeburn  1372:     if ($topic) {
1.1037    www      1373: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1374:     }
                   1375:     $out = '<span>' # Start cheatsheet
                   1376: 	  .$addOther
                   1377:           .'<span>'
1.1037    www      1378: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1379: 	  .'</span> <span>'
1.1037    www      1380: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1381: 	  .'</span>';
1.732     raeburn  1382:     unless ($not_author) {
1.1186    kruse    1383:         $out .= '<span>'
                   1384:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1385:                .'</span> <span>'
1.1424    raeburn  1386:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.763     bisitz   1387: 	       .'</span>';
1.732     raeburn  1388:     }
1.763     bisitz   1389:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1390:     return $out;
1.172     www      1391: }
                   1392: 
1.430     albertel 1393: sub general_help {
                   1394:     my $helptopic='Student_Intro';
                   1395:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1396: 	$helptopic='Authoring_Intro';
1.907     raeburn  1397:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1398: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1399:     } elsif ($env{'request.role'}=~/^dc/) {
                   1400:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1401:     }
                   1402:     return $helptopic;
                   1403: }
                   1404: 
                   1405: sub update_help_link {
                   1406:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1407:     my $origurl = $ENV{'REQUEST_URI'};
                   1408:     $origurl=~s|^/~|/priv/|;
                   1409:     my $timestamp = time;
                   1410:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1411:         $$datum = &escape($$datum);
                   1412:     }
                   1413: 
                   1414:     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";
                   1415:     my $output .= <<"ENDOUTPUT";
                   1416: <script type="text/javascript">
1.824     bisitz   1417: // <![CDATA[
1.430     albertel 1418: banner_link = '$banner_link';
1.824     bisitz   1419: // ]]>
1.430     albertel 1420: </script>
                   1421: ENDOUTPUT
                   1422:     return $output;
                   1423: }
                   1424: 
                   1425: # now just updates the help link and generates a blue icon
1.193     raeburn  1426: sub help_open_menu {
1.1381    raeburn  1427:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1428: 	= @_;    
1.949     droeschl 1429:     $stayOnPage = 1;
1.430     albertel 1430:     my $output;
                   1431:     if ($component_help) {
                   1432: 	if (!$text) {
                   1433: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1434: 				       $width,$height,'',$links_target);
1.430     albertel 1435: 	} else {
                   1436: 	    my $help_text;
                   1437: 	    $help_text=&unescape($topic);
                   1438: 	    $output='<table><tr><td>'.
                   1439: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1440: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1441: 	}
                   1442:     }
                   1443:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1444:     return $output.$banner_link;
                   1445: }
                   1446: 
                   1447: sub top_nav_help {
1.1369    raeburn  1448:     my ($text,$linkattr) = @_;
1.436     albertel 1449:     $text = &mt($text);
1.949     droeschl 1450:     my $stay_on_page = 1;
                   1451: 
1.1168    raeburn  1452:     my ($link,$banner_link);
                   1453:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1454:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1455: 	                         : "javascript:helpMenu('open')";
                   1456:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1457:     }
1.201     raeburn  1458:     my $title = &mt('Get help');
1.1168    raeburn  1459:     if ($link) {
                   1460:         return <<"END";
1.436     albertel 1461: $banner_link
1.1369    raeburn  1462: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1463: END
1.1168    raeburn  1464:     } else {
1.1459    raeburn  1465:         return '&nbsp;<h1 class="LC_helpmenu">'.$text.'</h1>&nbsp;';
1.1168    raeburn  1466:     }
1.436     albertel 1467: }
                   1468: 
                   1469: sub help_menu_js {
1.1154    raeburn  1470:     my ($httphost) = @_;
1.949     droeschl 1471:     my $stayOnPage = 1;
1.436     albertel 1472:     my $width = 620;
                   1473:     my $height = 600;
1.430     albertel 1474:     my $helptopic=&general_help();
1.1154    raeburn  1475:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1476:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.1459    raeburn  1477:     my $bannertitle = &mt('Help Menu');
                   1478:     &js_escape(\$bannertitle);
                   1479:     my $bodytitle = &mt('Documentation');
                   1480:     &js_escape(\$bodytitle);
1.331     albertel 1481:     my $start_page =
                   1482:         &Apache::loncommon::start_page('Help Menu', undef,
                   1483: 				       {'frameset'    => 1,
                   1484: 					'js_ready'    => 1,
1.1154    raeburn  1485:                                         'use_absolute' => $httphost,
1.331     albertel 1486: 					'add_entries' => {
1.1168    raeburn  1487: 					    'border' => '0', 
1.579     raeburn  1488: 					    'rows'   => "110,*",},});
1.331     albertel 1489:     my $end_page =
                   1490:         &Apache::loncommon::end_page({'frameset' => 1,
                   1491: 				      'js_ready' => 1,});
1.436     albertel 1492:     my $template .= <<"ENDTEMPLATE";
                   1493: <script type="text/javascript">
1.877     bisitz   1494: // <![CDATA[
1.253     albertel 1495: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1496: var banner_link = '';
1.243     raeburn  1497: function helpMenu(target) {
                   1498:     var caller = this;
                   1499:     if (target == 'open') {
                   1500:         var newWindow = null;
                   1501:         try {
1.262     albertel 1502:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1503:         }
                   1504:         catch(error) {
                   1505:             writeHelp(caller);
                   1506:             return;
                   1507:         }
                   1508:         if (newWindow) {
                   1509:             caller = newWindow;
                   1510:         }
1.193     raeburn  1511:     }
1.243     raeburn  1512:     writeHelp(caller);
                   1513:     return;
                   1514: }
                   1515: function writeHelp(caller) {
1.1459    raeburn  1516:     caller.document.writeln('$start_page\\n<frame name="bannerframe" title="$bannertitle" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1517:     caller.document.writeln('<frame name="bodyframe" title="$bodytitle" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1.1168    raeburn  1518:     caller.document.close();
                   1519:     caller.focus();
1.193     raeburn  1520: }
1.877     bisitz   1521: // END LON-CAPA Internal -->
1.253     albertel 1522: // ]]>
1.436     albertel 1523: </script>
1.193     raeburn  1524: ENDTEMPLATE
                   1525:     return $template;
                   1526: }
                   1527: 
1.172     www      1528: sub help_open_bug {
                   1529:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1530:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1531:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1532:     $text = "" if (not defined $text);
                   1533: 	$stayOnPage=1;
1.184     albertel 1534:     $width = 600 if (not defined $width);
                   1535:     $height = 600 if (not defined $height);
1.172     www      1536: 
                   1537:     $topic=~s/\W+/\+/g;
                   1538:     my $link='';
                   1539:     my $template='';
1.379     albertel 1540:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1541: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1542:     if (!$stayOnPage)
                   1543:     {
                   1544: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1545:     }
                   1546:     else
                   1547:     {
                   1548: 	$link = $url;
                   1549:     }
1.1314    raeburn  1550: 
1.1382    raeburn  1551:     my $target = '_top';
                   1552:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1553:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1554:         $target = '_blank';
1.1378    raeburn  1555:     }
1.1382    raeburn  1556: 
1.172     www      1557:     # Add the text
                   1558:     if ($text ne "")
                   1559:     {
                   1560: 	$template .= 
                   1561:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1562:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1563:     }
                   1564: 
                   1565:     # Add the graphic
1.179     matthew  1566:     my $title = &mt('Report a Bug');
1.215     albertel 1567:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1568:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1569:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1570: ENDTEMPLATE
                   1571:     if ($text ne '') { $template.='</td></tr></table>' };
                   1572:     return $template;
                   1573: 
                   1574: }
                   1575: 
                   1576: sub help_open_faq {
                   1577:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1578:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1579:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1580:     $text = "" if (not defined $text);
                   1581: 	$stayOnPage=1;
                   1582:     $width = 350 if (not defined $width);
                   1583:     $height = 400 if (not defined $height);
                   1584: 
                   1585:     $topic=~s/\W+/\+/g;
                   1586:     my $link='';
                   1587:     my $template='';
                   1588:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1589:     if (!$stayOnPage)
                   1590:     {
                   1591: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1592:     }
                   1593:     else
                   1594:     {
                   1595: 	$link = $url;
                   1596:     }
                   1597: 
                   1598:     # Add the text
                   1599:     if ($text ne "")
                   1600:     {
                   1601: 	$template .= 
1.173     www      1602:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1603:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1604:     }
                   1605: 
                   1606:     # Add the graphic
1.179     matthew  1607:     my $title = &mt('View the FAQ');
1.215     albertel 1608:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1609:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1610:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1611: ENDTEMPLATE
                   1612:     if ($text ne '') { $template.='</td></tr></table>' };
                   1613:     return $template;
                   1614: 
1.44      bowersj2 1615: }
1.37      matthew  1616: 
1.180     matthew  1617: ###############################################################
                   1618: ###############################################################
                   1619: 
1.45      matthew  1620: =pod
                   1621: 
1.648     raeburn  1622: =item * &change_content_javascript():
1.256     matthew  1623: 
                   1624: This and the next function allow you to create small sections of an
                   1625: otherwise static HTML page that you can update on the fly with
                   1626: Javascript, even in Netscape 4.
                   1627: 
                   1628: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1629: must be written to the HTML page once. It will prove the Javascript
                   1630: function "change(name, content)". Calling the change function with the
                   1631: name of the section 
                   1632: you want to update, matching the name passed to C<changable_area>, and
                   1633: the new content you want to put in there, will put the content into
                   1634: that area.
                   1635: 
                   1636: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1637: to contain room for the original contents. You need to "make space"
                   1638: for whatever changes you wish to make, and be B<sure> to check your
                   1639: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1640: it's adequate for updating a one-line status display, but little more.
                   1641: This script will set the space to 100% width, so you only need to
                   1642: worry about height in Netscape 4.
                   1643: 
                   1644: Modern browsers are much less limiting, and if you can commit to the
                   1645: user not using Netscape 4, this feature may be used freely with
                   1646: pretty much any HTML.
                   1647: 
                   1648: =cut
                   1649: 
                   1650: sub change_content_javascript {
                   1651:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1652:     if ($env{'browser.type'} eq 'netscape' &&
                   1653: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1654: 	return (<<NETSCAPE4);
                   1655: 	function change(name, content) {
                   1656: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1657: 	    doc.open();
                   1658: 	    doc.write(content);
                   1659: 	    doc.close();
                   1660: 	}
                   1661: NETSCAPE4
                   1662:     } else {
                   1663: 	# Otherwise, we need to use semi-standards-compliant code
                   1664: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1665: 	# is really scary, and every useful browser supports it
                   1666: 	return (<<DOMBASED);
                   1667: 	function change(name, content) {
                   1668: 	    element = document.getElementById(name);
                   1669: 	    element.innerHTML = content;
                   1670: 	}
                   1671: DOMBASED
                   1672:     }
                   1673: }
                   1674: 
                   1675: =pod
                   1676: 
1.648     raeburn  1677: =item * &changable_area($name,$origContent):
1.256     matthew  1678: 
                   1679: This provides a "changable area" that can be modified on the fly via
                   1680: the Javascript code provided in C<change_content_javascript>. $name is
                   1681: the name you will use to reference the area later; do not repeat the
                   1682: same name on a given HTML page more then once. $origContent is what
                   1683: the area will originally contain, which can be left blank.
                   1684: 
                   1685: =cut
                   1686: 
                   1687: sub changable_area {
                   1688:     my ($name, $origContent) = @_;
                   1689: 
1.258     albertel 1690:     if ($env{'browser.type'} eq 'netscape' &&
                   1691: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1692: 	# If this is netscape 4, we need to use the Layer tag
                   1693: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1694:     } else {
                   1695: 	return "<span id='$name'>$origContent</span>";
                   1696:     }
                   1697: }
                   1698: 
                   1699: =pod
                   1700: 
1.648     raeburn  1701: =item * &viewport_geometry_js 
1.590     raeburn  1702: 
                   1703: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1704: 
                   1705: =cut
                   1706: 
                   1707: 
                   1708: sub viewport_geometry_js { 
                   1709:     return <<"GEOMETRY";
                   1710: var Geometry = {};
                   1711: function init_geometry() {
                   1712:     if (Geometry.init) { return };
                   1713:     Geometry.init=1;
                   1714:     if (window.innerHeight) {
                   1715:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1716:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1717:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1718:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1719:     }
                   1720:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1721:         Geometry.getViewportHeight =
                   1722:             function() { return document.documentElement.clientHeight; };
                   1723:         Geometry.getViewportWidth =
                   1724:             function() { return document.documentElement.clientWidth; };
                   1725: 
                   1726:         Geometry.getHorizontalScroll =
                   1727:             function() { return document.documentElement.scrollLeft; };
                   1728:         Geometry.getVerticalScroll =
                   1729:             function() { return document.documentElement.scrollTop; };
                   1730:     }
                   1731:     else if (document.body.clientHeight) {
                   1732:         Geometry.getViewportHeight =
                   1733:             function() { return document.body.clientHeight; };
                   1734:         Geometry.getViewportWidth =
                   1735:             function() { return document.body.clientWidth; };
                   1736:         Geometry.getHorizontalScroll =
                   1737:             function() { return document.body.scrollLeft; };
                   1738:         Geometry.getVerticalScroll =
                   1739:             function() { return document.body.scrollTop; };
                   1740:     }
                   1741: }
                   1742: 
                   1743: GEOMETRY
                   1744: }
                   1745: 
                   1746: =pod
                   1747: 
1.648     raeburn  1748: =item * &viewport_size_js()
1.590     raeburn  1749: 
                   1750: 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. 
                   1751: 
                   1752: =cut
                   1753: 
                   1754: sub viewport_size_js {
                   1755:     my $geometry = &viewport_geometry_js();
                   1756:     return <<"DIMS";
                   1757: 
                   1758: $geometry
                   1759: 
                   1760: function getViewportDims(width,height) {
                   1761:     init_geometry();
                   1762:     width.value = Geometry.getViewportWidth();
                   1763:     height.value = Geometry.getViewportHeight();
                   1764:     return;
                   1765: }
                   1766: 
                   1767: DIMS
                   1768: }
                   1769: 
                   1770: =pod
                   1771: 
1.648     raeburn  1772: =item * &resize_textarea_js()
1.565     albertel 1773: 
                   1774: emits the needed javascript to resize a textarea to be as big as possible
                   1775: 
                   1776: creates a function resize_textrea that takes two IDs first should be
                   1777: the id of the element to resize, second should be the id of a div that
                   1778: surrounds everything that comes after the textarea, this routine needs
                   1779: to be attached to the <body> for the onload and onresize events.
                   1780: 
                   1781: =cut
                   1782: 
                   1783: sub resize_textarea_js {
1.590     raeburn  1784:     my $geometry = &viewport_geometry_js();
1.565     albertel 1785:     return <<"RESIZE";
                   1786:     <script type="text/javascript">
1.824     bisitz   1787: // <![CDATA[
1.590     raeburn  1788: $geometry
1.565     albertel 1789: 
1.588     albertel 1790: function getX(element) {
                   1791:     var x = 0;
                   1792:     while (element) {
                   1793: 	x += element.offsetLeft;
                   1794: 	element = element.offsetParent;
                   1795:     }
                   1796:     return x;
                   1797: }
                   1798: function getY(element) {
                   1799:     var y = 0;
                   1800:     while (element) {
                   1801: 	y += element.offsetTop;
                   1802: 	element = element.offsetParent;
                   1803:     }
                   1804:     return y;
                   1805: }
                   1806: 
                   1807: 
1.565     albertel 1808: function resize_textarea(textarea_id,bottom_id) {
                   1809:     init_geometry();
                   1810:     var textarea        = document.getElementById(textarea_id);
                   1811:     //alert(textarea);
                   1812: 
1.588     albertel 1813:     var textarea_top    = getY(textarea);
1.565     albertel 1814:     var textarea_height = textarea.offsetHeight;
                   1815:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1816:     var bottom_top      = getY(bottom);
1.565     albertel 1817:     var bottom_height   = bottom.offsetHeight;
                   1818:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1819:     var fudge           = 23;
1.565     albertel 1820:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1821:     if (new_height < 300) {
                   1822: 	new_height = 300;
                   1823:     }
                   1824:     textarea.style.height=new_height+'px';
                   1825: }
1.824     bisitz   1826: // ]]>
1.565     albertel 1827: </script>
                   1828: RESIZE
                   1829: 
                   1830: }
                   1831: 
1.1205    golterma 1832: sub colorfuleditor_js {
1.1248    raeburn  1833:     my $browse_or_search;
                   1834:     my $respath;
                   1835:     my ($cnum,$cdom) = &crsauthor_url();
                   1836:     if ($cnum) {
                   1837:         $respath = "/res/$cdom/$cnum/";
                   1838:         my %js_lt = &Apache::lonlocal::texthash(
                   1839:             sunm => 'Sub-directory name',
                   1840:             save => 'Save page to make this permanent',
                   1841:         );
                   1842:         &js_escape(\%js_lt);
1.1400    raeburn  1843:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1844:         $browse_or_search = <<"END";
                   1845: 
1.1400    raeburn  1846:     $showfile_js
                   1847: 
1.1248    raeburn  1848:     function toggleChooser(form,element,titleid,only,search) {
                   1849:         var disp = 'none';
                   1850:         if (document.getElementById('chooser_'+element)) {
                   1851:             var curr = document.getElementById('chooser_'+element).style.display;
                   1852:             if (curr == 'none') {
                   1853:                 disp='inline';
                   1854:                 if (form.elements['chooser_'+element].length) {
                   1855:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1856:                         form.elements['chooser_'+element][i].checked = false;
                   1857:                     }
                   1858:                 }
                   1859:                 toggleResImport(form,element);
                   1860:             }
                   1861:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1862:             var dirsel = '';
                   1863:             var filesel = '';
                   1864:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1865:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1866:                 if (currcrsres == 'none') {
                   1867:                     dirsel = 'coursepath_'+element;
                   1868:                     var filesel = 'coursefile_'+element;
                   1869:                     var include;
                   1870:                     if (document.getElementById('crsres_include_'+element)) {
                   1871:                         include = document.getElementById('crsres_include_'+element).value;
                   1872:                     }
1.1402    raeburn  1873:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1874:                 }
                   1875:             }
                   1876:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1877:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1878:                 if (currcrsupload == 'none') {
                   1879:                     dirsel = 'crsauthorpath_'+element;
                   1880:                     filesel = '';
1.1402    raeburn  1881:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1882:                 }
                   1883:             }
1.1248    raeburn  1884:         }
                   1885:     }
                   1886: 
1.1400    raeburn  1887:     function toggleCrsFile(form,element) {
1.1248    raeburn  1888:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1889:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1890:             if (curr == 'none') {
1.1400    raeburn  1891:                 if (document.getElementById('coursepath_'+element)) {
                   1892:                     var numdirs;
                   1893:                     if (document.getElementById('coursepath_'+element).length) {
                   1894:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1895:                     }
1.1402    raeburn  1896:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1897:                         (document.getElementById('nocrsres_'+element))) {
                   1898:                         if (numdirs) {
                   1899:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1900:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1901:                         } else {
                   1902:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1903:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1904:                         }
                   1905:                     }
1.1248    raeburn  1906:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1907:                     if (numdirs > 1) {
1.1400    raeburn  1908:                         var selelem = form.elements['coursefile_'+element];
                   1909:                         var i, len = selelem.options.length -1;
                   1910:                         if (len >=0) {
                   1911:                             for (i = len; i >= 0; i--) {
                   1912:                                 selelem.remove(i);
                   1913:                             }
                   1914:                             selelem.options[0] = new Option('','');
                   1915:                         }
1.1248    raeburn  1916:                     }
                   1917:                 }
1.1400    raeburn  1918:             }
1.1248    raeburn  1919:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1920:         }
                   1921:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1922:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1923:             if (document.getElementById('uploadcrsres_'+element)) {
                   1924:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1925:             }
                   1926:         }
                   1927:         return;
                   1928:     }
                   1929: 
1.1400    raeburn  1930:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1931:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1932:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1933:         }
                   1934:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1935:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1936:             if (curr == 'none') {
1.1400    raeburn  1937:                 form.elements['newsubdir_'+element][0].checked = true;
                   1938:                 toggleNewsubdir(form,element);
                   1939:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1940:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1941:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1942:                 }
                   1943:             }
                   1944:         }
                   1945:         return;
                   1946:     }
                   1947: 
                   1948:     function toggleResImport(form,element) {
                   1949:         var choices = new Array('crsres','upload');
                   1950:         for (var i=0; i<choices.length; i++) {
                   1951:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1952:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1953:             }
                   1954:         }
                   1955:     }
                   1956: 
                   1957:     function toggleNewsubdir(form,element) {
                   1958:         var newsub = form.elements['newsubdir_'+element];
                   1959:         if (newsub) {
                   1960:             if (newsub.length) {
                   1961:                 for (var j=0; j<newsub.length; j++) {
                   1962:                     if (newsub[j].checked) {
                   1963:                         if (document.getElementById('newsubdirname_'+element)) {
                   1964:                             if (newsub[j].value == '1') {
                   1965:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1966:                                 if (document.getElementById('newsubdir_'+element)) {
                   1967:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1968:                                 }
                   1969:                             } else {
                   1970:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1971:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1972:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1973:                             }
                   1974:                         }
                   1975:                         break; 
                   1976:                     }
                   1977:                 }
                   1978:             }
                   1979:         }
                   1980:     }
                   1981: 
                   1982:     function updateCrsFile(form,element) {
                   1983:         var directory = form.elements['coursepath_'+element];
                   1984:         var filename = form.elements['coursefile_'+element];
                   1985:         var path = directory.options[directory.selectedIndex].value;
                   1986:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1987:         if (file != '') {
                   1988:             form.elements[element].value = '$respath';
                   1989:             if (path == '/') {
                   1990:                 form.elements[element].value += file;
                   1991:             } else {
                   1992:                 form.elements[element].value += path+'/'+file;
                   1993:             }
                   1994:             unClean();
                   1995:             if (document.getElementById('previewimg_'+element)) {
                   1996:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1997:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1998:             }
                   1999:             if (document.getElementById('showimg_'+element)) {
                   2000:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   2001:             }
1.1248    raeburn  2002:         }
                   2003:         toggleChooser(form,element);
                   2004:         return;
                   2005:     }
                   2006: 
                   2007:     function uploadDone(suffix,name) {
                   2008:         if (name) {
                   2009: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   2010:             unClean();
                   2011:             toggleChooser(document.forms["lonhomework"],suffix);
                   2012:         }
                   2013:     }
                   2014: 
                   2015: \$(document).ready(function(){
                   2016: 
                   2017:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2018:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2019:             var buttonId = this.id;
                   2020:             var suffix = buttonId.toString();
                   2021:             suffix = suffix.replace(/^crsupload_/,'');
                   2022:             event.preventDefault();
                   2023:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2024:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2025:             \$(this.form).submit();
                   2026:             document.lonhomework.target = '';
                   2027:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2028:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2029:             }
                   2030:             return false;
                   2031:         }
                   2032:     });
                   2033: });
                   2034: END
                   2035:     }
1.1205    golterma 2036:     return <<"COLORFULEDIT"
                   2037: <script type="text/javascript">
                   2038: // <![CDATA[>
                   2039:     function fold_box(curDepth, lastresource){
                   2040: 
                   2041:     // we need a list because there can be several blocks you need to fold in one tag
                   2042:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2043:     // but there is only one folding button per tag
                   2044:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2045: 
                   2046:         if(block.item(0).style.display == 'none'){
                   2047: 
                   2048:             foldbutton.value = '@{[&mt("Hide")]}';
                   2049:             for (i = 0; i < block.length; i++){
                   2050:                 block.item(i).style.display = '';
                   2051:             }
                   2052:         }else{
                   2053: 
                   2054:             foldbutton.value = '@{[&mt("Show")]}';
                   2055:             for (i = 0; i < block.length; i++){
                   2056:                 // block.item(i).style.visibility = 'collapse';
                   2057:                 block.item(i).style.display = 'none';
                   2058:             }
                   2059:         };
                   2060:         saveState(lastresource);
                   2061:     }
                   2062: 
                   2063:     function saveState (lastresource) {
                   2064: 
                   2065:         var tag_list = getTagList();
                   2066:         if(tag_list != null){
                   2067:             var timestamp = new Date().getTime();
                   2068:             var key = lastresource;
                   2069: 
                   2070:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2071:             // starting with timestamp
                   2072:             var value = timestamp+';';
                   2073: 
                   2074:             // building the list of key-value pairs
                   2075:             for(var i = 0; i < tag_list.length; i++){
                   2076:                 value += tag_list[i]+',';
                   2077:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2078:             }
                   2079: 
                   2080:             // only iterate whole storage if nothing to override
                   2081:             if(localStorage.getItem(key) == null){        
                   2082: 
                   2083:                 // prevent storage from growing large
                   2084:                 if(localStorage.length > 50){
                   2085:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2086:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2087:                     var oldest_key;
                   2088:                     
                   2089:                     for(var i = 1; i < localStorage.length; i++){
                   2090:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2091:                             oldest_key = localStorage.key(i);
                   2092:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2093:                         }
                   2094:                     }
                   2095:                     localStorage.removeItem(oldest_key);
                   2096:                 }
                   2097:             }
                   2098:             localStorage.setItem(key,value);
                   2099:         }
                   2100:     }
                   2101: 
                   2102:     // restore folding status of blocks (on page load)
                   2103:     function restoreState (lastresource) {
                   2104:         if(localStorage.getItem(lastresource) != null){
                   2105:             var key = lastresource;
                   2106:             var value = localStorage.getItem(key);
                   2107:             var regex_delTimestamp = /^\d+;/;
                   2108: 
                   2109:             value.replace(regex_delTimestamp, '');
                   2110: 
                   2111:             var valueArr = value.split(';');
                   2112:             var pairs;
                   2113:             var elements;
                   2114:             for (var i = 0; i < valueArr.length; i++){
                   2115:                 pairs = valueArr[i].split(',');
                   2116:                 elements = document.getElementsByName(pairs[0]);
                   2117: 
                   2118:                 for (var j = 0; j < elements.length; j++){  
                   2119:                     elements[j].style.display = pairs[1];
                   2120:                     if (pairs[1] == "none"){
                   2121:                         var regex_id = /([_\\d]+)\$/;
                   2122:                         regex_id.exec(pairs[0]);
                   2123:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2124:                     }
                   2125:                 }
                   2126:             }
                   2127:         }
                   2128:     }
                   2129: 
                   2130:     function getTagList () {
                   2131:         
                   2132:         var stringToSearch = document.lonhomework.innerHTML;
                   2133: 
                   2134:         var ret = new Array();
                   2135:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2136:         var tag_list = stringToSearch.match(regex_findBlock);
                   2137: 
                   2138:         if(tag_list != null){
                   2139:             for(var i = 0; i < tag_list.length; i++){            
                   2140:                 ret.push(tag_list[i].replace(/"/, ''));
                   2141:             }
                   2142:         }
                   2143:         return ret;
                   2144:     }
                   2145: 
                   2146:     function saveScrollPosition (resource) {
                   2147:         var tag_list = getTagList();
                   2148: 
                   2149:         // we dont always want to jump to the first block
                   2150:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2151:         if(\$(window).scrollTop() > 170){
                   2152:             if(tag_list != null){
                   2153:                 var result;
                   2154:                 for(var i = 0; i < tag_list.length; i++){
                   2155:                     if(isElementInViewport(tag_list[i])){
                   2156:                         result += tag_list[i]+';';
                   2157:                     }
                   2158:                 }
                   2159:                 sessionStorage.setItem('anchor_'+resource, result);
                   2160:             }
                   2161:         } else {
                   2162:             // we dont need to save zero, just delete the item to leave everything tidy
                   2163:             sessionStorage.removeItem('anchor_'+resource);
                   2164:         }
                   2165:     }
                   2166: 
                   2167:     function restoreScrollPosition(resource){
                   2168: 
                   2169:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2170:         if(elem != null){
                   2171:             var tag_list = elem.split(';');
                   2172:             var elem_list;
                   2173: 
                   2174:             for(var i = 0; i < tag_list.length; i++){
                   2175:                 elem_list = document.getElementsByName(tag_list[i]);
                   2176:                 
                   2177:                 if(elem_list.length > 0){
                   2178:                     elem = elem_list[0];
                   2179:                     break;
                   2180:                 }
                   2181:             }
                   2182:             elem.scrollIntoView();
                   2183:         }
                   2184:     }
                   2185: 
                   2186:     function isElementInViewport(el) {
                   2187: 
                   2188:         // change to last element instead of first
                   2189:         var elem = document.getElementsByName(el);
                   2190:         var rect = elem[0].getBoundingClientRect();
                   2191: 
                   2192:         return (
                   2193:             rect.top >= 0 &&
                   2194:             rect.left >= 0 &&
                   2195:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2196:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2197:         );
                   2198:     }
                   2199:     
                   2200:     function autosize(depth){
                   2201:         var cmInst = window['cm'+depth];
                   2202:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2203: 
                   2204:         // is fixed size, switching to dynamic
                   2205:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2206:             cmInst.setSize("","auto");
                   2207:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2208:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2209: 
                   2210:         // is dynamic size, switching to fixed
                   2211:         } else {
                   2212:             cmInst.setSize("","300px");
                   2213:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2214:             sessionStorage.removeItem("autosized_"+depth);
                   2215:         }
                   2216:     }
                   2217: 
1.1248    raeburn  2218: $browse_or_search
1.1205    golterma 2219: 
                   2220: // ]]>
                   2221: </script>
                   2222: COLORFULEDIT
                   2223: }
                   2224: 
                   2225: sub xmleditor_js {
                   2226:     return <<XMLEDIT
                   2227: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2228: <script type="text/javascript">
                   2229: // <![CDATA[>
                   2230: 
                   2231:     function saveScrollPosition (resource) {
                   2232: 
                   2233:         var scrollPos = \$(window).scrollTop();
                   2234:         sessionStorage.setItem(resource,scrollPos);
                   2235:     }
                   2236: 
                   2237:     function restoreScrollPosition(resource){
                   2238: 
                   2239:         var scrollPos = sessionStorage.getItem(resource);
                   2240:         \$(window).scrollTop(scrollPos);
                   2241:     }
                   2242: 
                   2243:     // unless internet explorer
                   2244:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2245: 
                   2246:         \$(document).ready(function() {
                   2247:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2248:         });
                   2249:     }
                   2250: 
                   2251:     // inserts text at cursor position into codemirror (xml editor only)
                   2252:     function insertText(text){
                   2253:         cm.focus();
                   2254:         var curPos = cm.getCursor();
                   2255:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2256:     }
                   2257: // ]]>
                   2258: </script>
                   2259: XMLEDIT
                   2260: }
                   2261: 
                   2262: sub insert_folding_button {
                   2263:     my $curDepth = $Apache::lonxml::curdepth;
                   2264:     my $lastresource = $env{'request.ambiguous'};
                   2265: 
                   2266:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2267:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2268: }
                   2269: 
1.1248    raeburn  2270: sub crsauthor_url {
                   2271:     my ($url) = @_;
                   2272:     if ($url eq '') {
                   2273:         $url = $ENV{'REQUEST_URI'};
                   2274:     }
                   2275:     my ($cnum,$cdom);
                   2276:     if ($env{'request.course.id'}) {
                   2277:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2278:         if ($audom ne '' && $auname ne '') {
                   2279:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2280:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2281:                 $cnum = $auname;
                   2282:                 $cdom = $audom;
                   2283:             }
                   2284:         }
                   2285:     }
                   2286:     return ($cnum,$cdom);
                   2287: }
                   2288: 
                   2289: sub import_crsauthor_form {
1.1400    raeburn  2290:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2291:     return (0) unless ($env{'request.course.id'});
                   2292:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2293:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2294:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2295:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2296:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2297:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2298: 
1.1248    raeburn  2299:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2300:         $is_home = 1;
                   2301:     }
1.1400    raeburn  2302:     $toppath = "/priv/$cdom/$cnum";
                   2303:     my $nonemptydir = 1;
                   2304:     my $js_only;
                   2305:     if ($only) {
                   2306:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2307:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2308:     }
                   2309:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2310:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2311:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2312:     my %lt = &Apache::lonlocal::texthash (
                   2313:         fnam => 'Filename',
                   2314:         dire => 'Directory',
1.1400    raeburn  2315:         se   => 'Select',
1.1248    raeburn  2316:     );
1.1450    raeburn  2317:     $output = '<label>'.$lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2318:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2319:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2320:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2321:     if ($files{'/'}) {
                   2322:         $output .= '<option value="/">/</option>'."\n";
                   2323:     }
1.1400    raeburn  2324:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2325:         next if ($key eq '/');
1.1400    raeburn  2326:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2327:     }
1.1450    raeburn  2328:     $output .= '</select></label><br /><label>'."\n".
1.1402    raeburn  2329:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2330:                '<option value="" selected="selected"></option>'."\n".
1.1450    raeburn  2331:                '</select></label>'."\n".
1.1402    raeburn  2332:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2333:     return ($numdirs,$output);
                   2334: }
                   2335: 
                   2336: sub show_crsfiles_js {
                   2337:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2338:     my $se = &js_escape(&mt('Select'));
                   2339:     my $exclude;
                   2340:     if (ref($excluderef) eq 'HASH') {
                   2341:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2342:     }
                   2343:     my $js = <<"END";
                   2344: 
                   2345: 
1.1402    raeburn  2346:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2347:         var relpath = '';
                   2348:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2349:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2350:             if (currdir == '') {
                   2351:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2352:                     selelem = form.elements[filesel];
                   2353:                     var j, numfiles = selelem.options.length -1;
                   2354:                     if (numfiles >=0) {
                   2355:                         for (j = numfiles; j >= 0; j--) {
                   2356:                             selelem.remove(j);
                   2357:                         }
                   2358:                     }
                   2359:                     if (selelem.options.length == 0) {
                   2360:                         selelem.options[selelem.options.length] = new Option('','');
                   2361:                         selelem.selectedIndex = 0;
1.1248    raeburn  2362:                     }
                   2363:                 }
1.1400    raeburn  2364:                 return;
                   2365:             } else {
                   2366:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2367:             }
                   2368:         }
1.1400    raeburn  2369:         var http = new XMLHttpRequest();
                   2370:         var url = "/adm/courseauthor";
                   2371:         var crsrole = "$env{'request.role'}";
                   2372:         var exclude = '';
                   2373:         if (exc) {
                   2374:             exclude = '$exclude';
                   2375:         }
1.1402    raeburn  2376:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2377:         http.open("POST", url, true);
                   2378:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2379:         http.onreadystatechange = function() {
                   2380:             if (http.readyState == 4 && http.status == 200) {
                   2381:                 var data = JSON.parse(http.responseText);
                   2382:                 var selelem;
                   2383:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2384:                     if (Array.isArray(data.dirs)) {
                   2385:                         selelem = form.elements[dirsel];
                   2386:                         var i, numdirs = selelem.options.length -1;
                   2387:                         if (numdirs >=0) {
                   2388:                             for (i = numdirs; i >= 0; i--) {
                   2389:                                 selelem.remove(i);
                   2390:                             }
                   2391:                         }
                   2392:                         var len = data.dirs.length;
                   2393:                         if (len) {
1.1402    raeburn  2394:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2395:                             var j;
                   2396:                             for (j = 0; j < len; j++) {
                   2397:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2398:                             }
                   2399:                             selelem.selectedIndex = 0;
                   2400:                         }
                   2401:                         if (!setfile) {
                   2402:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2403:                                 selelem = form.elements[filesel];
                   2404:                                 var j, numfiles = selelem.options.length -1;
                   2405:                                 if (numfiles >=0) {
                   2406:                                     for (j = numfiles; j >= 0; j--) {
                   2407:                                         selelem.remove(j);
                   2408:                                     }
                   2409:                                 }
                   2410:                                 if (selelem.options.length == 0) {
                   2411:                                     selelem.options[selelem.options.length] = new Option('','');
                   2412:                                     selelem.selectedIndex = 0;
                   2413:                                 }
                   2414:                             }
                   2415:                         }
                   2416:                     }
                   2417:                 }
                   2418:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2419:                     selelem = form.elements[filesel];
                   2420:                     var i, numfiles = selelem.options.length -1;
                   2421:                     if (numfiles >=0) {
                   2422:                         for (i = numfiles; i >= 0; i--) {
                   2423:                             selelem.remove(i);
                   2424:                         }
                   2425:                     }
                   2426:                     var x;
                   2427:                     for (x in data.files) {
                   2428:                         if (Array.isArray(data.files[x])) {
                   2429:                             if (data.files[x].length > 1) {
                   2430:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2431:                             }
                   2432:                             var len = data.files[x].length;
                   2433:                             if (len) {
                   2434:                                 var k;
                   2435:                                 for (k = 0; k < len; k++) {
                   2436:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2437:                                 }
                   2438:                                 selelem.selectedIndex = 0;
                   2439:                             }
                   2440:                         }
                   2441:                     }
                   2442:                     if (selelem.options.length == 0) {
                   2443:                         selelem.options[selelem.options.length] = new Option('','');
                   2444:                         selelem.selectedIndex = 0;
                   2445:                     }
1.1248    raeburn  2446:                 }
                   2447:             }
                   2448:         }
1.1400    raeburn  2449:         http.send(params);
1.1248    raeburn  2450:     }
1.1400    raeburn  2451: END
1.1248    raeburn  2452: }
                   2453: 
1.1426    raeburn  2454: sub crsauthor_rights {
                   2455:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2456:     my $sourcerights = "$path/$rightsfile";
                   2457:     my $now = time;
                   2458:     if (!-e $sourcerights) {
                   2459:         my $cid = $cdom.'_'.$cnum;
                   2460:         if (!-e "$docroot/priv/$cdom") {
                   2461:             mkdir("$docroot/priv/$cdom",0755);
                   2462:         }
                   2463:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2464:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2465:         }
                   2466:         if (open(my $fh,">$sourcerights")) {
                   2467:             print $fh <<END;
                   2468: <accessrule effect="deny" realm="" type="course" role="" />
                   2469: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2470: END
                   2471:             close($fh);
                   2472:         }
                   2473:     }
                   2474:     if (!-e "$sourcerights.meta") {
                   2475:         if (open(my $fh,">$sourcerights.meta")) {
                   2476:             my $author=$env{'environment.firstname'}.' '.
                   2477:                        $env{'environment.middlename'}.' '.
                   2478:                        $env{'environment.lastname'}.' '.
                   2479:                        $env{'environment.generation'};
                   2480:             $author =~ s/\s+$//;
                   2481:             print $fh <<"END";
                   2482: 
                   2483: <abstract></abstract>
                   2484: <author>$author</author>
                   2485: <authorspace>$cnum:$cdom</authorspace>
                   2486: <copyright>private</copyright>
                   2487: <creationdate>$now</creationdate>
                   2488: <customdistributionfile></customdistributionfile>
                   2489: <dependencies></dependencies>
                   2490: <domain>$cdom</domain>
                   2491: <highestgradelevel>0</highestgradelevel>
                   2492: <keywords></keywords>
1.1445    raeburn  2493: <language>notset</language>
1.1426    raeburn  2494: <lastrevisiondate>$now</lastrevisiondate>
                   2495: <lowestgradelevel>0</lowestgradelevel>
                   2496: <mime>rights</mime>
                   2497: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2498: <notes></notes>
                   2499: <obsolete></obsolete>
                   2500: <obsoletereplacement></obsoletereplacement>
                   2501: <owner>$cnum:$cdom</owner>
                   2502: <rule>deny:::course,allow:$cid::course</rule>
                   2503: <sourceavail></sourceavail>
                   2504: <standards></standards>
                   2505: <subject></subject>
                   2506: <title>Course Authoring Rights</title>
                   2507: END
                   2508:             close($fh);
                   2509:         }
                   2510:     }
                   2511:     return;
                   2512: }
                   2513: 
1.565     albertel 2514: =pod
                   2515: 
1.1420    raeburn  2516: =item * &iframe_wrapper_headjs()
                   2517: 
1.1425    raeburn  2518: emits javascript containing two global vars to facilitate handling of resizing
                   2519: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2520: with standard LON-CAPA menus.
                   2521: 
                   2522: =cut
                   2523: 
1.1420    raeburn  2524: #
                   2525: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2526: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2527: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2528: # do not obscure the Functions menu.
                   2529: #
                   2530: 
                   2531: sub iframe_wrapper_headjs {
                   2532:     return <<"ENDJS";
                   2533: <script type="text/javascript">
                   2534: // <![CDATA[
                   2535: var LCnotready = 0;
                   2536: var LCresizedef = 0;
                   2537: // ]]>
                   2538: </script>
                   2539: 
                   2540: ENDJS
                   2541: 
                   2542: }
                   2543: 
                   2544: =pod
                   2545: 
                   2546: =item * &iframe_wrapper_resizejs()
                   2547: 
1.1425    raeburn  2548: emits javascript used to handle resizing for a page containing
                   2549: an iframe, to ensure that the iframe does not obscure any
                   2550: standard LON-CAPA menu items.
                   2551: 
                   2552: =back
                   2553: 
                   2554: =cut
                   2555: 
1.1420    raeburn  2556: #
                   2557: # jQuery to use when iframe is in use and a page resize occurs.
                   2558: # This script will ensure that the iframe does not obscure any
                   2559: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2560: # breadcrumbs and Functions menus. Expects javascript from
                   2561: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2562: # e.g., by inclusion in second arg passed to &start_page().
                   2563: #
                   2564: 
                   2565: sub iframe_wrapper_resizejs {
                   2566:     my $offset = 5;
                   2567:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2568:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2569:         $offset = 0;
                   2570:     }
                   2571:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2572:     \$(document).ready( function() {
                   2573:         \$(window).unbind('resize').resize(function(){
                   2574:             var header = null;
                   2575:             var offset = $offset;
                   2576:             var height = 0;
                   2577:             var hdrtop = 0;
1.1421    raeburn  2578:             if (\$('div.LC_menus_content:first').length) {
                   2579:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2580:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2581:                     offset = 12;
1.1421    raeburn  2582:                 }
                   2583:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2584:                 header = \$('div.LC_head_subbox:first');
                   2585:                 offset = 9;
                   2586:             } else {
                   2587:                 if (\$('#LC_breadcrumbs').length) {
                   2588:                     header = \$('#LC_breadcrumbs');
                   2589:                 }
                   2590:             }
                   2591:             if (header != null && header.length) {
                   2592:                 height = header.height();
                   2593:                 hdrtop = header.position().top;
                   2594:             }
                   2595:             var pos = height + hdrtop + offset;
                   2596:             \$('.LC_iframecontainer').css('top', pos);
                   2597:         });
                   2598:         LCresizedef = 1;
                   2599:         if (LCnotready == 1) {
                   2600:             LCnotready = 0;
                   2601:             \$(window).trigger('resize');
                   2602:         }
                   2603:     });
                   2604:     window.onload = function(){
                   2605:          if (LCresizedef) {
                   2606:              LCnotready = 0;
                   2607:              \$(window).trigger('resize');
                   2608:          } else {
                   2609:              LCnotready = 1;
                   2610:          }
                   2611:     };
                   2612: SCRIPT
                   2613: 
                   2614: }
                   2615: 
                   2616: =pod
                   2617: 
1.256     matthew  2618: =head1 Excel and CSV file utility routines
                   2619: 
                   2620: =cut
                   2621: 
                   2622: ###############################################################
                   2623: ###############################################################
                   2624: 
                   2625: =pod
                   2626: 
1.1162    raeburn  2627: =over 4
                   2628: 
1.648     raeburn  2629: =item * &csv_translate($text) 
1.37      matthew  2630: 
1.185     www      2631: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2632: format.
                   2633: 
                   2634: =cut
                   2635: 
1.180     matthew  2636: ###############################################################
                   2637: ###############################################################
1.37      matthew  2638: sub csv_translate {
                   2639:     my $text = shift;
                   2640:     $text =~ s/\"/\"\"/g;
1.209     albertel 2641:     $text =~ s/\n/ /g;
1.37      matthew  2642:     return $text;
                   2643: }
1.180     matthew  2644: 
                   2645: ###############################################################
                   2646: ###############################################################
                   2647: 
                   2648: =pod
                   2649: 
1.648     raeburn  2650: =item * &define_excel_formats()
1.180     matthew  2651: 
                   2652: Define some commonly used Excel cell formats.
                   2653: 
                   2654: Currently supported formats:
                   2655: 
                   2656: =over 4
                   2657: 
                   2658: =item header
                   2659: 
                   2660: =item bold
                   2661: 
                   2662: =item h1
                   2663: 
                   2664: =item h2
                   2665: 
                   2666: =item h3
                   2667: 
1.256     matthew  2668: =item h4
                   2669: 
                   2670: =item i
                   2671: 
1.180     matthew  2672: =item date
                   2673: 
                   2674: =back
                   2675: 
                   2676: Inputs: $workbook
                   2677: 
                   2678: Returns: $format, a hash reference.
                   2679: 
1.1057    foxr     2680: 
1.180     matthew  2681: =cut
                   2682: 
                   2683: ###############################################################
                   2684: ###############################################################
                   2685: sub define_excel_formats {
                   2686:     my ($workbook) = @_;
                   2687:     my $format;
                   2688:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2689:                                                 bottom    => 1,
                   2690:                                                 align     => 'center');
                   2691:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2692:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2693:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2694:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2695:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2696:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2697:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2698:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2699:     return $format;
                   2700: }
                   2701: 
                   2702: ###############################################################
                   2703: ###############################################################
1.113     bowersj2 2704: 
                   2705: =pod
                   2706: 
1.648     raeburn  2707: =item * &create_workbook()
1.255     matthew  2708: 
                   2709: Create an Excel worksheet.  If it fails, output message on the
                   2710: request object and return undefs.
                   2711: 
                   2712: Inputs: Apache request object
                   2713: 
                   2714: Returns (undef) on failure, 
                   2715:     Excel worksheet object, scalar with filename, and formats 
                   2716:     from &Apache::loncommon::define_excel_formats on success
                   2717: 
                   2718: =cut
                   2719: 
                   2720: ###############################################################
                   2721: ###############################################################
                   2722: sub create_workbook {
                   2723:     my ($r) = @_;
                   2724:         #
                   2725:     # Create the excel spreadsheet
                   2726:     my $filename = '/prtspool/'.
1.258     albertel 2727:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2728:         time.'_'.rand(1000000000).'.xls';
                   2729:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2730:     if (! defined($workbook)) {
                   2731:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2732:         $r->print(
                   2733:             '<p class="LC_error">'
                   2734:            .&mt('Problems occurred in creating the new Excel file.')
                   2735:            .' '.&mt('This error has been logged.')
                   2736:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2737:            .'</p>'
                   2738:         );
1.255     matthew  2739:         return (undef);
                   2740:     }
                   2741:     #
1.1014    foxr     2742:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2743:     #
                   2744:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2745:     return ($workbook,$filename,$format);
                   2746: }
                   2747: 
                   2748: ###############################################################
                   2749: ###############################################################
                   2750: 
                   2751: =pod
                   2752: 
1.648     raeburn  2753: =item * &create_text_file()
1.113     bowersj2 2754: 
1.542     raeburn  2755: Create a file to write to and eventually make available to the user.
1.256     matthew  2756: If file creation fails, outputs an error message on the request object and 
                   2757: return undefs.
1.113     bowersj2 2758: 
1.256     matthew  2759: Inputs: Apache request object, and file suffix
1.113     bowersj2 2760: 
1.256     matthew  2761: Returns (undef) on failure, 
                   2762:     Filehandle and filename on success.
1.113     bowersj2 2763: 
                   2764: =cut
                   2765: 
1.256     matthew  2766: ###############################################################
                   2767: ###############################################################
                   2768: sub create_text_file {
                   2769:     my ($r,$suffix) = @_;
                   2770:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2771:     my $fh;
                   2772:     my $filename = '/prtspool/'.
1.258     albertel 2773:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2774:         time.'_'.rand(1000000000).'.'.$suffix;
                   2775:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2776:     if (! defined($fh)) {
                   2777:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2778:         $r->print(
                   2779:             '<p class="LC_error">'
                   2780:            .&mt('Problems occurred in creating the output file.')
                   2781:            .' '.&mt('This error has been logged.')
                   2782:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2783:            .'</p>'
                   2784:         );
1.113     bowersj2 2785:     }
1.256     matthew  2786:     return ($fh,$filename)
1.113     bowersj2 2787: }
                   2788: 
                   2789: 
1.256     matthew  2790: =pod 
1.113     bowersj2 2791: 
                   2792: =back
                   2793: 
                   2794: =cut
1.37      matthew  2795: 
                   2796: ###############################################################
1.33      matthew  2797: ##        Home server <option> list generating code          ##
                   2798: ###############################################################
1.35      matthew  2799: 
1.169     www      2800: # ------------------------------------------
                   2801: 
                   2802: sub domain_select {
1.1471    raeburn  2803:     my ($name,$value,$multiple,$incdoms,$excdoms,$id)=@_;
1.1289    raeburn  2804:     my @possdoms;
                   2805:     if (ref($incdoms) eq 'ARRAY') {
                   2806:         @possdoms = @{$incdoms};
                   2807:     } else {
                   2808:         @possdoms = &Apache::lonnet::all_domains();
                   2809:     }
                   2810: 
1.169     www      2811:     my %domains=map { 
1.514     albertel 2812: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2813:     } @possdoms;
                   2814: 
                   2815:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2816:         foreach my $dom (@{$excdoms}) {
                   2817:             delete($domains{$dom});
                   2818:         }
                   2819:     }
                   2820: 
1.169     www      2821:     if ($multiple) {
                   2822: 	$domains{''}=&mt('Any domain');
1.550     albertel 2823: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.1471    raeburn  2824: 	return &multiple_select_form($name,$value,4,\%domains,undef,$id);
1.169     www      2825:     } else {
1.550     albertel 2826: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.1471    raeburn  2827: 	return &select_form($name,$value,\%domains,'','',$id);
1.169     www      2828:     }
                   2829: }
                   2830: 
1.282     albertel 2831: #-------------------------------------------
                   2832: 
                   2833: =pod
                   2834: 
1.519     raeburn  2835: =head1 Routines for form select boxes
                   2836: 
                   2837: =over 4
                   2838: 
1.1471    raeburn  2839: =item * &multiple_select_form($name,$value,$size,$hash,$order,$id)
1.282     albertel 2840: 
                   2841: Returns a string containing a <select> element int multiple mode
                   2842: 
                   2843: 
                   2844: Args:
                   2845:   $name - name of the <select> element
1.506     raeburn  2846:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2847:   $size - number of rows long the select element is
1.283     albertel 2848:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2849:           (shown text should already have been &mt())
1.506     raeburn  2850:   $order - (optional) array ref of the order to show the elements in
1.1472    raeburn  2851:   $id = (optional) id for <select> element
1.283     albertel 2852: 
1.282     albertel 2853: =cut
                   2854: 
                   2855: #-------------------------------------------
1.169     www      2856: sub multiple_select_form {
1.1471    raeburn  2857:     my ($name,$value,$size,$hash,$order,$id)=@_;
1.169     www      2858:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2859:     my $output='';
1.191     matthew  2860:     if (! defined($size)) {
                   2861:         $size = 4;
1.283     albertel 2862:         if (scalar(keys(%$hash))<4) {
                   2863:             $size = scalar(keys(%$hash));
1.191     matthew  2864:         }
                   2865:     }
1.1471    raeburn  2866:     if ($id ne '') {
                   2867:         $id = ' id="'.$id.'"'; 
                   2868:     }
                   2869:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple"'.$id.'>';
1.501     banghart 2870:     my @order;
1.506     raeburn  2871:     if (ref($order) eq 'ARRAY')  {
                   2872:         @order = @{$order};
                   2873:     } else {
                   2874:         @order = sort(keys(%$hash));
1.501     banghart 2875:     }
                   2876:     if (exists($$hash{'select_form_order'})) {
                   2877:         @order = @{$$hash{'select_form_order'}};
                   2878:     }
                   2879:         
1.284     albertel 2880:     foreach my $key (@order) {
1.356     albertel 2881:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2882:         $output.='selected="selected" ' if ($selected{$key});
                   2883:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2884:     }
                   2885:     $output.="</select>\n";
                   2886:     return $output;
                   2887: }
                   2888: 
1.88      www      2889: #-------------------------------------------
                   2890: 
                   2891: =pod
                   2892: 
1.1472    raeburn  2893: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly,$id,$aria_labelledby)
1.88      www      2894: 
                   2895: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2896: allow a user to select options from a ref to a hash containing:
                   2897: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2898: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2899: An optional arg -- $readonly -- if true will cause the select form
                   2900: to be disabled, e.g., for the case where an instructor has a section-
1.1471    raeburn  2901: specific role, and is viewing/modifying parameters. An optional arg
1.1472    raeburn  2902: -- $id -- will be used as the id attribute of the select element. An
                   2903: optional arg -- $aria_labelledby -- will be included as the aria-labelledby
                   2904: attribute of the select element.
1.970     raeburn  2905: 
1.88      www      2906: See lonrights.pm for an example invocation and use.
                   2907: 
                   2908: =cut
                   2909: 
                   2910: #-------------------------------------------
                   2911: sub select_form {
1.1472    raeburn  2912:     my ($def,$name,$hashref,$onchange,$readonly,$id,$aria_labelledby) = @_;
1.970     raeburn  2913:     return unless (ref($hashref) eq 'HASH');
                   2914:     if ($onchange) {
                   2915:         $onchange = ' onchange="'.$onchange.'"';
                   2916:     }
1.1228    raeburn  2917:     my $disabled;
                   2918:     if ($readonly) {
                   2919:         $disabled = ' disabled="disabled"';
                   2920:     }
1.1471    raeburn  2921:     if ($id ne '') {
                   2922:         $id = ' id="'.$id.'"';
                   2923:     }
1.1472    raeburn  2924:     if ($aria_labelledby ne '') {
                   2925:         $aria_labelledby = ' aria-labelledby="'.$aria_labelledby.'"';
                   2926:     }
                   2927:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled$id$aria_labelledby>\n";
1.128     albertel 2928:     my @keys;
1.970     raeburn  2929:     if (exists($hashref->{'select_form_order'})) {
                   2930: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2931:     } else {
1.970     raeburn  2932: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2933:     }
1.356     albertel 2934:     foreach my $key (@keys) {
                   2935:         $selectform.=
                   2936: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2937:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2938:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2939:     }
                   2940:     $selectform.="</select>";
                   2941:     return $selectform;
                   2942: }
                   2943: 
1.475     www      2944: # For display filters
                   2945: 
                   2946: sub display_filter {
1.1074    raeburn  2947:     my ($context) = @_;
1.475     www      2948:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2949:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2950:     my $phraseinput = 'hidden';
                   2951:     my $includeinput = 'hidden';
                   2952:     my ($checked,$includetypestext);
                   2953:     if ($env{'form.displayfilter'} eq 'containing') {
                   2954:         $phraseinput = 'text'; 
                   2955:         if ($context eq 'parmslog') {
                   2956:             $includeinput = 'checkbox';
                   2957:             if ($env{'form.includetypes'}) {
                   2958:                 $checked = ' checked="checked"';
                   2959:             }
                   2960:             $includetypestext = &mt('Include parameter types');
                   2961:         }
                   2962:     } else {
                   2963:         $includetypestext = '&nbsp;';
                   2964:     }
                   2965:     my ($additional,$secondid,$thirdid);
                   2966:     if ($context eq 'parmslog') {
                   2967:         $additional = 
                   2968:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2969:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2970:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2971:             '</label>';
                   2972:         $secondid = 'includetypes';
                   2973:         $thirdid = 'includetypestext';
                   2974:     }
                   2975:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2976:                                                     '$secondid','$thirdid')";
                   2977:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1471    raeburn  2978: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'','',undef,
1.475     www      2979: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2980: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2981:            &mt('Filter: [_1]',
1.477     www      2982: 	   &select_form($env{'form.displayfilter'},
                   2983: 			'displayfilter',
1.970     raeburn  2984: 			{'currentfolder' => 'Current folder/page',
1.477     www      2985: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2986: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2987: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2988:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2989:                          '" />'.$additional;
                   2990: }
                   2991: 
                   2992: sub display_filter_js {
                   2993:     my $includetext = &mt('Include parameter types');
                   2994:     return <<"ENDJS";
                   2995:   
                   2996: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2997:     var firstType = 'hidden';
                   2998:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2999:         firstType = 'text';
                   3000:     }
                   3001:     firstObject = document.getElementById(firstid);
                   3002:     if (typeof(firstObject) == 'object') {
                   3003:         if (firstObject.type != firstType) {
                   3004:             changeInputType(firstObject,firstType);
                   3005:         }
                   3006:     }
                   3007:     if (context == 'parmslog') {
                   3008:         var secondType = 'hidden';
                   3009:         if (firstType == 'text') {
                   3010:             secondType = 'checkbox';
                   3011:         }
                   3012:         secondObject = document.getElementById(secondid);  
                   3013:         if (typeof(secondObject) == 'object') {
                   3014:             if (secondObject.type != secondType) {
                   3015:                 changeInputType(secondObject,secondType);
                   3016:             }
                   3017:         }
                   3018:         var textItem = document.getElementById(thirdid);
                   3019:         var currtext = textItem.innerHTML;
                   3020:         var newtext;
                   3021:         if (firstType == 'text') {
                   3022:             newtext = '$includetext';
                   3023:         } else {
                   3024:             newtext = '&nbsp;';
                   3025:         }
                   3026:         if (currtext != newtext) {
                   3027:             textItem.innerHTML = newtext;
                   3028:         }
                   3029:     }
                   3030:     return;
                   3031: }
                   3032: 
                   3033: function changeInputType(oldObject,newType) {
                   3034:     var newObject = document.createElement('input');
                   3035:     newObject.type = newType;
                   3036:     if (oldObject.size) {
                   3037:         newObject.size = oldObject.size;
                   3038:     }
                   3039:     if (oldObject.value) {
                   3040:         newObject.value = oldObject.value;
                   3041:     }
                   3042:     if (oldObject.name) {
                   3043:         newObject.name = oldObject.name;
                   3044:     }
                   3045:     if (oldObject.id) {
                   3046:         newObject.id = oldObject.id;
                   3047:     }
                   3048:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3049:     return;
                   3050: }
                   3051: 
                   3052: ENDJS
1.475     www      3053: }
                   3054: 
1.167     www      3055: sub gradeleveldescription {
                   3056:     my $gradelevel=shift;
                   3057:     my %gradelevels=(0 => 'Not specified',
                   3058: 		     1 => 'Grade 1',
                   3059: 		     2 => 'Grade 2',
                   3060: 		     3 => 'Grade 3',
                   3061: 		     4 => 'Grade 4',
                   3062: 		     5 => 'Grade 5',
                   3063: 		     6 => 'Grade 6',
                   3064: 		     7 => 'Grade 7',
                   3065: 		     8 => 'Grade 8',
                   3066: 		     9 => 'Grade 9',
                   3067: 		     10 => 'Grade 10',
                   3068: 		     11 => 'Grade 11',
                   3069: 		     12 => 'Grade 12',
                   3070: 		     13 => 'Grade 13',
                   3071: 		     14 => '100 Level',
                   3072: 		     15 => '200 Level',
                   3073: 		     16 => '300 Level',
                   3074: 		     17 => '400 Level',
                   3075: 		     18 => 'Graduate Level');
                   3076:     return &mt($gradelevels{$gradelevel});
                   3077: }
                   3078: 
1.163     www      3079: sub select_level_form {
1.1471    raeburn  3080:     my ($deflevel,$name,$id)=@_;
                   3081:     if ($id ne '') {
                   3082:         $id = ' id="'.$id.'"';
                   3083:     }
1.163     www      3084:     unless ($deflevel) { $deflevel=0; }
1.1471    raeburn  3085:     my $selectform = "<select name=\"$name\" size=\"1\"$id>\n";
1.167     www      3086:     for (my $i=0; $i<=18; $i++) {
                   3087:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3088:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3089:                 ">".&gradeleveldescription($i)."</option>\n";
                   3090:     }
                   3091:     $selectform.="</select>";
                   3092:     return $selectform;
1.163     www      3093: }
1.167     www      3094: 
1.35      matthew  3095: #-------------------------------------------
                   3096: 
1.45      matthew  3097: =pod
                   3098: 
1.1453    raeburn  3099: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id)
1.35      matthew  3100: 
                   3101: Returns a string containing a <select name='$name' size='1'> form to 
                   3102: allow a user to select the domain to preform an operation in.  
                   3103: See loncreateuser.pm for an example invocation and use.
                   3104: 
1.90      www      3105: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3106: selected");
                   3107: 
1.743     raeburn  3108: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3109: 
1.910     raeburn  3110: 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.
                   3111: 
1.1121    raeburn  3112: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3113: 
                   3114: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3115: 
1.1256    raeburn  3116: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3117: 
1.1453    raeburn  3118: The option $id argument is the value (if any) to set as the (unique) id attribute for the select tag.
                   3119: 
1.35      matthew  3120: =cut
                   3121: 
                   3122: #-------------------------------------------
1.34      matthew  3123: sub select_dom_form {
1.1453    raeburn  3124:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled,$id) = @_;
1.872     raeburn  3125:     if ($onchange) {
1.874     raeburn  3126:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3127:     }
1.1256    raeburn  3128:     if ($disabled) {
                   3129:         $disabled = ' disabled="disabled"';
                   3130:     }
1.1453    raeburn  3131:     if ($id ne '') {
                   3132:         $id = ' id="'.$id.'"';
                   3133:     }
1.1121    raeburn  3134:     my (@domains,%exclude);
1.910     raeburn  3135:     if (ref($incdoms) eq 'ARRAY') {
                   3136:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3137:     } else {
                   3138:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3139:     }
1.90      www      3140:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3141:     if (ref($excdoms) eq 'ARRAY') {
                   3142:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3143:     }
1.1453    raeburn  3144:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled$id>\n";
1.356     albertel 3145:     foreach my $dom (@domains) {
1.1121    raeburn  3146:         next if ($exclude{$dom});
1.356     albertel 3147:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3148:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3149:         if ($showdomdesc) {
                   3150:             if ($dom ne '') {
                   3151:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3152:                 if ($domdesc ne '') {
                   3153:                     $selectdomain .= ' ('.$domdesc.')';
                   3154:                 }
                   3155:             } 
                   3156:         }
                   3157:         $selectdomain .= "</option>\n";
1.34      matthew  3158:     }
                   3159:     $selectdomain.="</select>";
                   3160:     return $selectdomain;
                   3161: }
                   3162: 
1.35      matthew  3163: #-------------------------------------------
                   3164: 
1.45      matthew  3165: =pod
                   3166: 
1.648     raeburn  3167: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3168: 
1.586     raeburn  3169: input: 4 arguments (two required, two optional) - 
                   3170:     $domain - domain of new user
                   3171:     $name - name of form element
                   3172:     $default - Value of 'default' causes a default item to be first 
                   3173:                             option, and selected by default. 
                   3174:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3175:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3176: output: returns 2 items: 
1.586     raeburn  3177: (a) form element which contains either:
                   3178:    (i) <select name="$name">
                   3179:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3180:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3181:        </select>
                   3182:        form item if there are multiple library servers in $domain, or
                   3183:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3184:        if there is only one library server in $domain.
                   3185: 
                   3186: (b) number of library servers found.
                   3187: 
                   3188: See loncreateuser.pm for example of use.
1.35      matthew  3189: 
                   3190: =cut
                   3191: 
                   3192: #-------------------------------------------
1.586     raeburn  3193: sub home_server_form_item {
                   3194:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3195:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3196:     my $result;
                   3197:     my $numlib = keys(%servers);
                   3198:     if ($numlib > 1) {
                   3199:         $result .= '<select name="'.$name.'" />'."\n";
                   3200:         if ($default) {
1.804     bisitz   3201:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3202:                        '</option>'."\n";
                   3203:         }
                   3204:         foreach my $hostid (sort(keys(%servers))) {
                   3205:             $result.= '<option value="'.$hostid.'">'.
                   3206: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3207:         }
                   3208:         $result .= '</select>'."\n";
                   3209:     } elsif ($numlib == 1) {
                   3210:         my $hostid;
                   3211:         foreach my $item (keys(%servers)) {
                   3212:             $hostid = $item;
                   3213:         }
                   3214:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3215:                    $hostid.'" />';
                   3216:                    if (!$hide) {
                   3217:                        $result .= $hostid.' '.$servers{$hostid};
                   3218:                    }
                   3219:                    $result .= "\n";
                   3220:     } elsif ($default) {
                   3221:         $result .= '<input type="hidden" name="'.$name.
                   3222:                    '" value="default" />';
                   3223:                    if (!$hide) {
                   3224:                        $result .= &mt('default');
                   3225:                    }
                   3226:                    $result .= "\n";
1.33      matthew  3227:     }
1.586     raeburn  3228:     return ($result,$numlib);
1.33      matthew  3229: }
1.112     bowersj2 3230: 
                   3231: =pod
                   3232: 
1.534     albertel 3233: =back 
                   3234: 
1.112     bowersj2 3235: =cut
1.87      matthew  3236: 
                   3237: ###############################################################
1.112     bowersj2 3238: ##                  Decoding User Agent                      ##
1.87      matthew  3239: ###############################################################
                   3240: 
                   3241: =pod
                   3242: 
1.112     bowersj2 3243: =head1 Decoding the User Agent
                   3244: 
                   3245: =over 4
                   3246: 
                   3247: =item * &decode_user_agent()
1.87      matthew  3248: 
                   3249: Inputs: $r
                   3250: 
                   3251: Outputs:
                   3252: 
                   3253: =over 4
                   3254: 
1.112     bowersj2 3255: =item * $httpbrowser
1.87      matthew  3256: 
1.112     bowersj2 3257: =item * $clientbrowser
1.87      matthew  3258: 
1.112     bowersj2 3259: =item * $clientversion
1.87      matthew  3260: 
1.112     bowersj2 3261: =item * $clientmathml
1.87      matthew  3262: 
1.112     bowersj2 3263: =item * $clientunicode
1.87      matthew  3264: 
1.112     bowersj2 3265: =item * $clientos
1.87      matthew  3266: 
1.1137    raeburn  3267: =item * $clientmobile
                   3268: 
1.1141    raeburn  3269: =item * $clientinfo
                   3270: 
1.1194    raeburn  3271: =item * $clientosversion
                   3272: 
1.87      matthew  3273: =back
                   3274: 
1.157     matthew  3275: =back 
                   3276: 
1.87      matthew  3277: =cut
                   3278: 
                   3279: ###############################################################
                   3280: ###############################################################
                   3281: sub decode_user_agent {
1.247     albertel 3282:     my ($r)=@_;
1.87      matthew  3283:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3284:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3285:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3286:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3287:     my $clientbrowser='unknown';
                   3288:     my $clientversion='0';
                   3289:     my $clientmathml='';
                   3290:     my $clientunicode='0';
1.1137    raeburn  3291:     my $clientmobile=0;
1.1194    raeburn  3292:     my $clientosversion='';
1.87      matthew  3293:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3294:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3295: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3296: 	    $clientbrowser=$bname;
                   3297:             $httpbrowser=~/$vreg/i;
                   3298: 	    $clientversion=$1;
                   3299:             $clientmathml=($clientversion>=$minv);
                   3300:             $clientunicode=($clientversion>=$univ);
                   3301: 	}
                   3302:     }
                   3303:     my $clientos='unknown';
1.1141    raeburn  3304:     my $clientinfo;
1.87      matthew  3305:     if (($httpbrowser=~/linux/i) ||
                   3306:         ($httpbrowser=~/unix/i) ||
                   3307:         ($httpbrowser=~/ux/i) ||
                   3308:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3309:     if (($httpbrowser=~/vax/i) ||
                   3310:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3311:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3312:     if (($httpbrowser=~/mac/i) ||
                   3313:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3314:     if ($httpbrowser=~/win/i) {
                   3315:         $clientos='win';
                   3316:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3317:             $clientosversion = $1;
                   3318:         }
                   3319:     }
1.87      matthew  3320:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3321:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3322:         $clientmobile=lc($1);
                   3323:     }
1.1141    raeburn  3324:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3325:         $clientinfo = 'firefox-'.$1;
                   3326:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3327:         $clientinfo = 'chromeframe-'.$1;
                   3328:     }
1.87      matthew  3329:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3330:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3331:             $clientosversion);
1.87      matthew  3332: }
                   3333: 
1.32      matthew  3334: ###############################################################
                   3335: ##    Authentication changing form generation subroutines    ##
                   3336: ###############################################################
                   3337: ##
                   3338: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3339: ## hash, and have reasonable default values.
                   3340: ##
                   3341: ##    formname = the name given in the <form> tag.
1.35      matthew  3342: #-------------------------------------------
                   3343: 
1.45      matthew  3344: =pod
                   3345: 
1.112     bowersj2 3346: =head1 Authentication Routines
                   3347: 
                   3348: =over 4
                   3349: 
1.648     raeburn  3350: =item * &authform_xxxxxx()
1.35      matthew  3351: 
                   3352: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3353: handle some of the conveniences required for authentication forms.  
                   3354: This is not an optimal method, but it works.  
                   3355: 
                   3356: =over 4
                   3357: 
1.112     bowersj2 3358: =item * authform_header
1.35      matthew  3359: 
1.112     bowersj2 3360: =item * authform_authorwarning
1.35      matthew  3361: 
1.112     bowersj2 3362: =item * authform_nochange
1.35      matthew  3363: 
1.112     bowersj2 3364: =item * authform_kerberos
1.35      matthew  3365: 
1.112     bowersj2 3366: =item * authform_internal
1.35      matthew  3367: 
1.112     bowersj2 3368: =item * authform_filesystem
1.35      matthew  3369: 
1.1310    raeburn  3370: =item * authform_lti
                   3371: 
1.35      matthew  3372: =back
                   3373: 
1.648     raeburn  3374: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3375: 
1.35      matthew  3376: =cut
                   3377: 
                   3378: #-------------------------------------------
1.32      matthew  3379: sub authform_header{  
                   3380:     my %in = (
                   3381:         formname => 'cu',
1.80      albertel 3382:         kerb_def_dom => '',
1.32      matthew  3383:         @_,
                   3384:     );
                   3385:     $in{'formname'} = 'document.' . $in{'formname'};
                   3386:     my $result='';
1.80      albertel 3387: 
                   3388: #---------------------------------------------- Code for upper case translation
                   3389:     my $Javascript_toUpperCase;
                   3390:     unless ($in{kerb_def_dom}) {
                   3391:         $Javascript_toUpperCase =<<"END";
                   3392:         switch (choice) {
                   3393:            case 'krb': currentform.elements[choicearg].value =
                   3394:                currentform.elements[choicearg].value.toUpperCase();
                   3395:                break;
                   3396:            default:
                   3397:         }
                   3398: END
                   3399:     } else {
                   3400:         $Javascript_toUpperCase = "";
                   3401:     }
                   3402: 
1.165     raeburn  3403:     my $radioval = "'nochange'";
1.591     raeburn  3404:     if (defined($in{'curr_authtype'})) {
                   3405:         if ($in{'curr_authtype'} ne '') {
                   3406:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3407:         }
1.174     matthew  3408:     }
1.165     raeburn  3409:     my $argfield = 'null';
1.591     raeburn  3410:     if (defined($in{'mode'})) {
1.165     raeburn  3411:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3412:             if (defined($in{'curr_autharg'})) {
                   3413:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3414:                     $argfield = "'$in{'curr_autharg'}'";
                   3415:                 }
                   3416:             }
                   3417:         }
                   3418:     }
                   3419: 
1.32      matthew  3420:     $result.=<<"END";
                   3421: var current = new Object();
1.165     raeburn  3422: current.radiovalue = $radioval;
                   3423: current.argfield = $argfield;
1.32      matthew  3424: 
                   3425: function changed_radio(choice,currentform) {
                   3426:     var choicearg = choice + 'arg';
                   3427:     // If a radio button in changed, we need to change the argfield
                   3428:     if (current.radiovalue != choice) {
                   3429:         current.radiovalue = choice;
                   3430:         if (current.argfield != null) {
                   3431:             currentform.elements[current.argfield].value = '';
                   3432:         }
                   3433:         if (choice == 'nochange') {
                   3434:             current.argfield = null;
                   3435:         } else {
                   3436:             current.argfield = choicearg;
                   3437:             switch(choice) {
                   3438:                 case 'krb': 
                   3439:                     currentform.elements[current.argfield].value = 
                   3440:                         "$in{'kerb_def_dom'}";
                   3441:                 break;
                   3442:               default:
                   3443:                 break;
                   3444:             }
                   3445:         }
                   3446:     }
                   3447:     return;
                   3448: }
1.22      www      3449: 
1.32      matthew  3450: function changed_text(choice,currentform) {
                   3451:     var choicearg = choice + 'arg';
                   3452:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3453:         $Javascript_toUpperCase
1.32      matthew  3454:         // clear old field
                   3455:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3456:             currentform.elements[current.argfield].value = '';
                   3457:         }
                   3458:         current.argfield = choicearg;
                   3459:     }
                   3460:     set_auth_radio_buttons(choice,currentform);
                   3461:     return;
1.20      www      3462: }
1.32      matthew  3463: 
                   3464: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3465:     var numauthchoices = currentform.login.length;
                   3466:     if (typeof numauthchoices  == "undefined") {
                   3467:         return;
                   3468:     } 
1.32      matthew  3469:     var i=0;
1.986     raeburn  3470:     while (i < numauthchoices) {
1.32      matthew  3471:         if (currentform.login[i].value == newvalue) { break; }
                   3472:         i++;
                   3473:     }
1.986     raeburn  3474:     if (i == numauthchoices) {
1.32      matthew  3475:         return;
                   3476:     }
                   3477:     current.radiovalue = newvalue;
                   3478:     currentform.login[i].checked = true;
                   3479:     return;
                   3480: }
                   3481: END
                   3482:     return $result;
                   3483: }
                   3484: 
1.1106    raeburn  3485: sub authform_authorwarning {
1.32      matthew  3486:     my $result='';
1.144     matthew  3487:     $result='<i>'.
                   3488:         &mt('As a general rule, only authors or co-authors should be '.
                   3489:             'filesystem authenticated '.
                   3490:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3491:     return $result;
                   3492: }
                   3493: 
1.1106    raeburn  3494: sub authform_nochange {
1.32      matthew  3495:     my %in = (
                   3496:               formname => 'document.cu',
                   3497:               kerb_def_dom => 'MSU.EDU',
                   3498:               @_,
                   3499:           );
1.1106    raeburn  3500:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3501:     my $result;
1.1104    raeburn  3502:     if (!$authnum) {
1.1105    raeburn  3503:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3504:     } else {
                   3505:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3506:                   '<input type="radio" name="login" value="nochange" '.
                   3507:                   'checked="checked" onclick="'.
1.281     albertel 3508:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3509: 	    '</label>';
1.586     raeburn  3510:     }
1.32      matthew  3511:     return $result;
                   3512: }
                   3513: 
1.591     raeburn  3514: sub authform_kerberos {
1.32      matthew  3515:     my %in = (
                   3516:               formname => 'document.cu',
                   3517:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3518:               kerb_def_auth => 'krb4',
1.32      matthew  3519:               @_,
                   3520:               );
1.586     raeburn  3521:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3522:         $autharg,$jscall,$disabled);
1.1106    raeburn  3523:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3524:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3525:        $check5 = ' checked="checked"';
1.80      albertel 3526:     } else {
1.772     bisitz   3527:        $check4 = ' checked="checked"';
1.80      albertel 3528:     }
1.1259    raeburn  3529:     if ($in{'readonly'}) {
                   3530:         $disabled = ' disabled="disabled"';
                   3531:     }
1.165     raeburn  3532:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3533:     if (defined($in{'curr_authtype'})) {
                   3534:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3535:             $krbcheck = ' checked="checked"';
1.623     raeburn  3536:             if (defined($in{'mode'})) {
                   3537:                 if ($in{'mode'} eq 'modifyuser') {
                   3538:                     $krbcheck = '';
                   3539:                 }
                   3540:             }
1.591     raeburn  3541:             if (defined($in{'curr_kerb_ver'})) {
                   3542:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3543:                     $check5 = ' checked="checked"';
1.591     raeburn  3544:                     $check4 = '';
                   3545:                 } else {
1.772     bisitz   3546:                     $check4 = ' checked="checked"';
1.591     raeburn  3547:                     $check5 = '';
                   3548:                 }
1.586     raeburn  3549:             }
1.591     raeburn  3550:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3551:                 $krbarg = $in{'curr_autharg'};
                   3552:             }
1.586     raeburn  3553:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3554:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3555:                     $result = 
                   3556:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3557:         $in{'curr_autharg'},$krbver);
                   3558:                 } else {
                   3559:                     $result =
                   3560:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3561:                 }
                   3562:                 return $result; 
                   3563:             }
                   3564:         }
                   3565:     } else {
                   3566:         if ($authnum == 1) {
1.784     bisitz   3567:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3568:         }
                   3569:     }
1.586     raeburn  3570:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3571:         return;
1.587     raeburn  3572:     } elsif ($authtype eq '') {
1.591     raeburn  3573:         if (defined($in{'mode'})) {
1.587     raeburn  3574:             if ($in{'mode'} eq 'modifycourse') {
                   3575:                 if ($authnum == 1) {
1.1259    raeburn  3576:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3577:                 }
                   3578:             }
                   3579:         }
1.586     raeburn  3580:     }
                   3581:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3582:     if ($authtype eq '') {
                   3583:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3584:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3585:                     $krbcheck.$disabled.' />';
1.586     raeburn  3586:     }
                   3587:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3588:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3589:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3590:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3591:          $in{'curr_authtype'} eq 'krb4')) {
                   3592:         $result .= &mt
1.144     matthew  3593:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3594:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3595:          '<label>'.$authtype,
1.281     albertel 3596:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3597:              'value="'.$krbarg.'" '.
1.1259    raeburn  3598:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3599:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3600:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3601: 	 '</label>');
1.586     raeburn  3602:     } elsif ($can_assign{'krb4'}) {
                   3603:         $result .= &mt
                   3604:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3605:          '[_3] Version 4 [_4]',
                   3606:          '<label>'.$authtype,
                   3607:          '</label><input type="text" size="10" name="krbarg" '.
                   3608:              'value="'.$krbarg.'" '.
1.1259    raeburn  3609:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3610:          '<label><input type="hidden" name="krbver" value="4" />',
                   3611:          '</label>');
                   3612:     } elsif ($can_assign{'krb5'}) {
                   3613:         $result .= &mt
                   3614:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3615:          '[_3] Version 5 [_4]',
                   3616:          '<label>'.$authtype,
                   3617:          '</label><input type="text" size="10" name="krbarg" '.
                   3618:              'value="'.$krbarg.'" '.
1.1259    raeburn  3619:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3620:          '<label><input type="hidden" name="krbver" value="5" />',
                   3621:          '</label>');
                   3622:     }
1.32      matthew  3623:     return $result;
                   3624: }
                   3625: 
1.1106    raeburn  3626: sub authform_internal {
1.586     raeburn  3627:     my %in = (
1.32      matthew  3628:                 formname => 'document.cu',
                   3629:                 kerb_def_dom => 'MSU.EDU',
                   3630:                 @_,
                   3631:                 );
1.1259    raeburn  3632:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3633:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3634:     if ($in{'readonly'}) {
                   3635:         $disabled = ' disabled="disabled"';
                   3636:     }
1.591     raeburn  3637:     if (defined($in{'curr_authtype'})) {
                   3638:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3639:             if ($can_assign{'int'}) {
1.772     bisitz   3640:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3641:                 if (defined($in{'mode'})) {
                   3642:                     if ($in{'mode'} eq 'modifyuser') {
                   3643:                         $intcheck = '';
                   3644:                     }
                   3645:                 }
1.591     raeburn  3646:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3647:                     $intarg = $in{'curr_autharg'};
                   3648:                 }
                   3649:             } else {
                   3650:                 $result = &mt('Currently internally authenticated.');
                   3651:                 return $result;
1.165     raeburn  3652:             }
                   3653:         }
1.586     raeburn  3654:     } else {
                   3655:         if ($authnum == 1) {
1.784     bisitz   3656:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3657:         }
                   3658:     }
                   3659:     if (!$can_assign{'int'}) {
                   3660:         return;
1.587     raeburn  3661:     } elsif ($authtype eq '') {
1.591     raeburn  3662:         if (defined($in{'mode'})) {
1.587     raeburn  3663:             if ($in{'mode'} eq 'modifycourse') {
                   3664:                 if ($authnum == 1) {
1.1259    raeburn  3665:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3666:                 }
                   3667:             }
                   3668:         }
1.165     raeburn  3669:     }
1.586     raeburn  3670:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3671:     if ($authtype eq '') {
                   3672:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3673:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3674:     }
1.605     bisitz   3675:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3676:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3677:     $result = &mt
1.144     matthew  3678:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3679:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3680:     $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  3681:     return $result;
                   3682: }
                   3683: 
1.1104    raeburn  3684: sub authform_local {
1.32      matthew  3685:     my %in = (
                   3686:               formname => 'document.cu',
                   3687:               kerb_def_dom => 'MSU.EDU',
                   3688:               @_,
                   3689:               );
1.1259    raeburn  3690:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3691:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3692:     if ($in{'readonly'}) {
                   3693:         $disabled = ' disabled="disabled"';
                   3694:     } 
1.591     raeburn  3695:     if (defined($in{'curr_authtype'})) {
                   3696:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3697:             if ($can_assign{'loc'}) {
1.772     bisitz   3698:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3699:                 if (defined($in{'mode'})) {
                   3700:                     if ($in{'mode'} eq 'modifyuser') {
                   3701:                         $loccheck = '';
                   3702:                     }
                   3703:                 }
1.591     raeburn  3704:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3705:                     $locarg = $in{'curr_autharg'};
                   3706:                 }
                   3707:             } else {
                   3708:                 $result = &mt('Currently using local (institutional) authentication.');
                   3709:                 return $result;
1.165     raeburn  3710:             }
                   3711:         }
1.586     raeburn  3712:     } else {
                   3713:         if ($authnum == 1) {
1.784     bisitz   3714:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3715:         }
                   3716:     }
                   3717:     if (!$can_assign{'loc'}) {
                   3718:         return;
1.587     raeburn  3719:     } elsif ($authtype eq '') {
1.591     raeburn  3720:         if (defined($in{'mode'})) {
1.587     raeburn  3721:             if ($in{'mode'} eq 'modifycourse') {
                   3722:                 if ($authnum == 1) {
1.1259    raeburn  3723:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3724:                 }
                   3725:             }
                   3726:         }
1.165     raeburn  3727:     }
1.586     raeburn  3728:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3729:     if ($authtype eq '') {
                   3730:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3731:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3732:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3733:     }
                   3734:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3735:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3736:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3737:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3738:     return $result;
                   3739: }
                   3740: 
1.1106    raeburn  3741: sub authform_filesystem {
1.32      matthew  3742:     my %in = (
                   3743:               formname => 'document.cu',
                   3744:               kerb_def_dom => 'MSU.EDU',
                   3745:               @_,
                   3746:               );
1.1259    raeburn  3747:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3748:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3749:     if ($in{'readonly'}) {
                   3750:         $disabled = ' disabled="disabled"';
                   3751:     }
1.591     raeburn  3752:     if (defined($in{'curr_authtype'})) {
                   3753:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3754:             if ($can_assign{'fsys'}) {
1.772     bisitz   3755:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3756:                 if (defined($in{'mode'})) {
                   3757:                     if ($in{'mode'} eq 'modifyuser') {
                   3758:                         $fsyscheck = '';
                   3759:                     }
                   3760:                 }
1.586     raeburn  3761:             } else {
                   3762:                 $result = &mt('Currently Filesystem Authenticated.');
                   3763:                 return $result;
1.1259    raeburn  3764:             }
1.586     raeburn  3765:         }
                   3766:     } else {
                   3767:         if ($authnum == 1) {
1.784     bisitz   3768:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3769:         }
                   3770:     }
                   3771:     if (!$can_assign{'fsys'}) {
                   3772:         return;
1.587     raeburn  3773:     } elsif ($authtype eq '') {
1.591     raeburn  3774:         if (defined($in{'mode'})) {
1.587     raeburn  3775:             if ($in{'mode'} eq 'modifycourse') {
                   3776:                 if ($authnum == 1) {
1.1259    raeburn  3777:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3778:                 }
                   3779:             }
                   3780:         }
1.586     raeburn  3781:     }
                   3782:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3783:     if ($authtype eq '') {
                   3784:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3785:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3786:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3787:     }
1.1310    raeburn  3788:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3789:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3790:     $result = &mt
1.144     matthew  3791:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3792:          '<label>'.$authtype,'</label>'.$autharg);
                   3793:     return $result;
                   3794: }
                   3795: 
                   3796: sub authform_lti {
                   3797:     my %in = (
                   3798:               formname => 'document.cu',
                   3799:               kerb_def_dom => 'MSU.EDU',
                   3800:               @_,
                   3801:               );
                   3802:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3803:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3804:     if ($in{'readonly'}) {
                   3805:         $disabled = ' disabled="disabled"';
                   3806:     }
                   3807:     if (defined($in{'curr_authtype'})) {
                   3808:         if ($in{'curr_authtype'} eq 'lti') {
                   3809:             if ($can_assign{'lti'}) {
                   3810:                 $lticheck = 'checked="checked" ';
                   3811:                 if (defined($in{'mode'})) {
                   3812:                     if ($in{'mode'} eq 'modifyuser') {
                   3813:                         $lticheck = '';
                   3814:                     }
                   3815:                 }
                   3816:             } else {
                   3817:                 $result = &mt('Currently LTI Authenticated.');
                   3818:                 return $result;
                   3819:             }
                   3820:         }
                   3821:     } else {
                   3822:         if ($authnum == 1) {
                   3823:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3824:         }
                   3825:     }
                   3826:     if (!$can_assign{'lti'}) {
                   3827:         return;
                   3828:     } elsif ($authtype eq '') {
                   3829:         if (defined($in{'mode'})) {
                   3830:             if ($in{'mode'} eq 'modifycourse') {
                   3831:                 if ($authnum == 1) {
                   3832:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3833:                 }
                   3834:             }
                   3835:         }
                   3836:     }
                   3837:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3838:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3839:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3840:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3841:                     $jscall.'"'.$disabled.' />';
                   3842:     }
                   3843:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3844:     if ($authtype) {
                   3845:         $result = &mt('[_1] LTI Authenticated',
                   3846:                       '<label>'.$authtype.'</label>'.$autharg);
                   3847:     } else {
                   3848:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3849:                   $autharg;
                   3850:     }
1.32      matthew  3851:     return $result;
                   3852: }
                   3853: 
1.586     raeburn  3854: sub get_assignable_auth {
                   3855:     my ($dom) = @_;
                   3856:     if ($dom eq '') {
                   3857:         $dom = $env{'request.role.domain'};
                   3858:     }
                   3859:     my %can_assign = (
                   3860:                           krb4 => 1,
                   3861:                           krb5 => 1,
                   3862:                           int  => 1,
                   3863:                           loc  => 1,
1.1310    raeburn  3864:                           lti  => 1,
1.586     raeburn  3865:                      );
                   3866:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3867:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3868:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3869:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3870:             my $context;
                   3871:             if ($env{'request.role'} =~ /^au/) {
                   3872:                 $context = 'author';
1.1259    raeburn  3873:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3874:                 $context = 'domain';
                   3875:             } elsif ($env{'request.course.id'}) {
                   3876:                 $context = 'course';
                   3877:             }
                   3878:             if ($context) {
                   3879:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3880:                    %can_assign = %{$authhash->{$context}}; 
                   3881:                 }
                   3882:             }
                   3883:         }
                   3884:     }
                   3885:     my $authnum = 0;
                   3886:     foreach my $key (keys(%can_assign)) {
                   3887:         if ($can_assign{$key}) {
                   3888:             $authnum ++;
                   3889:         }
                   3890:     }
                   3891:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3892:         $authnum --;
                   3893:     }
                   3894:     return ($authnum,%can_assign);
                   3895: }
                   3896: 
1.1331    raeburn  3897: sub check_passwd_rules {
                   3898:     my ($domain,$plainpass) = @_;
                   3899:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3900:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3901:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3902:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3903:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3904:             if ($passwdconf{'min'} > $min) {
                   3905:                 $min = $passwdconf{'min'};
                   3906:             }
1.1331    raeburn  3907:         }
                   3908:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3909:             $max = $passwdconf{'max'};
                   3910:         }
                   3911:         @chars = @{$passwdconf{'chars'}};
                   3912:     }
                   3913:     if (($min) && (length($plainpass) < $min)) {
                   3914:         push(@brokerule,'min');
                   3915:     }
                   3916:     if (($max) && (length($plainpass) > $max)) {
                   3917:         push(@brokerule,'max');
                   3918:     }
                   3919:     if (@chars) {
                   3920:         my %rules;
                   3921:         map { $rules{$_} = 1; } @chars;
                   3922:         if ($rules{'uc'}) {
                   3923:             unless ($plainpass =~ /[A-Z]/) {
                   3924:                 push(@brokerule,'uc');
                   3925:             }
                   3926:         }
                   3927:         if ($rules{'lc'}) {
1.1332    raeburn  3928:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3929:                 push(@brokerule,'lc');
                   3930:             }
                   3931:         }
                   3932:         if ($rules{'num'}) {
                   3933:             unless ($plainpass =~ /\d/) {
                   3934:                 push(@brokerule,'num');
                   3935:             }
                   3936:         }
                   3937:         if ($rules{'spec'}) {
                   3938:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3939:                 push(@brokerule,'spec');
                   3940:             }
                   3941:         }
                   3942:     }
                   3943:     if (@brokerule) {
                   3944:         my %rulenames = &Apache::lonlocal::texthash(
                   3945:             uc   => 'At least one upper case letter',
                   3946:             lc   => 'At least one lower case letter',
                   3947:             num  => 'At least one number',
                   3948:             spec => 'At least one non-alphanumeric',
                   3949:         );
                   3950:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3951:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3952:         $rulenames{'num'} .= ': 0123456789';
                   3953:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3954:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3955:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3956:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3957:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3958:             if (grep(/^$rule$/,@brokerule)) {
                   3959:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3960:             }
                   3961:         }
                   3962:         $warning .= '</ul>';
                   3963:     }
1.1332    raeburn  3964:     if (wantarray) {
                   3965:         return @brokerule;
                   3966:     }
1.1331    raeburn  3967:     return $warning;
                   3968: }
                   3969: 
1.1376    raeburn  3970: sub passwd_validation_js {
1.1377    raeburn  3971:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3972:     my (%passwdconf,$alertmsg);
                   3973:     if ($context eq 'linkprot') {
                   3974:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3975:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3976:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3977:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3978:             }
                   3979:         }
                   3980:         if ($id eq 'add') {
                   3981:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3982:         } elsif ($id =~ /^\d+$/) {
                   3983:             my $pos = $id+1;
                   3984:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3985:         } else {
                   3986:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3987:         }
1.1434    raeburn  3988:     } elsif ($context eq 'ltitools') {
                   3989:         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3990:         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3991:             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3992:                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3993:             }
                   3994:         }
                   3995:         if ($id eq 'add') {
                   3996:             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3997:         } elsif ($id =~ /^\d+$/) {
                   3998:             my $pos = $id+1;
                   3999:             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   4000:         } else {
                   4001:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   4002:         }
1.1377    raeburn  4003:     } else {
                   4004:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   4005:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   4006:     }
1.1376    raeburn  4007:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   4008:     $numrules = 0;
                   4009:     $min = $Apache::lonnet::passwdmin;
                   4010:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   4011:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   4012:             if ($passwdconf{'min'} > $min) {
                   4013:                 $min = $passwdconf{'min'};
                   4014:             }
                   4015:         }
                   4016:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   4017:             $max = $passwdconf{'max'};
                   4018:             $numrules ++;
                   4019:         }
                   4020:         @chars = @{$passwdconf{'chars'}};
                   4021:         if (@chars) {
                   4022:             $numrules ++;
                   4023:         }
                   4024:     }
                   4025:     if ($min > 0) {
                   4026:         $numrules ++;
                   4027:     }
                   4028:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   4029:         if ($min) {
                   4030:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   4031:         }
                   4032:         if ($max) {
                   4033:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   4034:         }
                   4035:         my (@charalerts,@charrules);
                   4036:         if (@chars) {
                   4037:             if (grep(/^uc$/,@chars)) {
                   4038:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   4039:                 push(@charrules,'uc');
                   4040:             }
                   4041:             if (grep(/^lc$/,@chars)) {
                   4042:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   4043:                 push(@charrules,'lc');
                   4044:             }
                   4045:             if (grep(/^num$/,@chars)) {
                   4046:                 push(@charalerts,&mt('contain at least one number'));
                   4047:                 push(@charrules,'num');
                   4048:             }
                   4049:             if (grep(/^spec$/,@chars)) {
                   4050:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4051:                 push(@charrules,'spec');
                   4052:             }
                   4053:         }
                   4054:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4055:                     qq|            var currpwval = $currpasswdval;\n|;
                   4056:             if ($min) {
                   4057:                 $intargjs .= qq|
                   4058:             if (currpwval.length < $min) {
                   4059:                 rulesmsg += ' - $alert{min}';
                   4060:             }
                   4061: |;
                   4062:             }
                   4063:             if ($max) {
                   4064:                 $intargjs .= qq|
                   4065:             if (currpwval.length > $max) {
                   4066:                 rulesmsg += ' - $alert{max}';
                   4067:             }
                   4068: |;
                   4069:             }
                   4070:             if (@chars > 0) {
                   4071:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4072:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4073:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4074:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4075:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4076:                 my %rules;
                   4077:                 map { $rules{$_} = 1; } @chars;
                   4078:                 if ($rules{'uc'}) {
                   4079:                     $intargjs .= qq|
                   4080:             var ucRegExp = /[A-Z]/;
                   4081:             if (!ucRegExp.test(currpwval)) {
                   4082:                 brokerules.push('uc');
                   4083:             }
                   4084: |;
                   4085:                 }
                   4086:                 if ($rules{'lc'}) {
                   4087:                     $intargjs .= qq|
                   4088:             var lcRegExp = /[a-z]/;
                   4089:             if (!lcRegExp.test(currpwval)) {
                   4090:                 brokerules.push('lc');
                   4091:             }
                   4092: |;
                   4093:                 }
                   4094:                 if ($rules{'num'}) {
                   4095:                      $intargjs .= qq|
                   4096:             var numRegExp = /[0-9]/;
                   4097:             if (!numRegExp.test(currpwval)) {
                   4098:                 brokerules.push('num');
                   4099:             }
                   4100: |;
                   4101:                 }
                   4102:                 if ($rules{'spec'}) {
                   4103:                      $intargjs .= q|
                   4104:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4105:             if (!specRegExp.test(currpwval)) {
                   4106:                 brokerules.push('spec');
                   4107:             }
                   4108: |;
                   4109:                 }
                   4110:                 $intargjs .= qq|
                   4111:             if (brokerules.length > 0) {
                   4112:                 for (var i=0; i<brokerules.length; i++) {
                   4113:                     for (var j=0; j<charrules.length; j++) {
                   4114:                         if (brokerules[i] == charrules[j]) {
                   4115:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4116:                             break;
                   4117:                         }
                   4118:                     }
                   4119:                 }
                   4120:             }
                   4121: |;
                   4122:             }
                   4123:             $intargjs .= qq|
                   4124:             if (rulesmsg != '') {
                   4125:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4126:                 alert(rulesmsg);
                   4127:                 return false;
                   4128:             }
                   4129: |;
                   4130:     }
                   4131:     return ($numrules,$intargjs);
                   4132: }
                   4133: 
1.80      albertel 4134: ###############################################################
                   4135: ##    Get Kerberos Defaults for Domain                 ##
                   4136: ###############################################################
                   4137: ##
                   4138: ## Returns default kerberos version and an associated argument
                   4139: ## as listed in file domain.tab. If not listed, provides
                   4140: ## appropriate default domain and kerberos version.
                   4141: ##
                   4142: #-------------------------------------------
                   4143: 
                   4144: =pod
                   4145: 
1.648     raeburn  4146: =item * &get_kerberos_defaults()
1.80      albertel 4147: 
                   4148: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4149: version and domain. If not found, it defaults to version 4 and the 
                   4150: domain of the server.
1.80      albertel 4151: 
1.648     raeburn  4152: =over 4
                   4153: 
1.80      albertel 4154: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4155: 
1.648     raeburn  4156: =back
                   4157: 
                   4158: =back
                   4159: 
1.80      albertel 4160: =cut
                   4161: 
                   4162: #-------------------------------------------
                   4163: sub get_kerberos_defaults {
                   4164:     my $domain=shift;
1.641     raeburn  4165:     my ($krbdef,$krbdefdom);
                   4166:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4167:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4168:         $krbdef = $domdefaults{'auth_def'};
                   4169:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4170:     } else {
1.80      albertel 4171:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4172:         my $krbdefdom=$1;
                   4173:         $krbdefdom=~tr/a-z/A-Z/;
                   4174:         $krbdef = "krb4";
                   4175:     }
                   4176:     return ($krbdef,$krbdefdom);
                   4177: }
1.112     bowersj2 4178: 
1.32      matthew  4179: 
1.46      matthew  4180: ###############################################################
                   4181: ##                Thesaurus Functions                        ##
                   4182: ###############################################################
1.20      www      4183: 
1.46      matthew  4184: =pod
1.20      www      4185: 
1.112     bowersj2 4186: =head1 Thesaurus Functions
                   4187: 
                   4188: =over 4
                   4189: 
1.648     raeburn  4190: =item * &initialize_keywords()
1.46      matthew  4191: 
                   4192: Initializes the package variable %Keywords if it is empty.  Uses the
                   4193: package variable $thesaurus_db_file.
                   4194: 
                   4195: =cut
                   4196: 
                   4197: ###################################################
                   4198: 
                   4199: sub initialize_keywords {
                   4200:     return 1 if (scalar keys(%Keywords));
                   4201:     # If we are here, %Keywords is empty, so fill it up
                   4202:     #   Make sure the file we need exists...
                   4203:     if (! -e $thesaurus_db_file) {
                   4204:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4205:                                  " failed because it does not exist");
                   4206:         return 0;
                   4207:     }
                   4208:     #   Set up the hash as a database
                   4209:     my %thesaurus_db;
                   4210:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4211:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4212:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4213:                                  $thesaurus_db_file);
                   4214:         return 0;
                   4215:     } 
                   4216:     #  Get the average number of appearances of a word.
                   4217:     my $avecount = $thesaurus_db{'average.count'};
                   4218:     #  Put keywords (those that appear > average) into %Keywords
                   4219:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4220:         my ($count,undef) = split /:/,$data;
                   4221:         $Keywords{$word}++ if ($count > $avecount);
                   4222:     }
                   4223:     untie %thesaurus_db;
                   4224:     # Remove special values from %Keywords.
1.356     albertel 4225:     foreach my $value ('total.count','average.count') {
                   4226:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4227:   }
1.46      matthew  4228:     return 1;
                   4229: }
                   4230: 
                   4231: ###################################################
                   4232: 
                   4233: =pod
                   4234: 
1.648     raeburn  4235: =item * &keyword($word)
1.46      matthew  4236: 
                   4237: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4238: than the average number of times in the thesaurus database.  Calls 
                   4239: &initialize_keywords
                   4240: 
                   4241: =cut
                   4242: 
                   4243: ###################################################
1.20      www      4244: 
                   4245: sub keyword {
1.46      matthew  4246:     return if (!&initialize_keywords());
                   4247:     my $word=lc(shift());
                   4248:     $word=~s/\W//g;
                   4249:     return exists($Keywords{$word});
1.20      www      4250: }
1.46      matthew  4251: 
                   4252: ###############################################################
                   4253: 
                   4254: =pod 
1.20      www      4255: 
1.648     raeburn  4256: =item * &get_related_words()
1.46      matthew  4257: 
1.160     matthew  4258: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4259: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4260: will be returned.  The order of the words returned is determined by the
                   4261: database which holds them.
                   4262: 
                   4263: Uses global $thesaurus_db_file.
                   4264: 
1.1057    foxr     4265: 
1.46      matthew  4266: =cut
                   4267: 
                   4268: ###############################################################
                   4269: sub get_related_words {
                   4270:     my $keyword = shift;
                   4271:     my %thesaurus_db;
                   4272:     if (! -e $thesaurus_db_file) {
                   4273:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4274:                                  "failed because the file does not exist");
                   4275:         return ();
                   4276:     }
                   4277:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4278:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4279:         return ();
                   4280:     } 
                   4281:     my @Words=();
1.429     www      4282:     my $count=0;
1.46      matthew  4283:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4284: 	# The first element is the number of times
                   4285: 	# the word appears.  We do not need it now.
1.429     www      4286: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4287: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4288: 	my $threshold=$mostfrequentcount/10;
                   4289:         foreach my $possibleword (@RelatedWords) {
                   4290:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4291:             if ($wordcount>$threshold) {
                   4292: 		push(@Words,$word);
                   4293:                 $count++;
                   4294:                 if ($count>10) { last; }
                   4295: 	    }
1.20      www      4296:         }
                   4297:     }
1.46      matthew  4298:     untie %thesaurus_db;
                   4299:     return @Words;
1.14      harris41 4300: }
1.1090    foxr     4301: ###############################################################
                   4302: #
                   4303: #  Spell checking
                   4304: #
                   4305: 
                   4306: =pod
                   4307: 
1.1142    raeburn  4308: =back
                   4309: 
1.1090    foxr     4310: =head1 Spell checking
                   4311: 
                   4312: =over 4
                   4313: 
                   4314: =item * &check_spelling($wordlist $language)
                   4315: 
                   4316: Takes a string containing words and feeds it to an external
                   4317: spellcheck program via a pipeline. Returns a string containing
                   4318: them mis-spelled words.
                   4319: 
                   4320: Parameters:
                   4321: 
                   4322: =over 4
                   4323: 
                   4324: =item - $wordlist
                   4325: 
                   4326: String that will be fed into the spellcheck program.
                   4327: 
                   4328: =item - $language
                   4329: 
                   4330: Language string that specifies the language for which the spell
                   4331: check will be performed.
                   4332: 
                   4333: =back
                   4334: 
                   4335: =back
                   4336: 
                   4337: Note: This sub assumes that aspell is installed.
                   4338: 
                   4339: 
                   4340: =cut
                   4341: 
1.46      matthew  4342: 
1.1090    foxr     4343: sub check_spelling {
                   4344:     my ($wordlist, $language) = @_;
1.1091    foxr     4345:     my @misspellings;
                   4346:     
                   4347:     # Generate the speller and set the langauge.
                   4348:     # if explicitly selected:
1.1090    foxr     4349: 
1.1091    foxr     4350:     my $speller = Text::Aspell->new;
1.1090    foxr     4351:     if ($language) {
1.1091    foxr     4352: 	$speller->set_option('lang', $language);
1.1090    foxr     4353:     }
                   4354: 
1.1091    foxr     4355:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4356: 
1.1091    foxr     4357:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4358: 
1.1091    foxr     4359:     foreach my $word (@words) {
                   4360: 	if(! $speller->check($word)) {
                   4361: 	    push(@misspellings, $word);
1.1090    foxr     4362: 	}
                   4363:     }
1.1091    foxr     4364:     return join(' ', @misspellings);
                   4365:     
1.1090    foxr     4366: }
                   4367: 
1.61      www      4368: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4369: =pod
                   4370: 
1.112     bowersj2 4371: =head1 User Name Functions
                   4372: 
                   4373: =over 4
                   4374: 
1.648     raeburn  4375: =item * &plainname($uname,$udom,$first)
1.81      albertel 4376: 
1.112     bowersj2 4377: Takes a users logon name and returns it as a string in
1.226     albertel 4378: "first middle last generation" form 
                   4379: if $first is set to 'lastname' then it returns it as
                   4380: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4381: 
                   4382: =cut
1.61      www      4383: 
1.295     www      4384: 
1.81      albertel 4385: ###############################################################
1.61      www      4386: sub plainname {
1.226     albertel 4387:     my ($uname,$udom,$first)=@_;
1.537     albertel 4388:     return if (!defined($uname) || !defined($udom));
1.295     www      4389:     my %names=&getnames($uname,$udom);
1.226     albertel 4390:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4391: 					  $names{'middlename'},
                   4392: 					  $names{'lastname'},
                   4393: 					  $names{'generation'},$first);
                   4394:     $name=~s/^\s+//;
1.62      www      4395:     $name=~s/\s+$//;
                   4396:     $name=~s/\s+/ /g;
1.353     albertel 4397:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4398:     return $name;
1.61      www      4399: }
1.66      www      4400: 
                   4401: # -------------------------------------------------------------------- Nickname
1.81      albertel 4402: =pod
                   4403: 
1.648     raeburn  4404: =item * &nickname($uname,$udom)
1.81      albertel 4405: 
                   4406: Gets a users name and returns it as a string as
                   4407: 
                   4408: "&quot;nickname&quot;"
1.66      www      4409: 
1.81      albertel 4410: if the user has a nickname or
                   4411: 
                   4412: "first middle last generation"
                   4413: 
                   4414: if the user does not
                   4415: 
                   4416: =cut
1.66      www      4417: 
                   4418: sub nickname {
                   4419:     my ($uname,$udom)=@_;
1.537     albertel 4420:     return if (!defined($uname) || !defined($udom));
1.295     www      4421:     my %names=&getnames($uname,$udom);
1.68      albertel 4422:     my $name=$names{'nickname'};
1.66      www      4423:     if ($name) {
                   4424:        $name='&quot;'.$name.'&quot;'; 
                   4425:     } else {
                   4426:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4427: 	     $names{'lastname'}.' '.$names{'generation'};
                   4428:        $name=~s/\s+$//;
                   4429:        $name=~s/\s+/ /g;
                   4430:     }
                   4431:     return $name;
                   4432: }
                   4433: 
1.295     www      4434: sub getnames {
                   4435:     my ($uname,$udom)=@_;
1.537     albertel 4436:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4437:     if ($udom eq 'public' && $uname eq 'public') {
                   4438: 	return ('lastname' => &mt('Public'));
                   4439:     }
1.295     www      4440:     my $id=$uname.':'.$udom;
                   4441:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4442:     if ($cached) {
                   4443: 	return %{$names};
                   4444:     } else {
                   4445: 	my %loadnames=&Apache::lonnet::get('environment',
                   4446:                     ['firstname','middlename','lastname','generation','nickname'],
                   4447: 					 $udom,$uname);
                   4448: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4449: 	return %loadnames;
                   4450:     }
                   4451: }
1.61      www      4452: 
1.542     raeburn  4453: # -------------------------------------------------------------------- getemails
1.648     raeburn  4454: 
1.542     raeburn  4455: =pod
                   4456: 
1.648     raeburn  4457: =item * &getemails($uname,$udom)
1.542     raeburn  4458: 
                   4459: Gets a user's email information and returns it as a hash with keys:
                   4460: notification, critnotification, permanentemail
                   4461: 
                   4462: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4463: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4464:  
1.648     raeburn  4465: 
1.542     raeburn  4466: =cut
                   4467: 
1.648     raeburn  4468: 
1.466     albertel 4469: sub getemails {
                   4470:     my ($uname,$udom)=@_;
                   4471:     if ($udom eq 'public' && $uname eq 'public') {
                   4472: 	return;
                   4473:     }
1.467     www      4474:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4475:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4476:     my $id=$uname.':'.$udom;
                   4477:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4478:     if ($cached) {
                   4479: 	return %{$names};
                   4480:     } else {
                   4481: 	my %loadnames=&Apache::lonnet::get('environment',
                   4482:                     			   ['notification','critnotification',
                   4483: 					    'permanentemail'],
                   4484: 					   $udom,$uname);
                   4485: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4486: 	return %loadnames;
                   4487:     }
                   4488: }
                   4489: 
1.551     albertel 4490: sub flush_email_cache {
                   4491:     my ($uname,$udom)=@_;
                   4492:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4493:     if (!$uname) { $uname=$env{'user.name'};   }
                   4494:     return if ($udom eq 'public' && $uname eq 'public');
                   4495:     my $id=$uname.':'.$udom;
                   4496:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4497: }
                   4498: 
1.728     raeburn  4499: # -------------------------------------------------------------------- getlangs
                   4500: 
                   4501: =pod
                   4502: 
                   4503: =item * &getlangs($uname,$udom)
                   4504: 
                   4505: Gets a user's language preference and returns it as a hash with key:
                   4506: language.
                   4507: 
                   4508: =cut
                   4509: 
                   4510: 
                   4511: sub getlangs {
                   4512:     my ($uname,$udom) = @_;
                   4513:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4514:     if (!$uname) { $uname=$env{'user.name'};   }
                   4515:     my $id=$uname.':'.$udom;
                   4516:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4517:     if ($cached) {
                   4518:         return %{$langs};
                   4519:     } else {
                   4520:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4521:                                            $udom,$uname);
                   4522:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4523:         return %loadlangs;
                   4524:     }
                   4525: }
                   4526: 
                   4527: sub flush_langs_cache {
                   4528:     my ($uname,$udom)=@_;
                   4529:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4530:     if (!$uname) { $uname=$env{'user.name'};   }
                   4531:     return if ($udom eq 'public' && $uname eq 'public');
                   4532:     my $id=$uname.':'.$udom;
                   4533:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4534: }
                   4535: 
1.61      www      4536: # ------------------------------------------------------------------ Screenname
1.81      albertel 4537: 
                   4538: =pod
                   4539: 
1.648     raeburn  4540: =item * &screenname($uname,$udom)
1.81      albertel 4541: 
                   4542: Gets a users screenname and returns it as a string
                   4543: 
                   4544: =cut
1.61      www      4545: 
                   4546: sub screenname {
                   4547:     my ($uname,$udom)=@_;
1.258     albertel 4548:     if ($uname eq $env{'user.name'} &&
                   4549: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4550:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4551:     return $names{'screenname'};
1.62      www      4552: }
                   4553: 
1.212     albertel 4554: 
1.802     bisitz   4555: # ------------------------------------------------------------- Confirm Wrapper
                   4556: =pod
                   4557: 
1.1142    raeburn  4558: =item * &confirmwrapper($message)
1.802     bisitz   4559: 
                   4560: Wrap messages about completion of operation in box
                   4561: 
                   4562: =cut
                   4563: 
                   4564: sub confirmwrapper {
                   4565:     my ($message)=@_;
                   4566:     if ($message) {
                   4567:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4568:                .$message."\n"
                   4569:                .'</div>'."\n";
                   4570:     } else {
                   4571:         return $message;
                   4572:     }
                   4573: }
                   4574: 
1.62      www      4575: # ------------------------------------------------------------- Message Wrapper
                   4576: 
                   4577: sub messagewrapper {
1.369     www      4578:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4579:     return 
1.441     albertel 4580:         '<a href="/adm/email?compose=individual&amp;'.
                   4581:         'recname='.$username.'&amp;recdom='.$domain.
                   4582: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4583:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4584: }
1.802     bisitz   4585: 
1.74      www      4586: # --------------------------------------------------------------- Notes Wrapper
                   4587: 
                   4588: sub noteswrapper {
                   4589:     my ($link,$un,$do)=@_;
                   4590:     return 
1.896     amueller 4591: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4592: }
1.802     bisitz   4593: 
1.62      www      4594: # ------------------------------------------------------------- Aboutme Wrapper
                   4595: 
                   4596: sub aboutmewrapper {
1.1070    raeburn  4597:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4598:     if (!defined($username)  && !defined($domain)) {
                   4599:         return;
                   4600:     }
1.1096    raeburn  4601:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4602: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4603: }
                   4604: 
                   4605: # ------------------------------------------------------------ Syllabus Wrapper
                   4606: 
                   4607: sub syllabuswrapper {
1.707     bisitz   4608:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4609:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4610: }
1.14      harris41 4611: 
1.1397    raeburn  4612: # -----------------------------------------------------------------------------
                   4613: 
1.1396    raeburn  4614: sub aboutme_on {
                   4615:     my ($uname,$udom)=@_;
                   4616:     unless ($uname) { $uname=$env{'user.name'}; }
                   4617:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4618:     return if ($udom eq 'public' && $uname eq 'public');
                   4619:     my $hashkey=$uname.':'.$udom;
                   4620:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4621:     if ($cached) {
                   4622:         return $aboutme;
                   4623:     }
                   4624:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4625:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4626:     return $aboutme;
                   4627: }
                   4628: 
                   4629: sub devalidate_aboutme_cache {
                   4630:     my ($uname,$udom)=@_;
                   4631:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4632:     if (!$uname) { $uname=$env{'user.name'};   }
                   4633:     return if ($udom eq 'public' && $uname eq 'public');
                   4634:     my $id=$uname.':'.$udom;
                   4635:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4636: }
                   4637: 
1.208     matthew  4638: sub track_student_link {
1.887     raeburn  4639:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4640:     my $link ="/adm/trackstudent?";
1.208     matthew  4641:     my $title = 'View recent activity';
                   4642:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4643:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4644:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4645:         $title .= ' of this student';
1.268     albertel 4646:     } 
1.208     matthew  4647:     if (defined($target) && $target !~ /^\s*$/) {
                   4648:         $target = qq{target="$target"};
                   4649:     } else {
                   4650:         $target = '';
                   4651:     }
1.268     albertel 4652:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4653:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4654:     $title = &mt($title);
                   4655:     $linktext = &mt($linktext);
1.448     albertel 4656:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4657: 	&help_open_topic('View_recent_activity');
1.208     matthew  4658: }
                   4659: 
1.781     raeburn  4660: sub slot_reservations_link {
                   4661:     my ($linktext,$sname,$sdom,$target) = @_;
                   4662:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4663:     my $title = 'View slot reservation history';
                   4664:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4665:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4666:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4667:         $title .= ' of this student';
                   4668:     }
                   4669:     if (defined($target) && $target !~ /^\s*$/) {
                   4670:         $target = qq{target="$target"};
                   4671:     } else {
                   4672:         $target = '';
                   4673:     }
                   4674:     $title = &mt($title);
                   4675:     $linktext = &mt($linktext);
                   4676:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4677: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4678: 
                   4679: }
                   4680: 
1.508     www      4681: # ===================================================== Display a student photo
                   4682: 
                   4683: 
1.509     albertel 4684: sub student_image_tag {
1.508     www      4685:     my ($domain,$user)=@_;
                   4686:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4687:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4688: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4689:     } else {
                   4690: 	return '';
                   4691:     }
                   4692: }
                   4693: 
1.112     bowersj2 4694: =pod
                   4695: 
                   4696: =back
                   4697: 
                   4698: =head1 Access .tab File Data
                   4699: 
                   4700: =over 4
                   4701: 
1.648     raeburn  4702: =item * &languageids() 
1.112     bowersj2 4703: 
                   4704: returns list of all language ids
                   4705: 
                   4706: =cut
                   4707: 
1.14      harris41 4708: sub languageids {
1.16      harris41 4709:     return sort(keys(%language));
1.14      harris41 4710: }
                   4711: 
1.112     bowersj2 4712: =pod
                   4713: 
1.648     raeburn  4714: =item * &languagedescription() 
1.112     bowersj2 4715: 
                   4716: returns description of a specified language id
                   4717: 
                   4718: =cut
                   4719: 
1.14      harris41 4720: sub languagedescription {
1.125     www      4721:     my $code=shift;
                   4722:     return  ($supported_language{$code}?'* ':'').
                   4723:             $language{$code}.
1.126     www      4724: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4725: }
                   4726: 
1.1048    foxr     4727: =pod
                   4728: 
                   4729: =item * &plainlanguagedescription
                   4730: 
                   4731: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4732: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4733: 
                   4734: =cut
                   4735: 
1.145     www      4736: sub plainlanguagedescription {
                   4737:     my $code=shift;
                   4738:     return $language{$code};
                   4739: }
                   4740: 
1.1048    foxr     4741: =pod
                   4742: 
                   4743: =item * &supportedlanguagecode
                   4744: 
                   4745: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4746: code.
                   4747: 
                   4748: =cut
                   4749: 
1.145     www      4750: sub supportedlanguagecode {
                   4751:     my $code=shift;
                   4752:     return $supported_language{$code};
1.97      www      4753: }
                   4754: 
1.112     bowersj2 4755: =pod
                   4756: 
1.1048    foxr     4757: =item * &latexlanguage()
                   4758: 
                   4759: Given a language key code returns the correspondnig language to use
                   4760: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4761: is no supported hyphenation for the language code.
                   4762: 
                   4763: =cut
                   4764: 
                   4765: sub latexlanguage {
                   4766:     my $code = shift;
                   4767:     return $latex_language{$code};
                   4768: }
                   4769: 
                   4770: =pod
                   4771: 
                   4772: =item * &latexhyphenation()
                   4773: 
                   4774: Same as above but what's supplied is the language as it might be stored
                   4775: in the metadata.
                   4776: 
                   4777: =cut
                   4778: 
                   4779: sub latexhyphenation {
                   4780:     my $key = shift;
                   4781:     return $latex_language_bykey{$key};
                   4782: }
                   4783: 
                   4784: =pod
                   4785: 
1.648     raeburn  4786: =item * &copyrightids() 
1.112     bowersj2 4787: 
                   4788: returns list of all copyrights
                   4789: 
                   4790: =cut
                   4791: 
                   4792: sub copyrightids {
                   4793:     return sort(keys(%cprtag));
                   4794: }
                   4795: 
                   4796: =pod
                   4797: 
1.648     raeburn  4798: =item * &copyrightdescription() 
1.112     bowersj2 4799: 
                   4800: returns description of a specified copyright id
                   4801: 
                   4802: =cut
                   4803: 
                   4804: sub copyrightdescription {
1.166     www      4805:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4806: }
1.197     matthew  4807: 
                   4808: =pod
                   4809: 
1.648     raeburn  4810: =item * &source_copyrightids() 
1.192     taceyjo1 4811: 
                   4812: returns list of all source copyrights
                   4813: 
                   4814: =cut
                   4815: 
                   4816: sub source_copyrightids {
                   4817:     return sort(keys(%scprtag));
                   4818: }
                   4819: 
                   4820: =pod
                   4821: 
1.648     raeburn  4822: =item * &source_copyrightdescription() 
1.192     taceyjo1 4823: 
                   4824: returns description of a specified source copyright id
                   4825: 
                   4826: =cut
                   4827: 
                   4828: sub source_copyrightdescription {
                   4829:     return &mt($scprtag{shift(@_)});
                   4830: }
1.112     bowersj2 4831: 
                   4832: =pod
                   4833: 
1.648     raeburn  4834: =item * &filecategories() 
1.112     bowersj2 4835: 
                   4836: returns list of all file categories
                   4837: 
                   4838: =cut
                   4839: 
                   4840: sub filecategories {
                   4841:     return sort(keys(%category_extensions));
                   4842: }
                   4843: 
                   4844: =pod
                   4845: 
1.648     raeburn  4846: =item * &filecategorytypes() 
1.112     bowersj2 4847: 
                   4848: returns list of file types belonging to a given file
                   4849: category
                   4850: 
                   4851: =cut
                   4852: 
                   4853: sub filecategorytypes {
1.356     albertel 4854:     my ($cat) = @_;
1.1248    raeburn  4855:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4856:         return @{$category_extensions{lc($cat)}};
                   4857:     } else {
                   4858:         return ();
                   4859:     }
1.112     bowersj2 4860: }
                   4861: 
                   4862: =pod
                   4863: 
1.648     raeburn  4864: =item * &fileembstyle() 
1.112     bowersj2 4865: 
                   4866: returns embedding style for a specified file type
                   4867: 
                   4868: =cut
                   4869: 
                   4870: sub fileembstyle {
                   4871:     return $fe{lc(shift(@_))};
1.169     www      4872: }
                   4873: 
1.351     www      4874: sub filemimetype {
                   4875:     return $fm{lc(shift(@_))};
                   4876: }
                   4877: 
1.169     www      4878: 
                   4879: sub filecategoryselect {
1.1471    raeburn  4880:     my ($name,$value,$id)=@_;
1.189     matthew  4881:     return &select_form($value,$name,
1.1471    raeburn  4882:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))},
                   4883:                         '','',$id);
1.112     bowersj2 4884: }
                   4885: 
                   4886: =pod
                   4887: 
1.648     raeburn  4888: =item * &filedescription() 
1.112     bowersj2 4889: 
                   4890: returns description for a specified file type
                   4891: 
                   4892: =cut
                   4893: 
                   4894: sub filedescription {
1.188     matthew  4895:     my $file_description = $fd{lc(shift())};
                   4896:     $file_description =~ s:([\[\]]):~$1:g;
                   4897:     return &mt($file_description);
1.112     bowersj2 4898: }
                   4899: 
                   4900: =pod
                   4901: 
1.648     raeburn  4902: =item * &filedescriptionex() 
1.112     bowersj2 4903: 
                   4904: returns description for a specified file type with
                   4905: extra formatting
                   4906: 
                   4907: =cut
                   4908: 
                   4909: sub filedescriptionex {
                   4910:     my $ex=shift;
1.188     matthew  4911:     my $file_description = $fd{lc($ex)};
                   4912:     $file_description =~ s:([\[\]]):~$1:g;
                   4913:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4914: }
                   4915: 
                   4916: # End of .tab access
                   4917: =pod
                   4918: 
                   4919: =back
                   4920: 
                   4921: =cut
                   4922: 
                   4923: # ------------------------------------------------------------------ File Types
                   4924: sub fileextensions {
                   4925:     return sort(keys(%fe));
                   4926: }
                   4927: 
1.97      www      4928: # ----------------------------------------------------------- Display Languages
                   4929: # returns a hash with all desired display languages
                   4930: #
                   4931: 
                   4932: sub display_languages {
                   4933:     my %languages=();
1.695     raeburn  4934:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4935: 	$languages{$lang}=1;
1.97      www      4936:     }
                   4937:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4938:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4939: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4940: 	    $languages{$lang}=1;
1.97      www      4941:         }
                   4942:     }
                   4943:     return %languages;
1.14      harris41 4944: }
                   4945: 
1.582     albertel 4946: sub languages {
                   4947:     my ($possible_langs) = @_;
1.695     raeburn  4948:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4949:     if (!ref($possible_langs)) {
                   4950: 	if( wantarray ) {
                   4951: 	    return @preferred_langs;
                   4952: 	} else {
                   4953: 	    return $preferred_langs[0];
                   4954: 	}
                   4955:     }
                   4956:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4957:     my @preferred_possibilities;
                   4958:     foreach my $preferred_lang (@preferred_langs) {
                   4959: 	if (exists($possibilities{$preferred_lang})) {
                   4960: 	    push(@preferred_possibilities, $preferred_lang);
                   4961: 	}
                   4962:     }
                   4963:     if( wantarray ) {
                   4964: 	return @preferred_possibilities;
                   4965:     }
                   4966:     return $preferred_possibilities[0];
                   4967: }
                   4968: 
1.742     raeburn  4969: sub user_lang {
                   4970:     my ($touname,$toudom,$fromcid) = @_;
                   4971:     my @userlangs;
                   4972:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4973:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4974:                     $env{'course.'.$fromcid.'.languages'}));
                   4975:     } else {
                   4976:         my %langhash = &getlangs($touname,$toudom);
                   4977:         if ($langhash{'languages'} ne '') {
                   4978:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4979:         } else {
                   4980:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4981:             if ($domdefs{'lang_def'} ne '') {
                   4982:                 @userlangs = ($domdefs{'lang_def'});
                   4983:             }
                   4984:         }
                   4985:     }
                   4986:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4987:     my $user_lh = Apache::localize->get_handle(@languages);
                   4988:     return $user_lh;
                   4989: }
                   4990: 
                   4991: 
1.112     bowersj2 4992: ###############################################################
                   4993: ##               Student Answer Attempts                     ##
                   4994: ###############################################################
                   4995: 
                   4996: =pod
                   4997: 
                   4998: =head1 Alternate Problem Views
                   4999: 
                   5000: =over 4
                   5001: 
1.648     raeburn  5002: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  5003:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 5004: 
                   5005: Return string with previous attempt on problem. Arguments:
                   5006: 
                   5007: =over 4
                   5008: 
                   5009: =item * $symb: Problem, including path
                   5010: 
                   5011: =item * $username: username of the desired student
                   5012: 
                   5013: =item * $domain: domain of the desired student
1.14      harris41 5014: 
1.112     bowersj2 5015: =item * $course: Course ID
1.14      harris41 5016: 
1.112     bowersj2 5017: =item * $getattempt: Leave blank for all attempts, otherwise put
                   5018:     something
1.14      harris41 5019: 
1.112     bowersj2 5020: =item * $regexp: if string matches this regexp, the string will be
                   5021:     sent to $gradesub
1.14      harris41 5022: 
1.112     bowersj2 5023: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 5024: 
1.1199    raeburn  5025: =item * $usec: section of the desired student
                   5026: 
                   5027: =item * $identifier: counter for student (multiple students one problem) or 
                   5028:     problem (one student; whole sequence).
                   5029: 
1.112     bowersj2 5030: =back
1.14      harris41 5031: 
1.112     bowersj2 5032: The output string is a table containing all desired attempts, if any.
1.16      harris41 5033: 
1.112     bowersj2 5034: =cut
1.1       albertel 5035: 
                   5036: sub get_previous_attempt {
1.1199    raeburn  5037:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 5038:   my $prevattempts='';
1.43      ng       5039:   no strict 'refs';
1.1       albertel 5040:   if ($symb) {
1.3       albertel 5041:     my (%returnhash)=
                   5042:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 5043:     if ($returnhash{'version'}) {
                   5044:       my %lasthash=();
                   5045:       my $version;
                   5046:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  5047:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   5048:             if ($key =~ /\.rawrndseed$/) {
                   5049:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   5050:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5051:             } else {
                   5052:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5053:             }
1.19      harris41 5054:         }
1.1       albertel 5055:       }
1.596     albertel 5056:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5057:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5058:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5059:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5060:       foreach my $key (sort(keys(%lasthash))) {
                   5061: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5062: 	if ($#parts > 0) {
1.31      albertel 5063: 	  my $data=$parts[-1];
1.989     raeburn  5064:           next if ($data eq 'foilorder');
1.31      albertel 5065: 	  pop(@parts);
1.1010    www      5066:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5067:           if ($data eq 'type') {
                   5068:               unless ($showsurv) {
                   5069:                   my $id = join(',',@parts);
                   5070:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5071:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5072:                       $lasthidden{$ign.'.'.$id} = 1;
                   5073:                   }
1.945     raeburn  5074:               }
1.1199    raeburn  5075:               if ($identifier ne '') {
                   5076:                   my $id = join(',',@parts);
                   5077:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5078:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5079:                       $hidestatus{$ign.'.'.$id} = 1;
                   5080:                   }
                   5081:               }
                   5082:           } elsif ($data eq 'regrader') {
                   5083:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5084:                   my $id = join(',',@parts);
                   5085:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5086:               }
1.1010    www      5087:           } 
1.31      albertel 5088: 	} else {
1.41      ng       5089: 	  if ($#parts == 0) {
                   5090: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5091: 	  } else {
                   5092: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5093: 	  }
1.31      albertel 5094: 	}
1.16      harris41 5095:       }
1.596     albertel 5096:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5097:       if ($getattempt eq '') {
1.1199    raeburn  5098:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5099:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5100:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5101:                 foreach my $id (keys(%regraded)) {
                   5102:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5103:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5104:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5105:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5106:                     }
                   5107:                 }
                   5108:             }
1.1200    raeburn  5109:         }
                   5110: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5111:             my (@hidden,@unsolved);
1.945     raeburn  5112:             if (%typeparts) {
                   5113:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5114:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5115:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5116:                         push(@hidden,$id);
1.1199    raeburn  5117:                     } elsif ($identifier ne '') {
                   5118:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5119:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5120:                                 ($hidestatus{$id})) {
1.1200    raeburn  5121:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5122:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5123:                                 push(@{$solved{$id}},$version);
                   5124:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5125:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5126:                                 my $skip;
                   5127:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5128:                                     foreach my $reset (@{$resets{$id}}) {
                   5129:                                         if ($reset > $solved{$id}[-1]) {
                   5130:                                             $skip=1;
                   5131:                                             last;
                   5132:                                         }
                   5133:                                     }
                   5134:                                 }
                   5135:                                 unless ($skip) {
                   5136:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5137:                                     push(@unsolved,$partslist);
                   5138:                                 }
                   5139:                             }
                   5140:                         }
1.945     raeburn  5141:                     }
                   5142:                 }
                   5143:             }
                   5144:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5145:                            '<td>'.&mt('Transaction [_1]',$version);
                   5146:             if (@unsolved) {
                   5147:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5148:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5149:                                  &mt('Hide').'</label></span>';
                   5150:             }
                   5151:             $prevattempts .= '</td>';
1.945     raeburn  5152:             if (@hidden) {
                   5153:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5154:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5155:                     my $hide;
                   5156:                     foreach my $id (@hidden) {
                   5157:                         if ($key =~ /^\Q$id\E/) {
                   5158:                             $hide = 1;
                   5159:                             last;
                   5160:                         }
                   5161:                     }
                   5162:                     if ($hide) {
                   5163:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5164:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5165:                             my $value = &format_previous_attempt_value($key,
                   5166:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5167:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5168:                         } else {
                   5169:                             $prevattempts.='<td>&nbsp;</td>';
                   5170:                         }
                   5171:                     } else {
                   5172:                         if ($key =~ /\./) {
1.1212    raeburn  5173:                             my $value = $returnhash{$version.':'.$key};
                   5174:                             if ($key =~ /\.rndseed$/) {
                   5175:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5176:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5177:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5178:                                 }
                   5179:                             }
                   5180:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5181:                                            '&nbsp;</td>';
1.945     raeburn  5182:                         } else {
                   5183:                             $prevattempts.='<td>&nbsp;</td>';
                   5184:                         }
                   5185:                     }
                   5186:                 }
                   5187:             } else {
                   5188: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5189:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5190:                     my $value = $returnhash{$version.':'.$key};
                   5191:                     if ($key =~ /\.rndseed$/) {
                   5192:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5193:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5194:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5195:                         }
                   5196:                     }
                   5197:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5198:                                    '&nbsp;</td>';
1.945     raeburn  5199: 	        }
                   5200:             }
                   5201: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5202: 	 }
1.1       albertel 5203:       }
1.945     raeburn  5204:       my @currhidden = keys(%lasthidden);
1.596     albertel 5205:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5206:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5207:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5208:           if (%typeparts) {
                   5209:               my $hidden;
                   5210:               foreach my $id (@currhidden) {
                   5211:                   if ($key =~ /^\Q$id\E/) {
                   5212:                       $hidden = 1;
                   5213:                       last;
                   5214:                   }
                   5215:               }
                   5216:               if ($hidden) {
                   5217:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5218:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5219:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5220:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5221:                           $value = &$gradesub($value);
                   5222:                       }
1.1173    kruse    5223:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5224:                   } else {
                   5225:                       $prevattempts.='<td>&nbsp;</td>';
                   5226:                   }
                   5227:               } else {
                   5228:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5229:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5230:                       $value = &$gradesub($value);
                   5231:                   }
1.1173    kruse    5232:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5233:               }
                   5234:           } else {
                   5235: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5236: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5237:                   $value = &$gradesub($value);
                   5238:               }
1.1173    kruse    5239: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5240:           }
1.16      harris41 5241:       }
1.596     albertel 5242:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5243:     } else {
1.1305    raeburn  5244:       my $msg;
                   5245:       if ($symb =~ /ext\.tool$/) {
                   5246:           $msg = &mt('No grade passed back.');
                   5247:       } else {
                   5248:           $msg = &mt('Nothing submitted - no attempts.');
                   5249:       }
1.596     albertel 5250:       $prevattempts=
                   5251: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5252: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5253: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5254:     }
                   5255:   } else {
1.596     albertel 5256:     $prevattempts=
                   5257: 	  &start_data_table().&start_data_table_row().
                   5258: 	  '<td>'.&mt('No data.').'</td>'.
                   5259: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5260:   }
1.10      albertel 5261: }
                   5262: 
1.581     albertel 5263: sub format_previous_attempt_value {
                   5264:     my ($key,$value) = @_;
1.1011    www      5265:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5266:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5267:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5268:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5269:     } elsif ($key =~ /answerstring$/) {
                   5270:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5271:         my @answer = %answers;
                   5272:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5273:         my @anskeys = sort(keys(%answers));
                   5274:         if (@anskeys == 1) {
                   5275:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5276:             if ($answer =~ m{\0}) {
                   5277:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5278:             }
                   5279:             my $tag_internal_answer_name = 'INTERNAL';
                   5280:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5281:                 $value = $answer; 
                   5282:             } else {
                   5283:                 $value = $anskeys[0].'='.$answer;
                   5284:             }
                   5285:         } else {
                   5286:             foreach my $ans (@anskeys) {
                   5287:                 my $answer = $answers{$ans};
1.1001    raeburn  5288:                 if ($answer =~ m{\0}) {
                   5289:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5290:                 }
                   5291:                 $value .=  $ans.'='.$answer.'<br />';;
                   5292:             } 
                   5293:         }
1.581     albertel 5294:     } else {
1.1173    kruse    5295:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5296:     }
                   5297:     return $value;
                   5298: }
                   5299: 
                   5300: 
1.107     albertel 5301: sub relative_to_absolute {
                   5302:     my ($url,$output)=@_;
                   5303:     my $parser=HTML::TokeParser->new(\$output);
                   5304:     my $token;
                   5305:     my $thisdir=$url;
                   5306:     my @rlinks=();
                   5307:     while ($token=$parser->get_token) {
                   5308: 	if ($token->[0] eq 'S') {
                   5309: 	    if ($token->[1] eq 'a') {
                   5310: 		if ($token->[2]->{'href'}) {
                   5311: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5312: 		}
                   5313: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5314: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5315: 	    } elsif ($token->[1] eq 'base') {
                   5316: 		$thisdir=$token->[2]->{'href'};
                   5317: 	    }
                   5318: 	}
                   5319:     }
                   5320:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5321:     foreach my $link (@rlinks) {
1.726     raeburn  5322: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5323: 		($link=~/^\//) ||
                   5324: 		($link=~/^javascript:/i) ||
                   5325: 		($link=~/^mailto:/i) ||
                   5326: 		($link=~/^\#/)) {
                   5327: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5328: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5329: 	}
                   5330:     }
                   5331: # -------------------------------------------------- Deal with Applet codebases
                   5332:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5333:     return $output;
                   5334: }
                   5335: 
1.112     bowersj2 5336: =pod
                   5337: 
1.648     raeburn  5338: =item * &get_student_view()
1.112     bowersj2 5339: 
                   5340: show a snapshot of what student was looking at
                   5341: 
                   5342: =cut
                   5343: 
1.10      albertel 5344: sub get_student_view {
1.186     albertel 5345:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5346:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5347:   my (%form);
1.10      albertel 5348:   my @elements=('symb','courseid','domain','username');
                   5349:   foreach my $element (@elements) {
1.186     albertel 5350:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5351:   }
1.186     albertel 5352:   if (defined($moreenv)) {
                   5353:       %form=(%form,%{$moreenv});
                   5354:   }
1.236     albertel 5355:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5356:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5357:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5358:       $feedurl =~ s{^/adm/wrapper}{};
                   5359:   }
1.650     www      5360:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5361:   $userview=~s/\<body[^\>]*\>//gi;
                   5362:   $userview=~s/\<\/body\>//gi;
                   5363:   $userview=~s/\<html\>//gi;
                   5364:   $userview=~s/\<\/html\>//gi;
                   5365:   $userview=~s/\<head\>//gi;
                   5366:   $userview=~s/\<\/head\>//gi;
1.1460    raeburn  5367:   $userview=~s/\Q<div class="LC_landmark" role="main"\E/<div class="LC_landmark"/; 
1.11      albertel 5368:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5369:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5370:   if (wantarray) {
                   5371:      return ($userview,$response);
                   5372:   } else {
                   5373:      return $userview;
                   5374:   }
                   5375: }
                   5376: 
                   5377: sub get_student_view_with_retries {
                   5378:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5379: 
                   5380:     my $ok = 0;                 # True if we got a good response.
                   5381:     my $content;
                   5382:     my $response;
                   5383: 
                   5384:     # Try to get the student_view done. within the retries count:
                   5385:     
                   5386:     do {
                   5387:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5388:          $ok      = $response->is_success;
                   5389:          if (!$ok) {
                   5390:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5391:          }
                   5392:          $retries--;
                   5393:     } while (!$ok && ($retries > 0));
                   5394:     
                   5395:     if (!$ok) {
                   5396:        $content = '';          # On error return an empty content.
                   5397:     }
1.651     www      5398:     if (wantarray) {
                   5399:        return ($content, $response);
                   5400:     } else {
                   5401:        return $content;
                   5402:     }
1.11      albertel 5403: }
                   5404: 
1.1349    raeburn  5405: sub css_links {
                   5406:     my ($currsymb,$level) = @_;
                   5407:     my ($links,@symbs,%cssrefs,%httpref);
                   5408:     if ($level eq 'map') {
                   5409:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5410:         if (ref($navmap)) {
                   5411:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5412:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5413:             foreach my $res (@resources) {
                   5414:                 if (ref($res) && $res->symb()) {
                   5415:                     push(@symbs,$res->symb());
                   5416:                 }
                   5417:             }
                   5418:         }
                   5419:     } else {
                   5420:         @symbs = ($currsymb);
                   5421:     }
                   5422:     foreach my $symb (@symbs) {
                   5423:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5424:         if ($css_href =~ /\S/) {
                   5425:             unless ($css_href =~ m{https?://}) {
                   5426:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5427:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5428:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5429:                 unless ($css_href =~ m{^/}) {
                   5430:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5431:                 }
                   5432:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5433:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5434:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5435:                         my $thisurl = $proburl;
                   5436:                         if ($env{'httpref.'.$proburl}) {
                   5437:                             $thisurl = $env{'httpref.'.$proburl};
                   5438:                         }
                   5439:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5440:                     }
                   5441:                 }
                   5442:             }
                   5443:             $cssrefs{$css_href} = 1;
                   5444:         }
                   5445:     }
                   5446:     if (keys(%httpref)) {
                   5447:         &Apache::lonnet::appenv(\%httpref);
                   5448:     }
                   5449:     if (keys(%cssrefs)) {
                   5450:         foreach my $css_href (keys(%cssrefs)) {
                   5451:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5452:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5453:         }
                   5454:     }
                   5455:     return $links;
                   5456: }
                   5457: 
1.112     bowersj2 5458: =pod
                   5459: 
1.648     raeburn  5460: =item * &get_student_answers() 
1.112     bowersj2 5461: 
                   5462: show a snapshot of how student was answering problem
                   5463: 
                   5464: =cut
                   5465: 
1.11      albertel 5466: sub get_student_answers {
1.100     sakharuk 5467:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5468:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5469:   my (%moreenv);
1.11      albertel 5470:   my @elements=('symb','courseid','domain','username');
                   5471:   foreach my $element (@elements) {
1.186     albertel 5472:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5473:   }
1.186     albertel 5474:   $moreenv{'grade_target'}='answer';
                   5475:   %moreenv=(%form,%moreenv);
1.497     raeburn  5476:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5477:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5478:   return $userview;
1.1       albertel 5479: }
1.116     albertel 5480: 
                   5481: =pod
                   5482: 
                   5483: =item * &submlink()
                   5484: 
1.242     albertel 5485: Inputs: $text $uname $udom $symb $target
1.116     albertel 5486: 
                   5487: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5488: 
                   5489: =cut
                   5490: 
                   5491: ###############################################
                   5492: sub submlink {
1.242     albertel 5493:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5494:     if (!($uname && $udom)) {
                   5495: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5496: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5497: 	if (!$symb) { $symb=$cursymb; }
                   5498:     }
1.254     matthew  5499:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5500:     $symb=&escape($symb);
1.960     bisitz   5501:     if ($target) { $target=" target=\"$target\""; }
                   5502:     return
                   5503:         '<a href="/adm/grades?command=submission'.
                   5504:         '&amp;symb='.$symb.
                   5505:         '&amp;student='.$uname.
                   5506:         '&amp;userdom='.$udom.'"'.
                   5507:         $target.'>'.$text.'</a>';
1.242     albertel 5508: }
                   5509: ##############################################
                   5510: 
                   5511: =pod
                   5512: 
                   5513: =item * &pgrdlink()
                   5514: 
                   5515: Inputs: $text $uname $udom $symb $target
                   5516: 
                   5517: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5518: 
                   5519: =cut
                   5520: 
                   5521: ###############################################
                   5522: sub pgrdlink {
                   5523:     my $link=&submlink(@_);
                   5524:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5525:     return $link;
                   5526: }
                   5527: ##############################################
                   5528: 
                   5529: =pod
                   5530: 
                   5531: =item * &pprmlink()
                   5532: 
                   5533: Inputs: $text $uname $udom $symb $target
                   5534: 
                   5535: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5536: student and a specific resource
1.242     albertel 5537: 
                   5538: =cut
                   5539: 
                   5540: ###############################################
                   5541: sub pprmlink {
                   5542:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5543:     if (!($uname && $udom)) {
                   5544: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5545: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5546: 	if (!$symb) { $symb=$cursymb; }
                   5547:     }
1.254     matthew  5548:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5549:     $symb=&escape($symb);
1.242     albertel 5550:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5551:     return '<a href="/adm/parmset?command=set&amp;'.
                   5552: 	'symb='.$symb.'&amp;uname='.$uname.
                   5553: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5554: }
                   5555: ##############################################
1.37      matthew  5556: 
1.112     bowersj2 5557: =pod
                   5558: 
                   5559: =back
                   5560: 
                   5561: =cut
                   5562: 
1.37      matthew  5563: ###############################################
1.51      www      5564: 
                   5565: 
                   5566: sub timehash {
1.687     raeburn  5567:     my ($thistime) = @_;
                   5568:     my $timezone = &Apache::lonlocal::gettimezone();
                   5569:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5570:                      ->set_time_zone($timezone);
                   5571:     my $wday = $dt->day_of_week();
                   5572:     if ($wday == 7) { $wday = 0; }
                   5573:     return ( 'second' => $dt->second(),
                   5574:              'minute' => $dt->minute(),
                   5575:              'hour'   => $dt->hour(),
                   5576:              'day'     => $dt->day_of_month(),
                   5577:              'month'   => $dt->month(),
                   5578:              'year'    => $dt->year(),
                   5579:              'weekday' => $wday,
                   5580:              'dayyear' => $dt->day_of_year(),
                   5581:              'dlsav'   => $dt->is_dst() );
1.51      www      5582: }
                   5583: 
1.370     www      5584: sub utc_string {
                   5585:     my ($date)=@_;
1.371     www      5586:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5587: }
                   5588: 
1.51      www      5589: sub maketime {
                   5590:     my %th=@_;
1.687     raeburn  5591:     my ($epoch_time,$timezone,$dt);
                   5592:     $timezone = &Apache::lonlocal::gettimezone();
                   5593:     eval {
                   5594:         $dt = DateTime->new( year   => $th{'year'},
                   5595:                              month  => $th{'month'},
                   5596:                              day    => $th{'day'},
                   5597:                              hour   => $th{'hour'},
                   5598:                              minute => $th{'minute'},
                   5599:                              second => $th{'second'},
                   5600:                              time_zone => $timezone,
                   5601:                          );
                   5602:     };
                   5603:     if (!$@) {
                   5604:         $epoch_time = $dt->epoch;
                   5605:         if ($epoch_time) {
                   5606:             return $epoch_time;
                   5607:         }
                   5608:     }
1.51      www      5609:     return POSIX::mktime(
                   5610:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5611:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5612: }
                   5613: 
                   5614: #########################################
1.51      www      5615: 
                   5616: sub findallcourses {
1.482     raeburn  5617:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5618:     my %roles;
                   5619:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5620:     my %courses;
1.51      www      5621:     my $now=time;
1.482     raeburn  5622:     if (!defined($uname)) {
                   5623:         $uname = $env{'user.name'};
                   5624:     }
                   5625:     if (!defined($udom)) {
                   5626:         $udom = $env{'user.domain'};
                   5627:     }
                   5628:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5629:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5630:         if (!%roles) {
                   5631:             %roles = (
                   5632:                        cc => 1,
1.907     raeburn  5633:                        co => 1,
1.482     raeburn  5634:                        in => 1,
                   5635:                        ep => 1,
                   5636:                        ta => 1,
                   5637:                        cr => 1,
                   5638:                        st => 1,
                   5639:              );
                   5640:         }
                   5641:         foreach my $entry (keys(%roleshash)) {
                   5642:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5643:             if ($trole =~ /^cr/) { 
                   5644:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5645:             } else {
                   5646:                 next if (!exists($roles{$trole}));
                   5647:             }
                   5648:             if ($tend) {
                   5649:                 next if ($tend < $now);
                   5650:             }
                   5651:             if ($tstart) {
                   5652:                 next if ($tstart > $now);
                   5653:             }
1.1058    raeburn  5654:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5655:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5656:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5657:             if ($secpart eq '') {
                   5658:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5659:                 $sec = 'none';
1.1058    raeburn  5660:                 $value .= $cnum.'/';
1.482     raeburn  5661:             } else {
                   5662:                 $cnum = $cnumpart;
                   5663:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5664:                 $value .= $cnum.'/'.$sec;
                   5665:             }
                   5666:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5667:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5668:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5669:                 }
                   5670:             } else {
                   5671:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5672:             }
1.482     raeburn  5673:         }
                   5674:     } else {
                   5675:         foreach my $key (keys(%env)) {
1.483     albertel 5676: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5677:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5678: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5679: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5680: 	        next if (%roles && !exists($roles{$role}));
                   5681: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5682:                 my $active=1;
                   5683:                 if ($starttime) {
                   5684: 		    if ($now<$starttime) { $active=0; }
                   5685:                 }
                   5686:                 if ($endtime) {
                   5687:                     if ($now>$endtime) { $active=0; }
                   5688:                 }
                   5689:                 if ($active) {
1.1058    raeburn  5690:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5691:                     if ($sec eq '') {
                   5692:                         $sec = 'none';
1.1058    raeburn  5693:                     } else {
                   5694:                         $value .= $sec;
                   5695:                     }
                   5696:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5697:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5698:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5699:                         }
                   5700:                     } else {
                   5701:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5702:                     }
1.474     raeburn  5703:                 }
                   5704:             }
1.51      www      5705:         }
                   5706:     }
1.474     raeburn  5707:     return %courses;
1.51      www      5708: }
1.37      matthew  5709: 
1.54      www      5710: ###############################################
1.474     raeburn  5711: 
                   5712: sub blockcheck {
1.1372    raeburn  5713:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5714:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5715:         my ($has_evb,$check_ipaccess);
                   5716:         my $dom = $env{'user.domain'};
                   5717:         if ($env{'request.course.id'}) {
                   5718:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5719:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5720:             my $checkrole = "cm./$cdom/$cnum";
                   5721:             my $sec = $env{'request.course.sec'};
                   5722:             if ($sec ne '') {
                   5723:                 $checkrole .= "/$sec";
                   5724:             }
                   5725:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5726:                 ($env{'request.role'} !~ /^st/)) {
                   5727:                 $has_evb = 1;
                   5728:             }
                   5729:             unless ($has_evb) {
                   5730:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5731:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5732:                     ($activity eq 'chat')) {
1.1372    raeburn  5733:                     if ($udom eq $cdom) {
                   5734:                         $check_ipaccess = 1;
                   5735:                     }
                   5736:                 }
                   5737:             }
1.1375    raeburn  5738:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5739:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5740:             my $checkrole;
                   5741:             if ($env{'request.role.domain'} eq '') {
                   5742:                 $checkrole = "cm./$env{'user.domain'}/";
                   5743:             } else {
                   5744:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5745:             }
                   5746:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5747:                 $has_evb = 1;
                   5748:             }
1.1372    raeburn  5749:         }
                   5750:         unless ($has_evb || $check_ipaccess) {
                   5751:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5752:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5753:                 $dom = $udom;
                   5754:             }
                   5755:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5756:                 $check_ipaccess = 1;
                   5757:             } else {
                   5758:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5759:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5760:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5761:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5762:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5763:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5764:                         $check_ipaccess = 1;
                   5765:                     }
                   5766:                 }
                   5767:             }
                   5768:         }
                   5769:         if ($check_ipaccess) {
                   5770:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5771:             unless (defined($cached)) {
                   5772:                 my %domconfig =
                   5773:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5774:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5775:             }
                   5776:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5777:                 foreach my $id (keys(%{$ipaccessref})) {
                   5778:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5779:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5780:                         if ($range) {
                   5781:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5782:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5783:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5784:                                         return ('','','',$id,$dom);
                   5785:                                         last;
                   5786:                                     }
                   5787:                                 }
                   5788:                             }
                   5789:                         }
                   5790:                     }
                   5791:                 }
                   5792:             }
                   5793:         }
1.1373    raeburn  5794:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5795:             return ();
                   5796:         }
1.1372    raeburn  5797:     }
1.1189    raeburn  5798:     if (defined($udom) && defined($uname)) {
                   5799:         # If uname and udom are for a course, check for blocks in the course.
                   5800:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5801:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5802:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5803:             return ($startblock,$endblock,$triggerblock);
                   5804:         }
                   5805:     } else {
1.490     raeburn  5806:         $udom = $env{'user.domain'};
                   5807:         $uname = $env{'user.name'};
                   5808:     }
                   5809: 
1.502     raeburn  5810:     my $startblock = 0;
                   5811:     my $endblock = 0;
1.1062    raeburn  5812:     my $triggerblock = '';
1.1373    raeburn  5813:     my %live_courses;
                   5814:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5815:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5816:     }
1.474     raeburn  5817: 
1.490     raeburn  5818:     # If uname is for a user, and activity is course-specific, i.e.,
                   5819:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5820: 
1.490     raeburn  5821:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5822:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5823:          $activity eq 'search' || $activity eq 'index' ||
                   5824:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5825:         ($env{'request.course.id'})) {
1.490     raeburn  5826:         foreach my $key (keys(%live_courses)) {
                   5827:             if ($key ne $env{'request.course.id'}) {
                   5828:                 delete($live_courses{$key});
                   5829:             }
                   5830:         }
                   5831:     }
                   5832: 
                   5833:     my $otheruser = 0;
                   5834:     my %own_courses;
                   5835:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5836:         # Resource belongs to user other than current user.
                   5837:         $otheruser = 1;
                   5838:         # Gather courses for current user
                   5839:         %own_courses = 
                   5840:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5841:     }
                   5842: 
                   5843:     # Gather active course roles - course coordinator, instructor, 
                   5844:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5845: 
                   5846:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5847:         my ($cdom,$cnum);
                   5848:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5849:             $cdom = $env{'course.'.$course.'.domain'};
                   5850:             $cnum = $env{'course.'.$course.'.num'};
                   5851:         } else {
1.490     raeburn  5852:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5853:         }
                   5854:         my $no_ownblock = 0;
                   5855:         my $no_userblock = 0;
1.533     raeburn  5856:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5857:             # Check if current user has 'evb' priv for this
                   5858:             if (defined($own_courses{$course})) {
                   5859:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5860:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5861:                     if ($sec ne 'none') {
                   5862:                         $checkrole .= '/'.$sec;
                   5863:                     }
                   5864:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5865:                         $no_ownblock = 1;
                   5866:                         last;
                   5867:                     }
                   5868:                 }
                   5869:             }
                   5870:             # if they have 'evb' priv and are currently not playing student
                   5871:             next if (($no_ownblock) &&
                   5872:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5873:         }
1.474     raeburn  5874:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5875:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5876:             if ($sec ne 'none') {
1.482     raeburn  5877:                 $checkrole .= '/'.$sec;
1.474     raeburn  5878:             }
1.490     raeburn  5879:             if ($otheruser) {
                   5880:                 # Resource belongs to user other than current user.
                   5881:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5882:                 my (%allroles,%userroles);
                   5883:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5884:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5885:                         my ($trole,$tdom,$tnum,$tsec);
                   5886:                         if ($entry =~ /^cr/) {
                   5887:                             ($trole,$tdom,$tnum,$tsec) = 
                   5888:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5889:                         } else {
                   5890:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5891:                         }
                   5892:                         my ($spec,$area,$trest);
                   5893:                         $area = '/'.$tdom.'/'.$tnum;
                   5894:                         $trest = $tnum;
                   5895:                         if ($tsec ne '') {
                   5896:                             $area .= '/'.$tsec;
                   5897:                             $trest .= '/'.$tsec;
                   5898:                         }
                   5899:                         $spec = $trole.'.'.$area;
                   5900:                         if ($trole =~ /^cr/) {
                   5901:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5902:                                                               $tdom,$spec,$trest,$area);
                   5903:                         } else {
                   5904:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5905:                                                                 $tdom,$spec,$trest,$area);
                   5906:                         }
                   5907:                     }
1.1276    raeburn  5908:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5909:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5910:                         if ($1) {
                   5911:                             $no_userblock = 1;
                   5912:                             last;
                   5913:                         }
1.486     raeburn  5914:                     }
                   5915:                 }
1.490     raeburn  5916:             } else {
                   5917:                 # Resource belongs to current user
                   5918:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5919:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5920:                     $no_ownblock = 1;
                   5921:                     last;
                   5922:                 }
1.474     raeburn  5923:             }
                   5924:         }
                   5925:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5926:         next if (($no_ownblock) &&
1.491     albertel 5927:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5928:         next if ($no_userblock);
1.474     raeburn  5929: 
1.1303    raeburn  5930:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5931:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5932: 
1.1062    raeburn  5933:         my ($start,$end,$trigger) = 
1.1347    raeburn  5934:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5935:         if (($start != 0) && 
                   5936:             (($startblock == 0) || ($startblock > $start))) {
                   5937:             $startblock = $start;
1.1062    raeburn  5938:             if ($trigger ne '') {
                   5939:                 $triggerblock = $trigger;
                   5940:             }
1.502     raeburn  5941:         }
                   5942:         if (($end != 0)  &&
                   5943:             (($endblock == 0) || ($endblock < $end))) {
                   5944:             $endblock = $end;
1.1062    raeburn  5945:             if ($trigger ne '') {
                   5946:                 $triggerblock = $trigger;
                   5947:             }
1.502     raeburn  5948:         }
1.490     raeburn  5949:     }
1.1062    raeburn  5950:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5951: }
                   5952: 
                   5953: sub get_blocks {
1.1347    raeburn  5954:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5955:     my $startblock = 0;
                   5956:     my $endblock = 0;
1.1062    raeburn  5957:     my $triggerblock = '';
1.490     raeburn  5958:     my $course = $cdom.'_'.$cnum;
                   5959:     $setters->{$course} = {};
                   5960:     $setters->{$course}{'staff'} = [];
                   5961:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5962:     $setters->{$course}{'triggers'} = [];
                   5963:     my (@blockers,%triggered);
                   5964:     my $now = time;
                   5965:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5966:     if ($activity eq 'docs') {
1.1348    raeburn  5967:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5968:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5969:             $blocked = 1;
                   5970:             $nosymbcache = 1;
1.1348    raeburn  5971:             $noenccheck = 1;
1.1347    raeburn  5972:         }
1.1348    raeburn  5973:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5974:         foreach my $block (@blockers) {
                   5975:             if ($block =~ /^firstaccess____(.+)$/) {
                   5976:                 my $item = $1;
                   5977:                 my $type = 'map';
                   5978:                 my $timersymb = $item;
                   5979:                 if ($item eq 'course') {
                   5980:                     $type = 'course';
                   5981:                 } elsif ($item =~ /___\d+___/) {
                   5982:                     $type = 'resource';
                   5983:                 } else {
                   5984:                     $timersymb = &Apache::lonnet::symbread($item);
                   5985:                 }
                   5986:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5987:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5988:                 $triggered{$block} = {
                   5989:                                        start => $start,
                   5990:                                        end   => $end,
                   5991:                                        type  => $type,
                   5992:                                      };
                   5993:             }
                   5994:         }
                   5995:     } else {
                   5996:         foreach my $block (keys(%commblocks)) {
                   5997:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5998:                 my ($start,$end) = ($1,$2);
                   5999:                 if ($start <= time && $end >= time) {
                   6000:                     if (ref($commblocks{$block}) eq 'HASH') {
                   6001:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6002:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6003:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   6004:                                     push(@blockers,$block);
                   6005:                                 }
                   6006:                             }
                   6007:                         }
                   6008:                     }
                   6009:                 }
                   6010:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6011:                 my $item = $1;
                   6012:                 my $timersymb = $item; 
                   6013:                 my $type = 'map';
                   6014:                 if ($item eq 'course') {
                   6015:                     $type = 'course';
                   6016:                 } elsif ($item =~ /___\d+___/) {
                   6017:                     $type = 'resource';
                   6018:                 } else {
                   6019:                     $timersymb = &Apache::lonnet::symbread($item);
                   6020:                 }
                   6021:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   6022:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   6023:                 if ($start && $end) {
                   6024:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  6025:                         if (ref($commblocks{$block}) eq 'HASH') {
                   6026:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6027:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   6028:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   6029:                                         push(@blockers,$block);
                   6030:                                         $triggered{$block} = {
                   6031:                                                                start => $start,
                   6032:                                                                end   => $end,
                   6033:                                                                type  => $type,
                   6034:                                                              };
                   6035:                                     }
                   6036:                                 }
                   6037:                             }
1.1062    raeburn  6038:                         }
                   6039:                     }
1.490     raeburn  6040:                 }
1.1062    raeburn  6041:             }
                   6042:         }
                   6043:     }
                   6044:     foreach my $blocker (@blockers) {
                   6045:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6046:             &parse_block_record($commblocks{$blocker});
                   6047:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6048:         my ($start,$end,$triggertype);
                   6049:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6050:             ($start,$end) = ($1,$2);
                   6051:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6052:             $start = $triggered{$blocker}{'start'};
                   6053:             $end = $triggered{$blocker}{'end'};
                   6054:             $triggertype = $triggered{$blocker}{'type'};
                   6055:         }
                   6056:         if ($start) {
                   6057:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6058:             if ($triggertype) {
                   6059:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6060:             } else {
                   6061:                 push(@{$$setters{$course}{'triggers'}},0);
                   6062:             }
                   6063:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6064:                 $startblock = $start;
                   6065:                 if ($triggertype) {
                   6066:                     $triggerblock = $blocker;
1.474     raeburn  6067:                 }
                   6068:             }
1.1062    raeburn  6069:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6070:                $endblock = $end;
                   6071:                if ($triggertype) {
                   6072:                    $triggerblock = $blocker;
                   6073:                }
                   6074:             }
1.474     raeburn  6075:         }
                   6076:     }
1.1062    raeburn  6077:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6078: }
                   6079: 
                   6080: sub parse_block_record {
                   6081:     my ($record) = @_;
                   6082:     my ($setuname,$setudom,$title,$blocks);
                   6083:     if (ref($record) eq 'HASH') {
                   6084:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6085:         $title = &unescape($record->{'event'});
                   6086:         $blocks = $record->{'blocks'};
                   6087:     } else {
                   6088:         my @data = split(/:/,$record,3);
                   6089:         if (scalar(@data) eq 2) {
                   6090:             $title = $data[1];
                   6091:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6092:         } else {
                   6093:             ($setuname,$setudom,$title) = @data;
                   6094:         }
                   6095:         $blocks = { 'com' => 'on' };
                   6096:     }
                   6097:     return ($setuname,$setudom,$title,$blocks);
                   6098: }
                   6099: 
1.854     kalberla 6100: sub blocking_status {
1.1372    raeburn  6101:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6102:     my %setters;
1.890     droeschl 6103: 
1.1061    raeburn  6104: # check for active blocking
1.1372    raeburn  6105:     if ($clientip eq '') {
                   6106:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6107:     }
                   6108:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6109:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6110:     my $blocked = 0;
1.1372    raeburn  6111:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6112:         $blocked = 1;
                   6113:     }
1.890     droeschl 6114: 
1.1061    raeburn  6115: # caller just wants to know whether a block is active
                   6116:     if (!wantarray) { return $blocked; }
                   6117: 
                   6118: # build a link to a popup window containing the details
                   6119:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6120: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6121:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6122:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6123:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6124:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6125:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6126:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6127:         if ($symb) {
                   6128:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6129:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6130:         }
1.1062    raeburn  6131:     }
1.1061    raeburn  6132: 
                   6133:     my $output .= <<'END_MYBLOCK';
                   6134: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6135:     var options = "width=" + w + ",height=" + h + ",";
                   6136:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6137:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6138:     var newWin = window.open(url, wdwName, options);
                   6139:     newWin.focus();
                   6140: }
1.890     droeschl 6141: END_MYBLOCK
1.854     kalberla 6142: 
1.1061    raeburn  6143:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6144:   
1.1061    raeburn  6145:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6146:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6147:     my $class = 'LC_comblock';
1.1062    raeburn  6148:     if ($activity eq 'docs') {
                   6149:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6150:         $class = '';
1.1063    raeburn  6151:     } elsif ($activity eq 'printout') {
                   6152:         $text = &mt('Printing Blocked');
1.1232    raeburn  6153:     } elsif ($activity eq 'passwd') {
                   6154:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6155:     } elsif ($activity eq 'grades') {
                   6156:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6157:     } elsif ($activity eq 'search') {
                   6158:         $text = &mt('Search Blocked');
1.1444    raeburn  6159:     } elsif ($activity eq 'index') {
                   6160:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6161:     } elsif ($activity eq 'alert') {
                   6162:         $text = &mt('Checking Critical Messages Blocked');
                   6163:     } elsif ($activity eq 'reinit') {
                   6164:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6165:     } elsif ($activity eq 'about') {
                   6166:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6167:     } elsif ($activity eq 'wishlist') {
                   6168:         $text = &mt('Access to Stored Links Blocked');
                   6169:     } elsif ($activity eq 'annotate') {
                   6170:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6171:     }
1.1061    raeburn  6172:     $output .= <<"END_BLOCK";
1.1217    raeburn  6173: <div class='$class'>
1.869     kalberla 6174:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6175:   title='$text'>
                   6176:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6177:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6178:   title='$text'>$text</a>
1.867     kalberla 6179: </div>
                   6180: 
                   6181: END_BLOCK
1.474     raeburn  6182: 
1.1061    raeburn  6183:     return ($blocked, $output);
1.854     kalberla 6184: }
1.490     raeburn  6185: 
1.60      matthew  6186: ###############################################
                   6187: 
1.682     raeburn  6188: sub check_ip_acc {
1.1201    raeburn  6189:     my ($acc,$clientip)=@_;
1.682     raeburn  6190:     &Apache::lonxml::debug("acc is $acc");
                   6191:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6192:         return 1;
                   6193:     }
1.1339    raeburn  6194:     my ($ip,$allowed);
                   6195:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6196:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6197:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6198:     } else {
1.1350    raeburn  6199:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6200:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6201:     }
1.682     raeburn  6202: 
                   6203:     my $name;
1.1219    raeburn  6204:     my %access = (
                   6205:                      allowfrom => 1,
                   6206:                      denyfrom  => 0,
                   6207:                  );
                   6208:     my @allows;
                   6209:     my @denies;
                   6210:     foreach my $item (split(',',$acc)) {
                   6211:         $item =~ s/^\s*//;
                   6212:         $item =~ s/\s*$//;
                   6213:         my $pattern;
                   6214:         if ($item =~ /^\!(.+)$/) {
                   6215:             push(@denies,$1);
                   6216:         } else {
                   6217:             push(@allows,$item);
                   6218:         }
                   6219:    }
                   6220:    my $numdenies = scalar(@denies);
                   6221:    my $numallows = scalar(@allows);
                   6222:    my $count = 0;
                   6223:    foreach my $pattern (@denies,@allows) {
                   6224:         $count ++; 
                   6225:         my $acctype = 'allowfrom';
                   6226:         if ($count <= $numdenies) {
                   6227:             $acctype = 'denyfrom';
                   6228:         }
1.682     raeburn  6229:         if ($pattern =~ /\*$/) {
                   6230:             #35.8.*
                   6231:             $pattern=~s/\*//;
1.1219    raeburn  6232:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6233:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6234:             #35.8.3.[34-56]
                   6235:             my $low=$2;
                   6236:             my $high=$3;
                   6237:             $pattern=$1;
                   6238:             if ($ip =~ /^\Q$pattern\E/) {
                   6239:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6240:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6241:             }
                   6242:         } elsif ($pattern =~ /^\*/) {
                   6243:             #*.msu.edu
                   6244:             $pattern=~s/\*//;
                   6245:             if (!defined($name)) {
                   6246:                 use Socket;
                   6247:                 my $netaddr=inet_aton($ip);
                   6248:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6249:             }
1.1219    raeburn  6250:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6251:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6252:             #127.0.0.1
1.1219    raeburn  6253:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6254:         } else {
                   6255:             #some.name.com
                   6256:             if (!defined($name)) {
                   6257:                 use Socket;
                   6258:                 my $netaddr=inet_aton($ip);
                   6259:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6260:             }
1.1219    raeburn  6261:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6262:         }
                   6263:         if ($allowed =~ /^(0|1)$/) { last; }
                   6264:     }
                   6265:     if ($allowed eq '') {
                   6266:         if ($numdenies && !$numallows) {
                   6267:             $allowed = 1;
                   6268:         } else {
                   6269:             $allowed = 0;
1.682     raeburn  6270:         }
                   6271:     }
                   6272:     return $allowed;
                   6273: }
                   6274: 
                   6275: ###############################################
                   6276: 
1.60      matthew  6277: =pod
                   6278: 
1.112     bowersj2 6279: =head1 Domain Template Functions
                   6280: 
                   6281: =over 4
                   6282: 
                   6283: =item * &determinedomain()
1.60      matthew  6284: 
                   6285: Inputs: $domain (usually will be undef)
                   6286: 
1.63      www      6287: Returns: Determines which domain should be used for designs
1.60      matthew  6288: 
                   6289: =cut
1.54      www      6290: 
1.60      matthew  6291: ###############################################
1.63      www      6292: sub determinedomain {
                   6293:     my $domain=shift;
1.531     albertel 6294:     if (! $domain) {
1.60      matthew  6295:         # Determine domain if we have not been given one
1.893     raeburn  6296:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6297:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6298:         if ($env{'request.role.domain'}) { 
                   6299:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6300:         }
                   6301:     }
1.63      www      6302:     return $domain;
                   6303: }
                   6304: ###############################################
1.517     raeburn  6305: 
1.518     albertel 6306: sub devalidate_domconfig_cache {
                   6307:     my ($udom)=@_;
                   6308:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6309: }
                   6310: 
                   6311: # ---------------------- Get domain configuration for a domain
                   6312: sub get_domainconf {
                   6313:     my ($udom) = @_;
                   6314:     my $cachetime=1800;
                   6315:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6316:     if (defined($cached)) { return %{$result}; }
                   6317: 
                   6318:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6319: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6320:     my (%designhash,%legacy);
1.518     albertel 6321:     if (keys(%domconfig) > 0) {
                   6322:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6323:             if (keys(%{$domconfig{'login'}})) {
                   6324:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6325:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6326:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6327:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6328:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6329:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6330:                                         if ($key eq 'loginvia') {
                   6331:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6332:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6333:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6334:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6335: 
                   6336:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6337:                                                 } else {
                   6338:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6339:                                                 }
1.948     raeburn  6340:                                             }
1.1208    raeburn  6341:                                         } elsif ($key eq 'headtag') {
                   6342:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6343:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6344:                                             }
1.946     raeburn  6345:                                         }
1.1208    raeburn  6346:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6347:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6348:                                         }
1.946     raeburn  6349:                                     }
                   6350:                                 }
                   6351:                             }
1.1366    raeburn  6352:                         } elsif ($key eq 'saml') {
                   6353:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6354:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6355:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6356:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6357:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6358:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6359:                                         }
                   6360:                                     }
                   6361:                                 }
                   6362:                             }
1.946     raeburn  6363:                         } else {
                   6364:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6365:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6366:                                     $domconfig{'login'}{$key}{$img};
                   6367:                             }
1.699     raeburn  6368:                         }
                   6369:                     } else {
                   6370:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6371:                     }
1.632     raeburn  6372:                 }
                   6373:             } else {
                   6374:                 $legacy{'login'} = 1;
1.518     albertel 6375:             }
1.632     raeburn  6376:         } else {
                   6377:             $legacy{'login'} = 1;
1.518     albertel 6378:         }
                   6379:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6380:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6381:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6382:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6383:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6384:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6385:                         }
1.518     albertel 6386:                     }
                   6387:                 }
1.632     raeburn  6388:             } else {
                   6389:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6390:             }
1.632     raeburn  6391:         } else {
                   6392:             $legacy{'rolecolors'} = 1;
1.518     albertel 6393:         }
1.948     raeburn  6394:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6395:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6396:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6397:             }
                   6398:         }
1.632     raeburn  6399:         if (keys(%legacy) > 0) {
                   6400:             my %legacyhash = &get_legacy_domconf($udom);
                   6401:             foreach my $item (keys(%legacyhash)) {
                   6402:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6403:                     if ($legacy{'login'}) { 
                   6404:                         $designhash{$item} = $legacyhash{$item};
                   6405:                     }
                   6406:                 } else {
                   6407:                     if ($legacy{'rolecolors'}) {
                   6408:                         $designhash{$item} = $legacyhash{$item};
                   6409:                     }
1.518     albertel 6410:                 }
                   6411:             }
                   6412:         }
1.632     raeburn  6413:     } else {
                   6414:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6415:     }
                   6416:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6417: 				  $cachetime);
                   6418:     return %designhash;
                   6419: }
                   6420: 
1.632     raeburn  6421: sub get_legacy_domconf {
                   6422:     my ($udom) = @_;
                   6423:     my %legacyhash;
                   6424:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6425:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6426:     if (-e $designfile) {
1.1317    raeburn  6427:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6428:             while (my $line = <$fh>) {
                   6429:                 next if ($line =~ /^\#/);
                   6430:                 chomp($line);
                   6431:                 my ($key,$val)=(split(/\=/,$line));
                   6432:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6433:             }
                   6434:             close($fh);
                   6435:         }
                   6436:     }
1.1026    raeburn  6437:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6438:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6439:     }
                   6440:     return %legacyhash;
                   6441: }
                   6442: 
1.63      www      6443: =pod
                   6444: 
1.112     bowersj2 6445: =item * &domainlogo()
1.63      www      6446: 
                   6447: Inputs: $domain (usually will be undef)
                   6448: 
                   6449: Returns: A link to a domain logo, if the domain logo exists.
                   6450: If the domain logo does not exist, a description of the domain.
                   6451: 
                   6452: =cut
1.112     bowersj2 6453: 
1.63      www      6454: ###############################################
                   6455: sub domainlogo {
1.517     raeburn  6456:     my $domain = &determinedomain(shift);
1.518     albertel 6457:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6458:     # See if there is a logo
                   6459:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6460:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6461:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6462: 	    if ($imgsrc =~ m{^/res/}) {
                   6463: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6464: 		&Apache::lonnet::repcopy($local_name);
                   6465: 	    }
                   6466: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6467:         }
                   6468:         my $alttext = $domain;
                   6469:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6470:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6471:         }
                   6472:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6473:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6474:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6475:     } else {
1.60      matthew  6476:         return '';
1.59      www      6477:     }
                   6478: }
1.63      www      6479: ##############################################
                   6480: 
                   6481: =pod
                   6482: 
1.112     bowersj2 6483: =item * &designparm()
1.63      www      6484: 
                   6485: Inputs: $which parameter; $domain (usually will be undef)
                   6486: 
                   6487: Returns: value of designparamter $which
                   6488: 
                   6489: =cut
1.112     bowersj2 6490: 
1.397     albertel 6491: 
1.400     albertel 6492: ##############################################
1.397     albertel 6493: sub designparm {
                   6494:     my ($which,$domain)=@_;
                   6495:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6496:         return $env{'environment.color.'.$which};
1.96      www      6497:     }
1.63      www      6498:     $domain=&determinedomain($domain);
1.1016    raeburn  6499:     my %domdesign;
                   6500:     unless ($domain eq 'public') {
                   6501:         %domdesign = &get_domainconf($domain);
                   6502:     }
1.520     raeburn  6503:     my $output;
1.517     raeburn  6504:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6505:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6506:     } else {
1.520     raeburn  6507:         $output = $defaultdesign{$which};
                   6508:     }
                   6509:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6510:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6511:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6512:             if ($output =~ m{^/res/}) {
                   6513:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6514:                 &Apache::lonnet::repcopy($local_name);
                   6515:             }
1.520     raeburn  6516:             $output = &lonhttpdurl($output);
                   6517:         }
1.63      www      6518:     }
1.520     raeburn  6519:     return $output;
1.63      www      6520: }
1.59      www      6521: 
1.822     bisitz   6522: ##############################################
                   6523: =pod
                   6524: 
1.832     bisitz   6525: =item * &authorspace()
                   6526: 
1.1028    raeburn  6527: Inputs: $url (usually will be undef).
1.832     bisitz   6528: 
1.1132    raeburn  6529: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6530:          directory being viewed (or for which action is being taken). 
                   6531:          If $url is provided, and begins /priv/<domain>/<uname>
                   6532:          the path will be that portion of the $context argument.
                   6533:          Otherwise the path will be for the author space of the current
                   6534:          user when the current role is author, or for that of the 
                   6535:          co-author/assistant co-author space when the current role 
                   6536:          is co-author or assistant co-author.
1.832     bisitz   6537: 
                   6538: =cut
                   6539: 
                   6540: sub authorspace {
1.1028    raeburn  6541:     my ($url) = @_;
                   6542:     if ($url ne '') {
                   6543:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6544:            return $1;
                   6545:         }
                   6546:     }
1.832     bisitz   6547:     my $caname = '';
1.1024    www      6548:     my $cadom = '';
1.1028    raeburn  6549:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6550:         ($cadom,$caname) =
1.832     bisitz   6551:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6552:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6553:         $caname = $env{'user.name'};
1.1024    www      6554:         $cadom = $env{'user.domain'};
1.832     bisitz   6555:     }
1.1028    raeburn  6556:     if (($caname ne '') && ($cadom ne '')) {
                   6557:         return "/priv/$cadom/$caname/";
                   6558:     }
                   6559:     return;
1.832     bisitz   6560: }
                   6561: 
                   6562: ##############################################
                   6563: =pod
                   6564: 
1.822     bisitz   6565: =item * &head_subbox()
                   6566: 
                   6567: Inputs: $content (contains HTML code with page functions, etc.)
                   6568: 
                   6569: Returns: HTML div with $content
                   6570:          To be included in page header
                   6571: 
                   6572: =cut
                   6573: 
                   6574: sub head_subbox {
                   6575:     my ($content)=@_;
                   6576:     my $output =
1.993     raeburn  6577:         '<div class="LC_head_subbox">'
1.822     bisitz   6578:        .$content
                   6579:        .'</div>'
                   6580: }
                   6581: 
                   6582: ##############################################
                   6583: =pod
                   6584: 
                   6585: =item * &CSTR_pageheader()
                   6586: 
1.1026    raeburn  6587: Input: (optional) filename from which breadcrumb trail is built.
                   6588:        In most cases no input as needed, as $env{'request.filename'}
                   6589:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6590:        frameset flag
                   6591:        If page header is being requested for use in a frameset, then
                   6592:        the second (option) argument -- frameset will be true, and
                   6593:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6594:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6595:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6596: 
                   6597: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6598:          To be included on Authoring Space pages
1.822     bisitz   6599: 
                   6600: =cut
                   6601: 
                   6602: sub CSTR_pageheader {
1.1407    raeburn  6603:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6604:     if ($trailfile eq '') {
                   6605:         $trailfile = $env{'request.filename'};
                   6606:     }
                   6607: 
                   6608: # this is for resources; directories have customtitle, and crumbs
                   6609: # and select recent are created in lonpubdir.pm
                   6610: 
                   6611:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6612:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6613:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6614:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6615:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6616: 
                   6617:     my $parentpath = '';
                   6618:     my $lastitem = '';
                   6619:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6620:         $parentpath = $1;
                   6621:         $lastitem = $2;
                   6622:     } else {
                   6623:         $lastitem = $thisdisfn;
                   6624:     }
1.921     bisitz   6625: 
1.1406    raeburn  6626:     my $crsauthor;
1.1246    raeburn  6627:     if (($env{'request.course.id'}) &&
                   6628:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6629:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6630:         $crsauthor = 1;
1.1406    raeburn  6631:         if ($title eq '') {
                   6632:             $title = &mt('Course Authoring Space');
                   6633:         }
                   6634:     } elsif ($title eq '') {
1.1246    raeburn  6635:         $title = &mt('Authoring Space');
                   6636:     }
                   6637: 
1.1379    raeburn  6638:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6639:     if ($frameset) {
                   6640:         $target = ' target="_parent"';
                   6641:         $crumbtarget = '_parent';
                   6642:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6643:         $target = '';
                   6644:         $crumbtarget = '';
1.1379    raeburn  6645:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6646:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6647:         $crumbtarget = $env{'request.deeplink.target'};
                   6648:     }
1.1313    raeburn  6649: 
1.921     bisitz   6650:     my $output =
1.1407    raeburn  6651:          '<div>'
1.822     bisitz   6652:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6653:         .'<b>'.$title.'</b> '
1.1314    raeburn  6654:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6655:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6656: 
                   6657:     if ($lastitem) {
                   6658:         $output .=
                   6659:              '<span class="LC_filename">'
                   6660:             .$lastitem
                   6661:             .'</span>';
                   6662:     }
1.1245    raeburn  6663: 
1.1246    raeburn  6664:     if ($crsauthor) {
1.1379    raeburn  6665:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6666:     } else {
                   6667:         $output .=
                   6668:              '<br />'
1.1314    raeburn  6669:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6670:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6671:             .'</form>'
1.1379    raeburn  6672:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6673:     }
1.1407    raeburn  6674:     $output .= '</div>';
1.921     bisitz   6675: 
                   6676:     return $output;
1.822     bisitz   6677: }
                   6678: 
1.1419    raeburn  6679: ##############################################
                   6680: =pod
                   6681: 
                   6682: =item * &nocodemirror()
                   6683: 
                   6684: Input: None
                   6685: 
                   6686: Returns: 1 if CodeMirror is deactivated based on
                   6687:          user's preference, or domain default,
                   6688:          if user indicated use of default.
                   6689: 
                   6690: =cut
                   6691: 
1.1416    raeburn  6692: sub nocodemirror {
                   6693:     my $nocodem = $env{'environment.nocodemirror'};
                   6694:     unless ($nocodem) {
                   6695:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6696:         if ($domdefs{'nocodemirror'}) {
                   6697:             $nocodem = 'yes';
                   6698:         }
                   6699:     }
1.1417    raeburn  6700:     if ($nocodem eq 'yes') {
                   6701:         return 1;
                   6702:     }
                   6703:     return;
1.1416    raeburn  6704: }
                   6705: 
1.1419    raeburn  6706: ##############################################
                   6707: =pod
                   6708: 
                   6709: =item * &permitted_editors()
                   6710: 
1.1422    raeburn  6711: Input: $uri (optional)
1.1419    raeburn  6712: 
                   6713: Returns: %editors hash in which keys are editors
1.1429    raeburn  6714:          permitted in current Authoring Space,
                   6715:          or in current course for web pages
                   6716:          created in a course.
                   6717: 
1.1419    raeburn  6718:          Value for each key is 1. Possible keys
1.1429    raeburn  6719:          are: edit, xml, and daxe.
                   6720: 
                   6721:          For a regular Authoring Space, if no specific
1.1419    raeburn  6722:          set of editors has been set for the Author
                   6723:          who owns the Authoring Space, then the
                   6724:          domain default will be used.  If no domain
                   6725:          default has been set, then the keys will be
                   6726:          edit and xml.
                   6727: 
1.1429    raeburn  6728:          For a course author, or for web pages created
                   6729:          in a course, if no specific set of editors has
                   6730:          been set for the course, then the domain
                   6731:          course default will be used. If no domain
                   6732:          course default has been set, then the keys
                   6733:          will be edit and xml.
                   6734: 
1.1419    raeburn  6735: =cut
                   6736: 
1.1418    raeburn  6737: sub permitted_editors {
1.1422    raeburn  6738:     my ($uri) = @_;
1.1429    raeburn  6739:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6740:     if ($env{'request.role'} =~ m{^au\./}) {
                   6741:         $is_author = 1;
                   6742:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6743:         ($audom,$auname) = ($1,$2);
                   6744:         if (($audom ne '') && ($auname ne '')) {
                   6745:             if (($env{'user.domain'} eq $audom) &&
                   6746:                 ($env{'user.name'} eq $auname)) {
                   6747:                 $is_author = 1;
                   6748:             } else {
                   6749:                 $is_coauthor = 1;
                   6750:             }
                   6751:         }
                   6752:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6753:         my ($cdom,$cnum);
                   6754:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6755:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6756:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6757:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6758:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6759:             $is_course = 1;
                   6760:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6761:             ($audom,$auname) = ($1,$2);
                   6762:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6763:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6764:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6765:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6766:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6767:             $is_course = 1;
                   6768:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6769:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6770:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6771:         }
1.1429    raeburn  6772:         unless ($is_course) {
                   6773:             if (($audom ne '') && ($auname ne '')) {
                   6774:                 if (($env{'user.domain'} eq $audom) &&
                   6775:                     ($env{'user.name'} eq $auname)) {
                   6776:                     $is_author = 1;
                   6777:                 } else {
                   6778:                     $is_coauthor = 1;
                   6779:                 }
1.1418    raeburn  6780:             }
                   6781:         }
                   6782:     }
                   6783:     if ($is_author) {
                   6784:         if (exists($env{'environment.editors'})) {
                   6785:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6786:         } else {
                   6787:             %editors = ( edit => 1,
                   6788:                          xml => 1,
                   6789:                        );
                   6790:         }
                   6791:     } elsif ($is_coauthor) {
                   6792:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6793:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6794:         } else {
                   6795:             %editors = ( edit => 1,
                   6796:                          xml => 1,
                   6797:                        );
                   6798:         }
1.1429    raeburn  6799:     } elsif ($is_course) {
                   6800:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6801:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6802:         } else {
                   6803:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6804:             if (exists($domdefaults{'crseditors'})) {
                   6805:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6806:             } else {
                   6807:                 %editors = ( edit => 1,
                   6808:                              xml => 1,
                   6809:                            );
                   6810:             }
                   6811:         }
1.1418    raeburn  6812:     } else {
                   6813:         %editors = ( edit => 1,
                   6814:                      xml => 1,
                   6815:                    );
                   6816:     }
                   6817:     return %editors;
                   6818: }
                   6819: 
1.60      matthew  6820: ###############################################
                   6821: ###############################################
                   6822: 
                   6823: =pod
                   6824: 
1.112     bowersj2 6825: =back
                   6826: 
1.549     albertel 6827: =head1 HTML Helpers
1.112     bowersj2 6828: 
                   6829: =over 4
                   6830: 
                   6831: =item * &bodytag()
1.60      matthew  6832: 
                   6833: Returns a uniform header for LON-CAPA web pages.
                   6834: 
                   6835: Inputs: 
                   6836: 
1.112     bowersj2 6837: =over 4
                   6838: 
                   6839: =item * $title, A title to be displayed on the page.
                   6840: 
                   6841: =item * $function, the current role (can be undef).
                   6842: 
                   6843: =item * $addentries, extra parameters for the <body> tag.
                   6844: 
                   6845: =item * $bodyonly, if defined, only return the <body> tag.
                   6846: 
                   6847: =item * $domain, if defined, force a given domain.
                   6848: 
                   6849: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6850:             text interface only)
1.60      matthew  6851: 
1.814     bisitz   6852: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6853:                      navigational links
1.317     albertel 6854: 
1.338     albertel 6855: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6856: 
1.460     albertel 6857: =item * $args, optional argument valid values are
                   6858:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6859:             use_absolute     -> for external resource or syllabus, this will
                   6860:                                 contain https://<hostname> if server uses
                   6861:                                 https (as per hosts.tab), but request is for http
                   6862:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6863: 
1.1096    raeburn  6864: =item * $advtoolsref, optional argument, ref to an array containing
                   6865:             inlineremote items to be added in "Functions" menu below
                   6866:             breadcrumbs.
                   6867: 
1.1316    raeburn  6868: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6869:             course, if LON-CAPA is in LTI Provider context. Value is
                   6870:             the scope of use, i.e., launch was for access to a single, a map
                   6871:             or the entire course.
                   6872: 
                   6873: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6874:             context, this will contain the URL for the landing item in
                   6875:             the course, after launch from an LTI Consumer
                   6876: 
1.1318    raeburn  6877: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6878:             context, this will contain a reference to hash of items
                   6879:             to be included in the page header and/or inline menu.
                   6880: 
1.1385    raeburn  6881: =item * $menucoll, optional argument, if specific menu collection is in
                   6882:             effect, either set as the default for the course, or set for
                   6883:             the deeplink paramater for $env{'request.deeplink.login'}
                   6884:             then $menucoll will be the number of that collection. 
                   6885: 
                   6886: =item * $menuref, optional argument, reference to a hash, containing the
                   6887:             menu options included for the menu in effect, based on the
                   6888:             configuration for the numbered menu collection in use.  
                   6889: 
                   6890: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6891:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6892:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6893:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6894:             being called a second time.
                   6895: 
1.112     bowersj2 6896: =back
                   6897: 
1.60      matthew  6898: Returns: A uniform header for LON-CAPA web pages.  
                   6899: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6900: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6901: other decorations will be returned.
                   6902: 
                   6903: =cut
                   6904: 
1.54      www      6905: sub bodytag {
1.831     bisitz   6906:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6907:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6908:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6909: 
1.954     raeburn  6910:     my $public;
                   6911:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6912:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6913:         $public = 1;
                   6914:     }
1.460     albertel 6915:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6916:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6917:     my $hostname = $args->{'hostname'};
1.339     albertel 6918: 
1.183     matthew  6919:     $function = &get_users_function() if (!$function);
1.339     albertel 6920:     my $font =   &designparm($function.'.font',$domain);
                   6921:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6922: 
1.803     bisitz   6923:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6924: 		   'bgcolor' => $pgbg,
1.339     albertel 6925: 		   'text'    => $font,
                   6926:                    'alink'   => &designparm($function.'.alink',$domain),
                   6927: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6928: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6929:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6930: 
1.63      www      6931:  # role and realm
1.1178    raeburn  6932:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6933:     if ($realm) {
                   6934:         $realm = '/'.$realm;
                   6935:     }
1.1357    raeburn  6936:     if ($role eq 'ca') {
1.479     albertel 6937:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6938:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6939:     } 
1.55      www      6940: # realm
1.1357    raeburn  6941:     my ($cid,$sec);
1.258     albertel 6942:     if ($env{'request.course.id'}) {
1.1357    raeburn  6943:         $cid = $env{'request.course.id'};
                   6944:         if ($env{'request.course.sec'}) {
                   6945:             $sec = $env{'request.course.sec'};
                   6946:         }
                   6947:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6948:         if (&Apache::lonnet::is_course($1,$2)) {
                   6949:             $cid = $1.'_'.$2;
                   6950:             $sec = $3;
                   6951:         }
                   6952:     }
                   6953:     if ($cid) {
1.378     raeburn  6954:         if ($env{'request.role'} !~ /^cr/) {
                   6955:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6956:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6957:             if ($env{'request.role.desc'}) {
                   6958:                 $role = $env{'request.role.desc'};
                   6959:             } else {
                   6960:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6961:             }
1.1257    raeburn  6962:         } else {
                   6963:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6964:         }
1.1357    raeburn  6965:         if ($sec) {
                   6966:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6967:         }   
1.1357    raeburn  6968: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6969:     } else {
                   6970:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6971:     }
1.433     albertel 6972: 
1.438     albertel 6973:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6974: 
1.101     www      6975: # construct main body tag
1.359     albertel 6976:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6977: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6978: 
1.1131    raeburn  6979:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6980: 
1.1130    raeburn  6981:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6982:         return $bodytag;
1.1130    raeburn  6983:     }
1.359     albertel 6984: 
1.954     raeburn  6985:     if ($public) {
1.433     albertel 6986: 	undef($role);
                   6987:     }
1.1318    raeburn  6988: 
1.1359    raeburn  6989:     my $showcrstitle = 1;
1.1357    raeburn  6990:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6991:         if (ref($ltimenu) eq 'HASH') {
                   6992:             unless ($ltimenu->{'role'}) {
                   6993:                 undef($role);
                   6994:             }
                   6995:             unless ($ltimenu->{'coursetitle'}) {
1.1359    raeburn  6996:                 $showcrstitle = 0;
                   6997:             }
                   6998:         }
                   6999:     } elsif (($cid) && ($menucoll)) {
                   7000:         if (ref($menuref) eq 'HASH') {
                   7001:             unless ($menuref->{'role'}) {
                   7002:                 undef($role);
                   7003:             }
                   7004:             unless ($menuref->{'crs'}) {
                   7005:                 $showcrstitle = 0;
1.1318    raeburn  7006:             }
                   7007:         }
                   7008:     }
                   7009: 
1.762     bisitz   7010:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 7011:     #
                   7012:     # Extra info if you are the DC
                   7013:     my $dc_info = '';
1.1359    raeburn  7014:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  7015:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  7016:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      7017:         $dc_info =~ s/\s+$//;
1.359     albertel 7018:     }
                   7019: 
1.1237    raeburn  7020:     my $crstype;
1.1357    raeburn  7021:     if ($cid) {
                   7022:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  7023:     } elsif ($args->{'crstype'}) {
                   7024:         $crstype = $args->{'crstype'};
                   7025:     }
                   7026:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   7027:         undef($role);
                   7028:     } else {
1.1242    raeburn  7029:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  7030:     }
1.853     droeschl 7031: 
1.903     droeschl 7032:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7033: 
                   7034:         #    if ($env{'request.state'} eq 'construct') {
                   7035:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7036:         #    }
                   7037: 
1.1440    raeburn  7038:         my $need_endlcint;
                   7039:         unless ($args->{'switchserver'}) {
                   7040:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7041:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7042:             $need_endlcint = 1;
                   7043:         }
1.359     albertel 7044: 
1.1427    raeburn  7045:         my $collapsible;
1.1423    raeburn  7046:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7047:             $collapsible = 1;
                   7048:             my ($menustate,$tiptext,$divclass);
                   7049:             if ($args->{'start_collapsed'}) {
                   7050:                 $menustate = 'collapsed';
                   7051:                 $tiptext = 'display';
                   7052:                 $divclass = 'hidden';
                   7053:             } else {
                   7054:                 $menustate = 'expanded';
                   7055:                 $tiptext = 'hide';
                   7056:                 $divclass = 'shown';
                   7057:             }
                   7058:             my $alttext = &mt('menu state: '.$menustate);
                   7059:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7060:             $bodytag .= <<"END";
1.1461    raeburn  7061: <div id="LC_expandingContainer" style="display:inline;" role="navigation">
1.1421    raeburn  7062: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7063: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   7064: <div class="LC_menus_content $divclass">
1.1421    raeburn  7065: END
                   7066:         }
1.1318    raeburn  7067:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7068:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7069:                                                               $args->{'links_disabled'},
1.1421    raeburn  7070:                                                               $args->{'links_target'},
1.1427    raeburn  7071:                                                               $collapsible);
1.1454    raeburn  7072:             my $labeltext = &HTML::Entities::encode(&mt('Primary links'));
1.1318    raeburn  7073:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7074:                 if ($dc_info) {
                   7075:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7076:                 }
1.1456    raeburn  7077:                 $bodytag .= qq|<div id="LC_nav_bar" role="navigation" aria-label="$labeltext">$left $role</div>|;
1.1454    raeburn  7078:                 unless (($realm eq '') && ($dc_info eq '')) {
                   7079:                     $bodytag .= qq|<div id="LC_realm" role="complementary"><em>$realm</em> $dc_info</div>|;
                   7080:                 }
1.1440    raeburn  7081:                 if ($need_endlcint) {
                   7082:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7083:                 }
1.1318    raeburn  7084:                 return $bodytag;
                   7085:             }
1.894     droeschl 7086: 
1.1457    raeburn  7087:             $bodytag .= '<div class="LC_landmark" style="margin: 3px 0 0 0;" role="navigation" aria-label="'.$labeltext.'">';
1.1318    raeburn  7088:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7089:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7090:             }
1.916     droeschl 7091: 
1.1454    raeburn  7092:             $bodytag .= $right.'</div>';
1.852     droeschl 7093: 
1.1318    raeburn  7094:             if ($dc_info) {
                   7095:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7096:             }
1.1454    raeburn  7097:             unless (($realm eq '') && ($dc_info eq '')) {
1.1457    raeburn  7098:                 $bodytag .= qq|<div id="LC_realm" role="complementary">$realm $dc_info</div>|;
1.1454    raeburn  7099:             }
1.1457    raeburn  7100:             $bodytag .= qq|<div style="clear: both; margin: 5px 0 0 0;"></div>|;
1.917     raeburn  7101:         }
1.916     droeschl 7102: 
1.1169    raeburn  7103:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7104:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7105:             if ($need_endlcint) {
                   7106:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7107:             }
1.1168    raeburn  7108:             return $bodytag;
                   7109:         }
1.1169    raeburn  7110:         #don't show menus for public users
1.954     raeburn  7111:         if (!$public){
1.1318    raeburn  7112:             unless ($args->{'no_inline_menu'}) {
1.1459    raeburn  7113:                 $bodytag .= '<div class="LC_landmark" role="navigation" aria-label="Secondary Links">'.
                   7114:                             Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7115:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7116:                                                             $menucoll,$menuref,
1.1380    raeburn  7117:                                                             $args->{'links_disabled'},
1.1459    raeburn  7118:                                                             $args->{'links_target'}).
1.1460    raeburn  7119:                             '</div>';
1.1318    raeburn  7120:             }
1.903     droeschl 7121:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7122:             if ($need_endlcint) {
                   7123:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7124:             }
1.920     raeburn  7125:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7126:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7127:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7128:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7129:             } elsif ($forcereg) {
                   7130:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7131:                                 $args->{'group'},$args->{'hide_buttons'},
                   7132:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7133:             } else {
1.1459    raeburn  7134:                 $bodytag .=
1.1096    raeburn  7135:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7136:                                                         $forcereg,$args->{'group'},
                   7137:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7138:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7139:             }
1.1440    raeburn  7140:         } else {
                   7141:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7142:             # menu. Especially needed for publicly accessible resources.
1.1459    raeburn  7143:             $bodytag .= '<hr style="clear:both" role="complementary" />';
1.1440    raeburn  7144:             if ($need_endlcint) {
                   7145:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7146:             }
1.235     raeburn  7147:         }
1.1423    raeburn  7148:         if ($args->{'collapsible_header'} ne '') {
                   7149:             $bodytag .= $args->{'collapsible_header'}.
                   7150:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7151:                         '</div></div>';
                   7152:         }
1.235     raeburn  7153:         return $bodytag;
1.182     matthew  7154: }
                   7155: 
1.917     raeburn  7156: sub dc_courseid_toggle {
                   7157:     my ($dc_info) = @_;
1.980     raeburn  7158:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7159:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7160:            &mt('(More ...)').'</a></span>'.
                   7161:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7162: }
                   7163: 
1.330     albertel 7164: sub make_attr_string {
                   7165:     my ($register,$attr_ref) = @_;
                   7166: 
                   7167:     if ($attr_ref && !ref($attr_ref)) {
                   7168: 	die("addentries Must be a hash ref ".
                   7169: 	    join(':',caller(1))." ".
                   7170: 	    join(':',caller(0))." ");
                   7171:     }
                   7172: 
                   7173:     if ($register) {
1.339     albertel 7174: 	my ($on_load,$on_unload);
                   7175: 	foreach my $key (keys(%{$attr_ref})) {
                   7176: 	    if      (lc($key) eq 'onload') {
                   7177: 		$on_load.=$attr_ref->{$key}.';';
                   7178: 		delete($attr_ref->{$key});
                   7179: 
                   7180: 	    } elsif (lc($key) eq 'onunload') {
                   7181: 		$on_unload.=$attr_ref->{$key}.';';
                   7182: 		delete($attr_ref->{$key});
                   7183: 	    }
                   7184: 	}
1.953     droeschl 7185: 	$attr_ref->{'onload'}  = $on_load;
                   7186: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7187:     }
1.339     albertel 7188: 
1.330     albertel 7189:     my $attr_string;
1.1159    raeburn  7190:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7191: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7192:     }
                   7193:     return $attr_string;
                   7194: }
                   7195: 
                   7196: 
1.182     matthew  7197: ###############################################
1.251     albertel 7198: ###############################################
                   7199: 
                   7200: =pod
                   7201: 
                   7202: =item * &endbodytag()
                   7203: 
                   7204: Returns a uniform footer for LON-CAPA web pages.
                   7205: 
1.635     raeburn  7206: Inputs: 1 - optional reference to an args hash
                   7207: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7208: a 'Continue' link is not displayed if the page contains an
                   7209: internal redirect in the <head></head> section,
                   7210: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7211: 
                   7212: =cut
                   7213: 
                   7214: sub endbodytag {
1.635     raeburn  7215:     my ($args) = @_;
1.1080    raeburn  7216:     my $endbodytag;
                   7217:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7218:         $endbodytag='</body>';
                   7219:     }
1.315     albertel 7220:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7221:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7222:             my ($endbodyjs,$idattr);
                   7223:             if ($env{'internal.head.to_opener'}) {
                   7224:                 my $linkid = 'LC_continue_link';
                   7225:                 $idattr = ' id="'.$linkid.'"';
                   7226:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7227:                 $endbodyjs=<<ENDJS;
                   7228: <script type="text/javascript">
                   7229: // <![CDATA[
                   7230: function ebFunction(evt) {
                   7231:     evt.preventDefault();
                   7232:     var dest = '$redirect_for_js';
                   7233:     if (window.opener != null && !window.opener.closed) {
                   7234:         window.opener.location.href=dest;
                   7235:         window.close();
                   7236:     } else {
                   7237:         window.location.href=dest;
                   7238:     }
                   7239:     return false;
                   7240: }
                   7241: 
                   7242: \$(document).ready(function () {
                   7243:   if (document.getElementById('$linkid')) {
                   7244:     var clickelem = document.getElementById('$linkid');
                   7245:     clickelem.addEventListener('click',ebFunction,false);
                   7246:   }
                   7247: });
                   7248: // ]]>
                   7249: </script>
                   7250: ENDJS
                   7251:             }
1.635     raeburn  7252: 	    $endbodytag=
1.1386    raeburn  7253: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7254: 	        &mt('Continue').'</a>'.
                   7255: 	        $endbodytag;
                   7256:         }
1.315     albertel 7257:     }
1.1411    raeburn  7258:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7259:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7260:     }
1.251     albertel 7261:     return $endbodytag;
                   7262: }
                   7263: 
1.352     albertel 7264: =pod
                   7265: 
                   7266: =item * &standard_css()
                   7267: 
                   7268: Returns a style sheet
                   7269: 
                   7270: Inputs: (all optional)
                   7271:             domain         -> force to color decorate a page for a specific
                   7272:                                domain
                   7273:             function       -> force usage of a specific rolish color scheme
                   7274:             bgcolor        -> override the default page bgcolor
                   7275: 
                   7276: =cut
                   7277: 
1.343     albertel 7278: sub standard_css {
1.345     albertel 7279:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7280:     $function  = &get_users_function() if (!$function);
                   7281:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7282:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7283:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7284: #second colour for later usage
1.345     albertel 7285:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7286:     my $pgbg_or_bgcolor =
                   7287: 	         $bgcolor ||
1.352     albertel 7288: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7289:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7290:     my $alink  = &designparm($function.'.alink', $domain);
                   7291:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7292:     my $link   = &designparm($function.'.link',  $domain);
                   7293: 
1.602     albertel 7294:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7295:     my $mono                 = 'monospace';
1.850     bisitz   7296:     my $data_table_head      = $sidebg;
                   7297:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7298:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7299:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7300:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7301:     my $mail_new             = '#FFBB77';
                   7302:     my $mail_new_hover       = '#DD9955';
                   7303:     my $mail_read            = '#BBBB77';
                   7304:     my $mail_read_hover      = '#999944';
                   7305:     my $mail_replied         = '#AAAA88';
                   7306:     my $mail_replied_hover   = '#888855';
                   7307:     my $mail_other           = '#99BBBB';
                   7308:     my $mail_other_hover     = '#669999';
1.391     albertel 7309:     my $table_header         = '#DDDDDD';
1.489     raeburn  7310:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7311:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7312:     my $button_hover         = '#BF2317';
1.392     albertel 7313: 
1.608     albertel 7314:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7315:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7316:                                              : '0 3px 0 4px';
1.448     albertel 7317: 
1.523     albertel 7318: 
1.343     albertel 7319:     return <<END;
1.947     droeschl 7320: 
                   7321: /* needed for iframe to allow 100% height in FF */
                   7322: body, html { 
                   7323:     margin: 0;
                   7324:     padding: 0 0.5%;
                   7325:     height: 99%; /* to avoid scrollbars */
                   7326: }
                   7327: 
1.795     www      7328: body {
1.911     bisitz   7329:   font-family: $sans;
                   7330:   line-height:130%;
                   7331:   font-size:0.83em;
                   7332:   color:$font;
1.1436    raeburn  7333:   background-color: $pgbg_or_bgcolor;
1.795     www      7334: }
                   7335: 
1.959     onken    7336: a:focus,
                   7337: a:focus img {
1.795     www      7338:   color: red;
                   7339: }
1.698     harmsja  7340: 
1.911     bisitz   7341: form, .inline {
                   7342:   display: inline;
1.795     www      7343: }
1.721     harmsja  7344: 
1.1453    raeburn  7345: .LC_landmark {
                   7346:   margin: 0;
                   7347:   padding: 0;
                   7348:   border: none;
                   7349: }
                   7350: 
1.1443    raeburn  7351: .LC_visually_hidden:not(:focus):not(:active) {
                   7352:     clip-path: inset(50%);
                   7353:     height: 1px;
                   7354:     overflow: hidden;
                   7355:     position: absolute;
                   7356:     white-space: nowrap;
                   7357:     width: 1px;
                   7358:     display: inline;
                   7359: }
                   7360: 
1.1453    raeburn  7361: .LC_heading_2 {
                   7362:   font-size: 1.17em;
                   7363: }
                   7364: 
1.1458    raeburn  7365: .LC_heading_3 {
                   7366:   font-size: 1.0em;
                   7367: }
                   7368: 
1.1472    raeburn  7369: h1.LC_search_results {
                   7370:   font-size: 1.0em;
                   7371:   font-weight: normal;
                   7372: }
                   7373: 
1.1421    raeburn  7374: .LC_menus_content.shown{
1.1428    raeburn  7375:   display: block;
1.1421    raeburn  7376: }
                   7377: 
                   7378: .LC_menus_content.hidden {
                   7379:   display: none;
                   7380: }
                   7381: 
1.795     www      7382: .LC_right {
1.911     bisitz   7383:   text-align:right;
1.795     www      7384: }
                   7385: 
1.1470    raeburn  7386: .LC_left {
                   7387:   text-align:left;
                   7388: }
                   7389: 
1.1449    raeburn  7390: .LC_center {
                   7391:   text-align:center;
                   7392: }
                   7393: 
1.795     www      7394: .LC_middle {
1.911     bisitz   7395:   vertical-align:middle;
1.795     www      7396: }
1.721     harmsja  7397: 
1.1130    raeburn  7398: .LC_floatleft {
                   7399:   float: left;
                   7400: }
                   7401: 
                   7402: .LC_floatright {
                   7403:   float: right;
                   7404: }
                   7405: 
1.911     bisitz   7406: .LC_400Box {
                   7407:   width:400px;
                   7408: }
1.721     harmsja  7409: 
1.1421    raeburn  7410: #LC_collapsible_separator {
                   7411:     border: 1px solid black;
                   7412:     width: 99.9%;
                   7413:     height: 0px;
                   7414: }
                   7415: 
1.947     droeschl 7416: .LC_iframecontainer {
                   7417:     width: 98%;
                   7418:     margin: 0;
                   7419:     position: fixed;
                   7420:     top: 8.5em;
                   7421:     bottom: 0;
                   7422: }
                   7423: 
                   7424: .LC_iframecontainer iframe{
                   7425:     border: none;
                   7426:     width: 100%;
                   7427:     height: 100%;
                   7428: }
                   7429: 
1.778     bisitz   7430: .LC_filename {
                   7431:   font-family: $mono;
                   7432:   white-space:pre;
1.921     bisitz   7433:   font-size: 120%;
1.778     bisitz   7434: }
                   7435: 
                   7436: .LC_fileicon {
                   7437:   border: none;
                   7438:   height: 1.3em;
                   7439:   vertical-align: text-bottom;
                   7440:   margin-right: 0.3em;
                   7441:   text-decoration:none;
                   7442: }
                   7443: 
1.1008    www      7444: .LC_setting {
                   7445:   text-decoration:underline;
                   7446: }
                   7447: 
1.350     albertel 7448: .LC_error {
                   7449:   color: red;
                   7450: }
1.795     www      7451: 
1.1097    bisitz   7452: .LC_warning {
                   7453:   color: darkorange;
                   7454: }
                   7455: 
1.457     albertel 7456: .LC_diff_removed {
1.733     bisitz   7457:   color: red;
1.394     albertel 7458: }
1.532     albertel 7459: 
                   7460: .LC_info,
1.457     albertel 7461: .LC_success,
                   7462: .LC_diff_added {
1.350     albertel 7463:   color: green;
                   7464: }
1.795     www      7465: 
1.802     bisitz   7466: div.LC_confirm_box {
                   7467:   background-color: #FAFAFA;
                   7468:   border: 1px solid $lg_border_color;
                   7469:   margin-right: 0;
                   7470:   padding: 5px;
                   7471: }
                   7472: 
                   7473: div.LC_confirm_box .LC_error img,
                   7474: div.LC_confirm_box .LC_success img {
                   7475:   vertical-align: middle;
                   7476: }
                   7477: 
1.1242    raeburn  7478: .LC_maxwidth {
                   7479:   max-width: 100%;
                   7480:   height: auto;
                   7481: }
                   7482: 
1.1243    raeburn  7483: .LC_textsize_mobile {
                   7484:   \@media only screen and (max-device-width: 480px) {
                   7485:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7486:   }
                   7487: }
                   7488: 
1.440     albertel 7489: .LC_icon {
1.771     droeschl 7490:   border: none;
1.790     droeschl 7491:   vertical-align: middle;
1.771     droeschl 7492: }
                   7493: 
1.543     albertel 7494: .LC_docs_spacer {
                   7495:   width: 25px;
                   7496:   height: 1px;
1.771     droeschl 7497:   border: none;
1.543     albertel 7498: }
1.346     albertel 7499: 
1.532     albertel 7500: .LC_internal_info {
1.735     bisitz   7501:   color: #999999;
1.532     albertel 7502: }
                   7503: 
1.794     www      7504: .LC_discussion {
1.1050    www      7505:   background: $data_table_dark;
1.911     bisitz   7506:   border: 1px solid black;
                   7507:   margin: 2px;
1.794     www      7508: }
                   7509: 
                   7510: .LC_disc_action_left {
1.1050    www      7511:   background: $sidebg;
1.911     bisitz   7512:   text-align: left;
1.1050    www      7513:   padding: 4px;
                   7514:   margin: 2px;
1.794     www      7515: }
                   7516: 
                   7517: .LC_disc_action_right {
1.1050    www      7518:   background: $sidebg;
1.911     bisitz   7519:   text-align: right;
1.1050    www      7520:   padding: 4px;
                   7521:   margin: 2px;
1.794     www      7522: }
                   7523: 
                   7524: .LC_disc_new_item {
1.911     bisitz   7525:   background: white;
                   7526:   border: 2px solid red;
1.1050    www      7527:   margin: 4px;
                   7528:   padding: 4px;
1.794     www      7529: }
                   7530: 
                   7531: .LC_disc_old_item {
1.911     bisitz   7532:   background: white;
1.1050    www      7533:   margin: 4px;
                   7534:   padding: 4px;
1.794     www      7535: }
                   7536: 
1.1468    raeburn  7537: .LC_pastsubmission {
1.458     albertel 7538:   border: 1px solid black;
                   7539:   margin: 2px;
1.1468    raeburn  7540:   padding: 2px;
1.458     albertel 7541: }
                   7542: 
1.924     bisitz   7543: table#LC_menubuttons {
1.345     albertel 7544:   width: 100%;
                   7545:   background: $pgbg;
1.392     albertel 7546:   border: 2px;
1.402     albertel 7547:   border-collapse: separate;
1.803     bisitz   7548:   padding: 0;
1.345     albertel 7549: }
1.392     albertel 7550: 
1.801     tempelho 7551: table#LC_title_bar a {
                   7552:   color: $fontmenu;
                   7553: }
1.836     bisitz   7554: 
1.807     droeschl 7555: table#LC_title_bar {
1.819     tempelho 7556:   clear: both;
1.836     bisitz   7557:   display: none;
1.807     droeschl 7558: }
                   7559: 
1.795     www      7560: table#LC_title_bar,
1.933     droeschl 7561: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7562: table#LC_title_bar.LC_with_remote {
1.359     albertel 7563:   width: 100%;
1.392     albertel 7564:   border-color: $pgbg;
                   7565:   border-style: solid;
                   7566:   border-width: $border;
1.379     albertel 7567:   background: $pgbg;
1.801     tempelho 7568:   color: $fontmenu;
1.392     albertel 7569:   border-collapse: collapse;
1.803     bisitz   7570:   padding: 0;
1.819     tempelho 7571:   margin: 0;
1.359     albertel 7572: }
1.795     www      7573: 
1.933     droeschl 7574: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7575:     margin: 0;
                   7576:     padding: 0;
1.933     droeschl 7577:     position: relative;
                   7578:     list-style: none;
1.913     droeschl 7579: }
1.933     droeschl 7580: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7581:     display: inline;
                   7582: }
1.933     droeschl 7583: 
                   7584: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7585:     padding: 0;
1.933     droeschl 7586:     margin: 0;
                   7587:     float: left;
1.913     droeschl 7588: }
1.933     droeschl 7589: .LC_breadcrumb_tools_tools {
                   7590:     padding: 0;
                   7591:     margin: 0;
1.913     droeschl 7592:     float: right;
                   7593: }
                   7594: 
1.1240    raeburn  7595: .LC_placement_prog {
                   7596:     padding-right: 20px;
                   7597:     font-weight: bold;
                   7598:     font-size: 90%;
                   7599: }
                   7600: 
1.359     albertel 7601: table#LC_title_bar td {
                   7602:   background: $tabbg;
                   7603: }
1.795     www      7604: 
1.911     bisitz   7605: table#LC_menubuttons img {
1.803     bisitz   7606:   border: none;
1.346     albertel 7607: }
1.795     www      7608: 
1.842     droeschl 7609: .LC_breadcrumbs_component {
1.911     bisitz   7610:   float: right;
                   7611:   margin: 0 1em;
1.357     albertel 7612: }
1.842     droeschl 7613: .LC_breadcrumbs_component img {
1.911     bisitz   7614:   vertical-align: middle;
1.777     tempelho 7615: }
1.795     www      7616: 
1.1243    raeburn  7617: .LC_breadcrumbs_hoverable {
                   7618:   background: $sidebg;
                   7619: }
                   7620: 
1.383     albertel 7621: td.LC_table_cell_checkbox {
                   7622:   text-align: center;
                   7623: }
1.795     www      7624: 
                   7625: .LC_fontsize_small {
1.911     bisitz   7626:   font-size: 70%;
1.705     tempelho 7627: }
                   7628: 
1.844     bisitz   7629: #LC_breadcrumbs {
1.911     bisitz   7630:   clear:both;
                   7631:   background: $sidebg;
                   7632:   border-bottom: 1px solid $lg_border_color;
                   7633:   line-height: 2.5em;
1.933     droeschl 7634:   overflow: hidden;
1.911     bisitz   7635:   margin: 0;
                   7636:   padding: 0;
1.995     raeburn  7637:   text-align: left;
1.819     tempelho 7638: }
1.862     bisitz   7639: 
1.1098    bisitz   7640: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7641:   clear:both;
                   7642:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7643:   border: 1px solid $sidebg;
1.1098    bisitz   7644:   margin: 0 0 10px 0;
1.966     bisitz   7645:   padding: 3px;
1.995     raeburn  7646:   text-align: left;
1.822     bisitz   7647: }
                   7648: 
1.795     www      7649: .LC_fontsize_medium {
1.911     bisitz   7650:   font-size: 85%;
1.705     tempelho 7651: }
                   7652: 
1.795     www      7653: .LC_fontsize_large {
1.911     bisitz   7654:   font-size: 120%;
1.705     tempelho 7655: }
                   7656: 
1.346     albertel 7657: .LC_menubuttons_inline_text {
                   7658:   color: $font;
1.698     harmsja  7659:   font-size: 90%;
1.701     harmsja  7660:   padding-left:3px;
1.346     albertel 7661: }
                   7662: 
1.934     droeschl 7663: .LC_menubuttons_inline_text img{
                   7664:   vertical-align: middle;
                   7665: }
                   7666: 
1.1051    www      7667: li.LC_menubuttons_inline_text img {
1.951     onken    7668:   cursor:pointer;
1.1002    droeschl 7669:   text-decoration: none;
1.951     onken    7670: }
                   7671: 
1.526     www      7672: .LC_menubuttons_link {
                   7673:   text-decoration: none;
                   7674: }
1.795     www      7675: 
1.522     albertel 7676: .LC_menubuttons_category {
1.521     www      7677:   color: $font;
1.526     www      7678:   background: $pgbg;
1.521     www      7679:   font-size: larger;
                   7680:   font-weight: bold;
                   7681: }
                   7682: 
1.346     albertel 7683: td.LC_menubuttons_text {
1.911     bisitz   7684:   color: $font;
1.346     albertel 7685: }
1.706     harmsja  7686: 
1.346     albertel 7687: .LC_current_location {
                   7688:   background: $tabbg;
                   7689: }
1.795     www      7690: 
1.1286    raeburn  7691: td.LC_zero_height {
                   7692:   line-height: 0; 
                   7693:   cellpadding: 0;
                   7694: }
                   7695: 
1.938     bisitz   7696: table.LC_data_table {
1.347     albertel 7697:   border: 1px solid #000000;
1.402     albertel 7698:   border-collapse: separate;
1.426     albertel 7699:   border-spacing: 1px;
1.610     albertel 7700:   background: $pgbg;
1.347     albertel 7701: }
1.795     www      7702: 
1.422     albertel 7703: .LC_data_table_dense {
                   7704:   font-size: small;
                   7705: }
1.795     www      7706: 
1.507     raeburn  7707: table.LC_nested_outer {
                   7708:   border: 1px solid #000000;
1.589     raeburn  7709:   border-collapse: collapse;
1.803     bisitz   7710:   border-spacing: 0;
1.507     raeburn  7711:   width: 100%;
                   7712: }
1.795     www      7713: 
1.879     raeburn  7714: table.LC_innerpickbox,
1.507     raeburn  7715: table.LC_nested {
1.803     bisitz   7716:   border: none;
1.589     raeburn  7717:   border-collapse: collapse;
1.803     bisitz   7718:   border-spacing: 0;
1.507     raeburn  7719:   width: 100%;
                   7720: }
1.795     www      7721: 
1.911     bisitz   7722: table.LC_data_table tr th,
                   7723: table.LC_calendar tr th,
1.879     raeburn  7724: table.LC_prior_tries tr th,
                   7725: table.LC_innerpickbox tr th {
1.349     albertel 7726:   font-weight: bold;
                   7727:   background-color: $data_table_head;
1.801     tempelho 7728:   color:$fontmenu;
1.701     harmsja  7729:   font-size:90%;
1.347     albertel 7730: }
1.795     www      7731: 
1.879     raeburn  7732: table.LC_innerpickbox tr th,
                   7733: table.LC_innerpickbox tr td {
                   7734:   vertical-align: top;
                   7735: }
                   7736: 
1.711     raeburn  7737: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7738:   background-color: #CCCCCC;
1.711     raeburn  7739:   font-weight: bold;
                   7740:   text-align: left;
                   7741: }
1.795     www      7742: 
1.912     bisitz   7743: table.LC_data_table tr.LC_odd_row > td {
                   7744:   background-color: $data_table_light;
                   7745:   padding: 2px;
                   7746:   vertical-align: top;
                   7747: }
                   7748: 
1.809     bisitz   7749: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7750:   background-color: $data_table_light;
1.912     bisitz   7751:   vertical-align: top;
                   7752: }
                   7753: 
                   7754: table.LC_data_table tr.LC_even_row > td {
                   7755:   background-color: $data_table_dark;
1.425     albertel 7756:   padding: 2px;
1.900     bisitz   7757:   vertical-align: top;
1.347     albertel 7758: }
1.795     www      7759: 
1.809     bisitz   7760: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7761:   background-color: $data_table_dark;
1.900     bisitz   7762:   vertical-align: top;
1.347     albertel 7763: }
1.795     www      7764: 
1.425     albertel 7765: table.LC_data_table tr.LC_data_table_highlight td {
                   7766:   background-color: $data_table_darker;
                   7767: }
1.795     www      7768: 
1.639     raeburn  7769: table.LC_data_table tr td.LC_leftcol_header {
                   7770:   background-color: $data_table_head;
                   7771:   font-weight: bold;
                   7772: }
1.795     www      7773: 
1.451     albertel 7774: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7775: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7776:   font-weight: bold;
                   7777:   font-style: italic;
                   7778:   text-align: center;
                   7779:   padding: 8px;
1.347     albertel 7780: }
1.795     www      7781: 
1.1114    raeburn  7782: table.LC_data_table tr.LC_empty_row td,
                   7783: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7784:   background-color: $sidebg;
                   7785: }
                   7786: 
                   7787: table.LC_nested tr.LC_empty_row td {
                   7788:   background-color: #FFFFFF;
                   7789: }
                   7790: 
1.890     droeschl 7791: table.LC_caption {
                   7792: }
                   7793: 
1.1469    raeburn  7794: caption.LC_caption_prefs {
                   7795:   font-weight: normal;
                   7796:   text-align: left;
                   7797:   padding-bottom: 0.8em;
                   7798: }
                   7799: 
1.507     raeburn  7800: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7801:   padding: 4ex
                   7802: }
1.795     www      7803: 
1.507     raeburn  7804: table.LC_nested_outer tr th {
                   7805:   font-weight: bold;
1.801     tempelho 7806:   color:$fontmenu;
1.507     raeburn  7807:   background-color: $data_table_head;
1.701     harmsja  7808:   font-size: small;
1.507     raeburn  7809:   border-bottom: 1px solid #000000;
                   7810: }
1.795     www      7811: 
1.507     raeburn  7812: table.LC_nested_outer tr td.LC_subheader {
                   7813:   background-color: $data_table_head;
                   7814:   font-weight: bold;
                   7815:   font-size: small;
                   7816:   border-bottom: 1px solid #000000;
                   7817:   text-align: right;
1.451     albertel 7818: }
1.795     www      7819: 
1.507     raeburn  7820: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7821:   background-color: #CCCCCC;
1.451     albertel 7822:   font-weight: bold;
                   7823:   font-size: small;
1.507     raeburn  7824:   text-align: center;
                   7825: }
1.795     www      7826: 
1.589     raeburn  7827: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7828: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7829:   text-align: left;
1.451     albertel 7830: }
1.795     www      7831: 
1.507     raeburn  7832: table.LC_nested td {
1.735     bisitz   7833:   background-color: #FFFFFF;
1.451     albertel 7834:   font-size: small;
1.507     raeburn  7835: }
1.795     www      7836: 
1.507     raeburn  7837: table.LC_nested_outer tr th.LC_right_item,
                   7838: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7839: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7840: table.LC_nested tr td.LC_right_item {
1.451     albertel 7841:   text-align: right;
                   7842: }
                   7843: 
1.507     raeburn  7844: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7845:   background-color: #EEEEEE;
1.451     albertel 7846: }
                   7847: 
1.473     raeburn  7848: table.LC_createuser {
                   7849: }
                   7850: 
                   7851: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7852:   font-size: small;
1.473     raeburn  7853: }
                   7854: 
                   7855: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7856:   background-color: #CCCCCC;
1.473     raeburn  7857:   font-weight: bold;
                   7858:   text-align: center;
                   7859: }
                   7860: 
1.349     albertel 7861: table.LC_calendar {
                   7862:   border: 1px solid #000000;
                   7863:   border-collapse: collapse;
1.917     raeburn  7864:   width: 98%;
1.349     albertel 7865: }
1.795     www      7866: 
1.349     albertel 7867: table.LC_calendar_pickdate {
                   7868:   font-size: xx-small;
                   7869: }
1.795     www      7870: 
1.349     albertel 7871: table.LC_calendar tr td {
                   7872:   border: 1px solid #000000;
                   7873:   vertical-align: top;
1.917     raeburn  7874:   width: 14%;
1.349     albertel 7875: }
1.795     www      7876: 
1.349     albertel 7877: table.LC_calendar tr td.LC_calendar_day_empty {
                   7878:   background-color: $data_table_dark;
                   7879: }
1.795     www      7880: 
1.779     bisitz   7881: table.LC_calendar tr td.LC_calendar_day_current {
                   7882:   background-color: $data_table_highlight;
1.777     tempelho 7883: }
1.795     www      7884: 
1.938     bisitz   7885: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7886:   background-color: $mail_new;
                   7887: }
1.795     www      7888: 
1.938     bisitz   7889: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7890:   background-color: $mail_new_hover;
                   7891: }
1.795     www      7892: 
1.938     bisitz   7893: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7894:   background-color: $mail_read;
                   7895: }
1.795     www      7896: 
1.938     bisitz   7897: /*
                   7898: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7899:   background-color: $mail_read_hover;
                   7900: }
1.938     bisitz   7901: */
1.795     www      7902: 
1.938     bisitz   7903: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7904:   background-color: $mail_replied;
                   7905: }
1.795     www      7906: 
1.938     bisitz   7907: /*
                   7908: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7909:   background-color: $mail_replied_hover;
                   7910: }
1.938     bisitz   7911: */
1.795     www      7912: 
1.938     bisitz   7913: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7914:   background-color: $mail_other;
                   7915: }
1.795     www      7916: 
1.938     bisitz   7917: /*
                   7918: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7919:   background-color: $mail_other_hover;
                   7920: }
1.938     bisitz   7921: */
1.494     raeburn  7922: 
1.777     tempelho 7923: table.LC_data_table tr > td.LC_browser_file,
                   7924: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7925:   background: #AAEE77;
1.389     albertel 7926: }
1.795     www      7927: 
1.777     tempelho 7928: table.LC_data_table tr > td.LC_browser_file_locked,
                   7929: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7930:   background: #FFAA99;
1.387     albertel 7931: }
1.795     www      7932: 
1.777     tempelho 7933: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7934:   background: #888888;
1.779     bisitz   7935: }
1.795     www      7936: 
1.777     tempelho 7937: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7938: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7939:   background: #F8F866;
1.777     tempelho 7940: }
1.795     www      7941: 
1.696     bisitz   7942: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7943:   background: #E0E8FF;
1.387     albertel 7944: }
1.696     bisitz   7945: 
1.707     bisitz   7946: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7947:   /* background: #77FF77; */
1.707     bisitz   7948: }
1.795     www      7949: 
1.707     bisitz   7950: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7951:   border-right: 8px solid #FFFF77;
1.707     bisitz   7952: }
1.795     www      7953: 
1.707     bisitz   7954: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7955:   border-right: 8px solid #FFAA77;
1.707     bisitz   7956: }
1.795     www      7957: 
1.707     bisitz   7958: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7959:   border-right: 8px solid #FF7777;
1.707     bisitz   7960: }
1.795     www      7961: 
1.707     bisitz   7962: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7963:   border-right: 8px solid #AAFF77;
1.707     bisitz   7964: }
1.795     www      7965: 
1.707     bisitz   7966: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7967:   border-right: 8px solid #11CC55;
1.707     bisitz   7968: }
                   7969: 
1.1469    raeburn  7970: table.LC_data_table tr.LC_prefs_row {
                   7971:    line-height: 250%;
                   7972: }
                   7973: 
1.388     albertel 7974: span.LC_current_location {
1.701     harmsja  7975:   font-size:larger;
1.388     albertel 7976:   background: $pgbg;
                   7977: }
1.387     albertel 7978: 
1.1029    www      7979: span.LC_current_nav_location {
                   7980:   font-weight:bold;
                   7981:   background: $sidebg;
                   7982: }
                   7983: 
1.395     albertel 7984: span.LC_parm_menu_item {
                   7985:   font-size: larger;
                   7986: }
1.795     www      7987: 
1.395     albertel 7988: span.LC_parm_scope_all {
                   7989:   color: red;
                   7990: }
1.795     www      7991: 
1.395     albertel 7992: span.LC_parm_scope_folder {
                   7993:   color: green;
                   7994: }
1.795     www      7995: 
1.395     albertel 7996: span.LC_parm_scope_resource {
                   7997:   color: orange;
                   7998: }
1.795     www      7999: 
1.395     albertel 8000: span.LC_parm_part {
                   8001:   color: blue;
                   8002: }
1.795     www      8003: 
1.911     bisitz   8004: span.LC_parm_folder,
                   8005: span.LC_parm_symb {
1.395     albertel 8006:   font-size: x-small;
                   8007:   font-family: $mono;
                   8008:   color: #AAAAAA;
                   8009: }
                   8010: 
1.977     bisitz   8011: ul.LC_parm_parmlist li {
                   8012:   display: inline-block;
                   8013:   padding: 0.3em 0.8em;
                   8014:   vertical-align: top;
                   8015:   width: 150px;
                   8016:   border-top:1px solid $lg_border_color;
                   8017: }
                   8018: 
1.795     www      8019: td.LC_parm_overview_level_menu,
                   8020: td.LC_parm_overview_map_menu,
                   8021: td.LC_parm_overview_parm_selectors,
                   8022: td.LC_parm_overview_restrictions  {
1.396     albertel 8023:   border: 1px solid black;
                   8024:   border-collapse: collapse;
                   8025: }
1.795     www      8026: 
1.1285    raeburn  8027: span.LC_parm_recursive,
                   8028: td.LC_parm_recursive {
                   8029:   font-weight: bold;
                   8030:   font-size: smaller;
                   8031: }
                   8032: 
1.396     albertel 8033: table.LC_parm_overview_restrictions td {
                   8034:   border-width: 1px 4px 1px 4px;
                   8035:   border-style: solid;
                   8036:   border-color: $pgbg;
                   8037:   text-align: center;
                   8038: }
1.795     www      8039: 
1.396     albertel 8040: table.LC_parm_overview_restrictions th {
                   8041:   background: $tabbg;
                   8042:   border-width: 1px 4px 1px 4px;
                   8043:   border-style: solid;
                   8044:   border-color: $pgbg;
                   8045: }
1.795     www      8046: 
1.1459    raeburn  8047: h1.LC_helpmenu {
                   8048:   display: inline;
                   8049:   font-size: 100%;
                   8050:   font-weight: normal;
                   8051:   line-height: 1em;
                   8052:   margin: 0;
                   8053:   padding: 0;
                   8054:   border: 0;
1.398     albertel 8055: }
1.795     www      8056: 
1.1456    raeburn  8057: .LC_helpdesk_headbox {
                   8058:   border: 2px groove threedface;
                   8059:   padding: 1em;
                   8060: }
                   8061: 
                   8062: h1.LC_helpdesk_legend {
                   8063:   float: left;
                   8064:   margin: -1.7em 0 0;
                   8065:   padding: 0 .5em;
1.397     albertel 8066:   background: $pgbg;
1.1456    raeburn  8067:   font-size: 1em;
                   8068:   font-weight: bold;
                   8069: }
                   8070: 
                   8071: h1.LC_helpdesk_title {
                   8072:   display: inline;
                   8073:   font-size: 1em;
                   8074:   line-height: 2.5em;
                   8075:   margin: 0;
1.803     bisitz   8076:   padding: 0;
1.1456    raeburn  8077:   vertical-align: bottom;
1.397     albertel 8078: }
1.795     www      8079: 
1.1456    raeburn  8080: .LC_helpdesk_links {
                   8081:   border: 1px solid black;
                   8082:   padding: 3px;
1.397     albertel 8083:   background: $tabbg;
1.399     albertel 8084:   text-align: center;
                   8085:   font-weight: bold;
1.1456    raeburn  8086:   display: inline;
                   8087:   margin-right: -6px;
                   8088: }
                   8089: 
                   8090: .LC_helpdesk_img,
                   8091: .LC_helpdesk_text {
                   8092:   padding: 0;
                   8093:   margin: 0;
                   8094:   border: 0;
                   8095:   display: inline;
1.397     albertel 8096: }
1.396     albertel 8097: 
1.1456    raeburn  8098: .LC_helpdesk_img a:link,
                   8099: .LC_helpdesk_img a:visited,
                   8100: .LC_helpdesk_img a:active,
                   8101: .LC_helpdesk_text a:link,
                   8102: .LC_helpdesk_text a:visited,
                   8103: .LC_helpdesk_text a:active {
1.397     albertel 8104:   text-decoration: none;
                   8105:   color: $font;
                   8106: }
1.795     www      8107: 
1.1456    raeburn  8108: div.LC_helpdesk_text a:hover {
1.397     albertel 8109:   text-decoration: underline;
                   8110:   color: $vlink;
                   8111: }
1.396     albertel 8112: 
1.417     albertel 8113: .LC_chrt_popup_exists {
                   8114:   border: 1px solid #339933;
                   8115:   margin: -1px;
                   8116: }
1.795     www      8117: 
1.417     albertel 8118: .LC_chrt_popup_up {
                   8119:   border: 1px solid yellow;
                   8120:   margin: -1px;
                   8121: }
1.795     www      8122: 
1.417     albertel 8123: .LC_chrt_popup {
                   8124:   border: 1px solid #8888FF;
                   8125:   background: #CCCCFF;
                   8126: }
1.795     www      8127: 
1.421     albertel 8128: table.LC_pick_box {
                   8129:   border-collapse: separate;
                   8130:   background: white;
                   8131:   border: 1px solid black;
                   8132:   border-spacing: 1px;
                   8133: }
1.795     www      8134: 
1.1454    raeburn  8135: table.LC_pick_box th.LC_pick_box_title {
1.850     bisitz   8136:   background: $sidebg;
1.421     albertel 8137:   font-weight: bold;
1.900     bisitz   8138:   text-align: left;
1.740     bisitz   8139:   vertical-align: top;
1.421     albertel 8140:   width: 184px;
                   8141:   padding: 8px;
                   8142: }
1.795     www      8143: 
1.579     raeburn  8144: table.LC_pick_box td.LC_pick_box_value {
                   8145:   text-align: left;
                   8146:   padding: 8px;
                   8147: }
1.795     www      8148: 
1.579     raeburn  8149: table.LC_pick_box td.LC_pick_box_select {
                   8150:   text-align: left;
                   8151:   padding: 8px;
                   8152: }
1.795     www      8153: 
1.424     albertel 8154: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8155:   padding: 0;
1.421     albertel 8156:   height: 1px;
                   8157:   background: black;
                   8158: }
1.795     www      8159: 
1.421     albertel 8160: table.LC_pick_box td.LC_pick_box_submit {
                   8161:   text-align: right;
                   8162: }
1.795     www      8163: 
1.579     raeburn  8164: table.LC_pick_box td.LC_evenrow_value {
                   8165:   text-align: left;
                   8166:   padding: 8px;
                   8167:   background-color: $data_table_light;
                   8168: }
1.795     www      8169: 
1.579     raeburn  8170: table.LC_pick_box td.LC_oddrow_value {
                   8171:   text-align: left;
                   8172:   padding: 8px;
                   8173:   background-color: $data_table_light;
                   8174: }
1.795     www      8175: 
1.1473  ! raeburn  8176: td.LC_log_filter,
        !          8177: th.LC_log_filter {
        !          8178:   vertical-align: top;
        !          8179:   text-align: left;
        !          8180:   padding: 0 4px;
        !          8181: }
        !          8182: 
1.579     raeburn  8183: span.LC_helpform_receipt_cat {
                   8184:   font-weight: bold;
                   8185: }
1.795     www      8186: 
1.424     albertel 8187: table.LC_group_priv_box {
                   8188:   background: white;
                   8189:   border: 1px solid black;
                   8190:   border-spacing: 1px;
                   8191: }
1.795     www      8192: 
1.424     albertel 8193: table.LC_group_priv_box td.LC_pick_box_title {
                   8194:   background: $tabbg;
                   8195:   font-weight: bold;
                   8196:   text-align: right;
                   8197:   width: 184px;
                   8198: }
1.795     www      8199: 
1.424     albertel 8200: table.LC_group_priv_box td.LC_groups_fixed {
                   8201:   background: $data_table_light;
                   8202:   text-align: center;
                   8203: }
1.795     www      8204: 
1.424     albertel 8205: table.LC_group_priv_box td.LC_groups_optional {
                   8206:   background: $data_table_dark;
                   8207:   text-align: center;
                   8208: }
1.795     www      8209: 
1.424     albertel 8210: table.LC_group_priv_box td.LC_groups_functionality {
                   8211:   background: $data_table_darker;
                   8212:   text-align: center;
                   8213:   font-weight: bold;
                   8214: }
1.795     www      8215: 
1.424     albertel 8216: table.LC_group_priv td {
                   8217:   text-align: left;
1.803     bisitz   8218:   padding: 0;
1.424     albertel 8219: }
                   8220: 
                   8221: .LC_navbuttons {
                   8222:   margin: 2ex 0ex 2ex 0ex;
                   8223: }
1.795     www      8224: 
1.423     albertel 8225: .LC_topic_bar {
                   8226:   font-weight: bold;
                   8227:   background: $tabbg;
1.918     wenzelju 8228:   margin: 1em 0em 1em 2em;
1.805     bisitz   8229:   padding: 3px;
1.918     wenzelju 8230:   font-size: 1.2em;
1.423     albertel 8231: }
1.795     www      8232: 
1.423     albertel 8233: .LC_topic_bar span {
1.918     wenzelju 8234:   left: 0.5em;
                   8235:   position: absolute;
1.423     albertel 8236:   vertical-align: middle;
1.918     wenzelju 8237:   font-size: 1.2em;
1.423     albertel 8238: }
1.795     www      8239: 
1.423     albertel 8240: table.LC_course_group_status {
                   8241:   margin: 20px;
                   8242: }
1.795     www      8243: 
1.423     albertel 8244: table.LC_status_selector td {
                   8245:   vertical-align: top;
                   8246:   text-align: center;
1.424     albertel 8247:   padding: 4px;
                   8248: }
1.795     www      8249: 
1.599     albertel 8250: div.LC_feedback_link {
1.616     albertel 8251:   clear: both;
1.829     kalberla 8252:   background: $sidebg;
1.779     bisitz   8253:   width: 100%;
1.829     kalberla 8254:   padding-bottom: 10px;
                   8255:   border: 1px $tabbg solid;
1.833     kalberla 8256:   height: 22px;
                   8257:   line-height: 22px;
                   8258:   padding-top: 5px;
                   8259: }
                   8260: 
                   8261: div.LC_feedback_link img {
                   8262:   height: 22px;
1.867     kalberla 8263:   vertical-align:middle;
1.829     kalberla 8264: }
                   8265: 
1.911     bisitz   8266: div.LC_feedback_link a {
1.829     kalberla 8267:   text-decoration: none;
1.489     raeburn  8268: }
1.795     www      8269: 
1.867     kalberla 8270: div.LC_comblock {
1.911     bisitz   8271:   display:inline;
1.867     kalberla 8272:   color:$font;
                   8273:   font-size:90%;
                   8274: }
                   8275: 
                   8276: div.LC_feedback_link div.LC_comblock {
                   8277:   padding-left:5px;
                   8278: }
                   8279: 
                   8280: div.LC_feedback_link div.LC_comblock a {
                   8281:   color:$font;
                   8282: }
                   8283: 
1.489     raeburn  8284: span.LC_feedback_link {
1.858     bisitz   8285:   /* background: $feedback_link_bg; */
1.599     albertel 8286:   font-size: larger;
                   8287: }
1.795     www      8288: 
1.599     albertel 8289: span.LC_message_link {
1.858     bisitz   8290:   /* background: $feedback_link_bg; */
1.599     albertel 8291:   font-size: larger;
                   8292:   position: absolute;
                   8293:   right: 1em;
1.489     raeburn  8294: }
1.421     albertel 8295: 
1.515     albertel 8296: table.LC_prior_tries {
1.524     albertel 8297:   border: 1px solid #000000;
                   8298:   border-collapse: separate;
                   8299:   border-spacing: 1px;
1.515     albertel 8300: }
1.523     albertel 8301: 
1.515     albertel 8302: table.LC_prior_tries td {
1.524     albertel 8303:   padding: 2px;
1.515     albertel 8304: }
1.523     albertel 8305: 
                   8306: .LC_answer_correct {
1.795     www      8307:   background: lightgreen;
                   8308:   color: darkgreen;
                   8309:   padding: 6px;
1.523     albertel 8310: }
1.795     www      8311: 
1.523     albertel 8312: .LC_answer_charged_try {
1.797     www      8313:   background: #FFAAAA;
1.795     www      8314:   color: darkred;
                   8315:   padding: 6px;
1.523     albertel 8316: }
1.795     www      8317: 
1.779     bisitz   8318: .LC_answer_not_charged_try,
1.523     albertel 8319: .LC_answer_no_grade,
                   8320: .LC_answer_late {
1.795     www      8321:   background: lightyellow;
1.523     albertel 8322:   color: black;
1.795     www      8323:   padding: 6px;
1.523     albertel 8324: }
1.795     www      8325: 
1.523     albertel 8326: .LC_answer_previous {
1.795     www      8327:   background: lightblue;
                   8328:   color: darkblue;
                   8329:   padding: 6px;
1.523     albertel 8330: }
1.795     www      8331: 
1.779     bisitz   8332: .LC_answer_no_message {
1.777     tempelho 8333:   background: #FFFFFF;
                   8334:   color: black;
1.795     www      8335:   padding: 6px;
1.779     bisitz   8336: }
1.795     www      8337: 
1.1334    raeburn  8338: .LC_answer_unknown,
                   8339: .LC_answer_warning {
1.779     bisitz   8340:   background: orange;
                   8341:   color: black;
1.795     www      8342:   padding: 6px;
1.777     tempelho 8343: }
1.795     www      8344: 
1.1467    raeburn  8345: span.LC_prob_status {
                   8346:   margin: 5px 0 0 0;
                   8347:   padding: 0 5px 0 0;
                   8348:   vertical-align: middle;
                   8349: }
                   8350: 
                   8351: div.LC_prob_status_outer {
                   8352:   display: inline-block;
                   8353:   margin: -5px 0 0 0;
                   8354:   padding: 0;
                   8355: }
                   8356: 
                   8357: div.LC_prob_status_inner {
                   8358:   display: inline-block;
                   8359:   margin: 0 5px 0 0;
                   8360:   padding: 5px;
1.1446    raeburn  8361: }
                   8362: 
1.1468    raeburn  8363: caption.LC_filesub_status {
                   8364:   text-align: left;
                   8365:   font-weight: bold;
                   8366: }
                   8367: 
1.1448    raeburn  8368: .LC_mail_actions {
                   8369:   float: left;
                   8370:   padding: 0;
                   8371:   margin: 6px;
                   8372: }
                   8373: 
                   8374: .LC_vertical_line {
                   8375:   width: 1px;
                   8376:   background-color: black;
                   8377:   height: 4em;
                   8378:   float: left;
                   8379:   margin: 0;
                   8380:   padding: 0;
                   8381: }
                   8382: 
1.529     albertel 8383: span.LC_prior_numerical,
                   8384: span.LC_prior_string,
                   8385: span.LC_prior_custom,
                   8386: span.LC_prior_reaction,
                   8387: span.LC_prior_math {
1.925     bisitz   8388:   font-family: $mono;
1.523     albertel 8389:   white-space: pre;
                   8390: }
                   8391: 
1.525     albertel 8392: span.LC_prior_string {
1.925     bisitz   8393:   font-family: $mono;
1.525     albertel 8394:   white-space: pre;
                   8395: }
                   8396: 
1.523     albertel 8397: table.LC_prior_option {
                   8398:   width: 100%;
                   8399:   border-collapse: collapse;
                   8400: }
1.795     www      8401: 
1.911     bisitz   8402: table.LC_prior_rank,
1.795     www      8403: table.LC_prior_match {
1.528     albertel 8404:   border-collapse: collapse;
                   8405: }
1.795     www      8406: 
1.528     albertel 8407: table.LC_prior_option tr td,
                   8408: table.LC_prior_rank tr td,
                   8409: table.LC_prior_match tr td {
1.524     albertel 8410:   border: 1px solid #000000;
1.515     albertel 8411: }
                   8412: 
1.855     bisitz   8413: .LC_nobreak {
1.544     albertel 8414:   white-space: nowrap;
1.519     raeburn  8415: }
                   8416: 
1.576     raeburn  8417: span.LC_cusr_emph {
                   8418:   font-style: italic;
                   8419: }
                   8420: 
1.633     raeburn  8421: span.LC_cusr_subheading {
                   8422:   font-weight: normal;
                   8423:   font-size: 85%;
                   8424: }
                   8425: 
1.861     bisitz   8426: div.LC_docs_entry_move {
1.859     bisitz   8427:   border: 1px solid #BBBBBB;
1.545     albertel 8428:   background: #DDDDDD;
1.861     bisitz   8429:   width: 22px;
1.859     bisitz   8430:   padding: 1px;
                   8431:   margin: 0;
1.545     albertel 8432: }
                   8433: 
1.861     bisitz   8434: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8435: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8436:   font-size: x-small;
                   8437: }
1.795     www      8438: 
1.861     bisitz   8439: .LC_docs_entry_parameter {
                   8440:   white-space: nowrap;
                   8441: }
                   8442: 
1.544     albertel 8443: .LC_docs_copy {
1.545     albertel 8444:   color: #000099;
1.544     albertel 8445: }
1.795     www      8446: 
1.544     albertel 8447: .LC_docs_cut {
1.545     albertel 8448:   color: #550044;
1.544     albertel 8449: }
1.795     www      8450: 
1.544     albertel 8451: .LC_docs_rename {
1.545     albertel 8452:   color: #009900;
1.544     albertel 8453: }
1.795     www      8454: 
1.544     albertel 8455: .LC_docs_remove {
1.545     albertel 8456:   color: #990000;
                   8457: }
                   8458: 
1.1284    raeburn  8459: .LC_docs_alias {
                   8460:   color: #440055;  
                   8461: }
                   8462: 
1.1286    raeburn  8463: .LC_domprefs_email,
1.1284    raeburn  8464: .LC_docs_alias_name,
1.547     albertel 8465: .LC_docs_reinit_warn,
                   8466: .LC_docs_ext_edit {
                   8467:   font-size: x-small;
                   8468: }
                   8469: 
1.545     albertel 8470: table.LC_docs_adddocs td,
                   8471: table.LC_docs_adddocs th {
                   8472:   border: 1px solid #BBBBBB;
                   8473:   padding: 4px;
                   8474:   background: #DDDDDD;
1.543     albertel 8475: }
                   8476: 
1.584     albertel 8477: table.LC_sty_begin {
                   8478:   background: #BBFFBB;
                   8479: }
1.795     www      8480: 
1.584     albertel 8481: table.LC_sty_end {
                   8482:   background: #FFBBBB;
                   8483: }
                   8484: 
1.589     raeburn  8485: table.LC_double_column {
1.803     bisitz   8486:   border-width: 0;
1.589     raeburn  8487:   border-collapse: collapse;
                   8488:   width: 100%;
                   8489:   padding: 2px;
                   8490: }
                   8491: 
                   8492: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8493:   top: 2px;
1.589     raeburn  8494:   left: 2px;
                   8495:   width: 47%;
                   8496:   vertical-align: top;
                   8497: }
                   8498: 
                   8499: table.LC_double_column tr td.LC_right_col {
                   8500:   top: 2px;
1.779     bisitz   8501:   right: 2px;
1.589     raeburn  8502:   width: 47%;
                   8503:   vertical-align: top;
                   8504: }
                   8505: 
1.591     raeburn  8506: div.LC_left_float {
                   8507:   float: left;
                   8508:   padding-right: 5%;
1.597     albertel 8509:   padding-bottom: 4px;
1.591     raeburn  8510: }
                   8511: 
                   8512: div.LC_clear_float_header {
1.597     albertel 8513:   padding-bottom: 2px;
1.591     raeburn  8514: }
                   8515: 
                   8516: div.LC_clear_float_footer {
1.597     albertel 8517:   padding-top: 10px;
1.591     raeburn  8518:   clear: both;
                   8519: }
                   8520: 
1.597     albertel 8521: div.LC_grade_show_user {
1.941     bisitz   8522: /*  border-left: 5px solid $sidebg; */
                   8523:   border-top: 5px solid #000000;
                   8524:   margin: 50px 0 0 0;
1.936     bisitz   8525:   padding: 15px 0 5px 10px;
1.597     albertel 8526: }
1.795     www      8527: 
1.936     bisitz   8528: div.LC_grade_show_user_odd_row {
1.941     bisitz   8529: /*  border-left: 5px solid #000000; */
                   8530: }
                   8531: 
                   8532: div.LC_grade_show_user div.LC_Box {
                   8533:   margin-right: 50px;
1.597     albertel 8534: }
                   8535: 
1.1461    raeburn  8536: div.LC_grade_show_user div.LC_Box table tr th {
                   8537:   font-weight: normal;
                   8538: }
                   8539: 
1.597     albertel 8540: div.LC_grade_submissions,
                   8541: div.LC_grade_message_center,
1.936     bisitz   8542: div.LC_grade_info_links {
1.597     albertel 8543:   margin: 5px;
                   8544:   width: 99%;
                   8545:   background: #FFFFFF;
                   8546: }
1.795     www      8547: 
1.597     albertel 8548: div.LC_grade_submissions_header,
1.936     bisitz   8549: div.LC_grade_message_center_header {
1.705     tempelho 8550:   font-weight: bold;
                   8551:   font-size: large;
1.597     albertel 8552: }
1.795     www      8553: 
1.597     albertel 8554: div.LC_grade_submissions_body,
1.936     bisitz   8555: div.LC_grade_message_center_body {
1.597     albertel 8556:   border: 1px solid black;
                   8557:   width: 99%;
                   8558:   background: #FFFFFF;
                   8559: }
1.795     www      8560: 
1.613     albertel 8561: table.LC_scantron_action {
                   8562:   width: 100%;
                   8563: }
1.795     www      8564: 
1.613     albertel 8565: table.LC_scantron_action tr th {
1.698     harmsja  8566:   font-weight:bold;
                   8567:   font-style:normal;
1.613     albertel 8568: }
1.795     www      8569: 
1.1461    raeburn  8570: div.LC_edit_problem_daxe_header {
                   8571:   padding: 3px;
                   8572:   background: $tabbg;
                   8573:   z-index: 100;
                   8574: }
                   8575: 
1.779     bisitz   8576: .LC_edit_problem_header,
1.614     albertel 8577: div.LC_edit_problem_footer {
1.705     tempelho 8578:   font-weight: normal;
                   8579:   font-size:  medium;
1.602     albertel 8580:   margin: 2px;
1.1060    bisitz   8581:   background-color: $sidebg;
1.600     albertel 8582: }
1.795     www      8583: 
1.600     albertel 8584: div.LC_edit_problem_header,
1.602     albertel 8585: div.LC_edit_problem_header div,
1.614     albertel 8586: div.LC_edit_problem_footer,
                   8587: div.LC_edit_problem_footer div,
1.602     albertel 8588: div.LC_edit_problem_editxml_header,
                   8589: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8590:   z-index: 100;
1.600     albertel 8591: }
1.795     www      8592: 
1.600     albertel 8593: div.LC_edit_problem_header_title {
1.705     tempelho 8594:   font-weight: bold;
                   8595:   font-size: larger;
1.602     albertel 8596:   background: $tabbg;
                   8597:   padding: 3px;
1.1060    bisitz   8598:   margin: 0 0 5px 0;
1.602     albertel 8599: }
1.795     www      8600: 
1.602     albertel 8601: table.LC_edit_problem_header_title {
                   8602:   width: 100%;
1.600     albertel 8603:   background: $tabbg;
1.602     albertel 8604: }
                   8605: 
1.1205    golterma 8606: div.LC_edit_actionbar {
                   8607:     background-color: $sidebg;
1.1218    droeschl 8608:     margin: 0;
                   8609:     padding: 0;
                   8610:     line-height: 200%;
1.602     albertel 8611: }
1.795     www      8612: 
1.1218    droeschl 8613: div.LC_edit_actionbar div{
                   8614:     padding: 0;
                   8615:     margin: 0;
                   8616:     display: inline-block;
1.600     albertel 8617: }
1.795     www      8618: 
1.1124    bisitz   8619: .LC_edit_opt {
                   8620:   padding-left: 1em;
                   8621:   white-space: nowrap;
                   8622: }
                   8623: 
1.1152    golterma 8624: .LC_edit_problem_latexhelper{
                   8625:     text-align: right;
                   8626: }
                   8627: 
                   8628: #LC_edit_problem_colorful div{
                   8629:     margin-left: 40px;
                   8630: }
                   8631: 
1.1205    golterma 8632: #LC_edit_problem_codemirror div{
                   8633:     margin-left: 0px;
                   8634: }
                   8635: 
1.911     bisitz   8636: img.stift {
1.803     bisitz   8637:   border-width: 0;
                   8638:   vertical-align: middle;
1.677     riegler  8639: }
1.680     riegler  8640: 
1.1460    raeburn  8641: div.LC_mainmenu {
                   8642:   margin: 3px 2px 2px 1px;
                   8643:   float: left;
1.777     tempelho 8644: }
1.795     www      8645: 
1.716     raeburn  8646: div.LC_createcourse {
1.911     bisitz   8647:   margin: 10px 10px 10px 10px;
1.716     raeburn  8648: }
                   8649: 
1.917     raeburn  8650: .LC_dccid {
1.1130    raeburn  8651:   float: right;
1.917     raeburn  8652:   margin: 0.2em 0 0 0;
                   8653:   padding: 0;
                   8654:   font-size: 90%;
                   8655:   display:none;
                   8656: }
                   8657: 
1.897     wenzelju 8658: ol.LC_primary_menu a:hover,
1.721     harmsja  8659: ol#LC_MenuBreadcrumbs a:hover,
                   8660: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8661: ul#LC_secondary_menu a:hover,
1.721     harmsja  8662: .LC_FormSectionClearButton input:hover
1.795     www      8663: ul.LC_TabContent   li:hover a {
1.952     onken    8664:   color:$button_hover;
1.911     bisitz   8665:   text-decoration:none;
1.693     droeschl 8666: }
                   8667: 
1.779     bisitz   8668: h1 {
1.911     bisitz   8669:   padding: 0;
                   8670:   line-height:130%;
1.693     droeschl 8671: }
1.698     harmsja  8672: 
1.911     bisitz   8673: h2,
                   8674: h3,
                   8675: h4,
                   8676: h5,
                   8677: h6 {
                   8678:   margin: 5px 0 5px 0;
                   8679:   padding: 0;
                   8680:   line-height:130%;
1.693     droeschl 8681: }
1.795     www      8682: 
                   8683: .LC_hcell {
1.911     bisitz   8684:   padding:3px 15px 3px 15px;
                   8685:   margin: 0;
                   8686:   background-color:$tabbg;
                   8687:   color:$fontmenu;
                   8688:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8689: }
1.795     www      8690: 
1.840     bisitz   8691: .LC_Box > .LC_hcell {
1.911     bisitz   8692:   margin: 0 -10px 10px -10px;
1.835     bisitz   8693: }
                   8694: 
1.721     harmsja  8695: .LC_noBorder {
1.911     bisitz   8696:   border: 0;
1.698     harmsja  8697: }
1.693     droeschl 8698: 
1.721     harmsja  8699: .LC_FormSectionClearButton input {
1.911     bisitz   8700:   background-color:transparent;
                   8701:   border: none;
                   8702:   cursor:pointer;
                   8703:   text-decoration:underline;
1.693     droeschl 8704: }
1.763     bisitz   8705: 
                   8706: .LC_help_open_topic {
1.911     bisitz   8707:   color: #FFFFFF;
                   8708:   background-color: #EEEEFF;
                   8709:   margin: 1px;
                   8710:   padding: 4px;
                   8711:   border: 1px solid #000033;
                   8712:   white-space: nowrap;
                   8713:   /* vertical-align: middle; */
1.759     neumanie 8714: }
1.693     droeschl 8715: 
1.911     bisitz   8716: dl,
                   8717: ul,
                   8718: div,
                   8719: fieldset {
                   8720:   margin: 10px 10px 10px 0;
                   8721:   /* overflow: hidden; */
1.693     droeschl 8722: }
1.795     www      8723: 
1.1404    raeburn  8724: fieldset#LC_selectuser {
1.1460    raeburn  8725:   margin: -1px 0 0 0;
                   8726:   padding: 0;
                   8727:   border: 0;
1.1404    raeburn  8728: }
                   8729: 
1.1473  ! raeburn  8730: fieldset.LC_delete_slot {
        !          8731:   display:inline;
        !          8732:   margin: 0 4px 4px;
        !          8733:   padding: 4px;
        !          8734: }
        !          8735: 
        !          8736: fieldset.LC_delete_slot > legend {
        !          8737:   font-weight: normal;
        !          8738: }
        !          8739: 
        !          8740: p.LC_medium_line {
        !          8741:   line-height: 0.85em;
        !          8742: }
        !          8743: 
1.1211    raeburn  8744: article.geogebraweb div {
                   8745:     margin: 0;
                   8746: }
                   8747: 
1.838     bisitz   8748: fieldset > legend {
1.911     bisitz   8749:   font-weight: bold;
                   8750:   padding: 0 5px 0 5px;
1.838     bisitz   8751: }
                   8752: 
1.813     bisitz   8753: #LC_nav_bar {
1.911     bisitz   8754:   float: left;
1.995     raeburn  8755:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8756:   margin: 0 0 2px 0;
1.807     droeschl 8757: }
                   8758: 
1.916     droeschl 8759: #LC_realm {
                   8760:   margin: 0.2em 0 0 0;
                   8761:   padding: 0;
                   8762:   font-weight: bold;
                   8763:   text-align: center;
1.995     raeburn  8764:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8765: }
                   8766: 
1.911     bisitz   8767: #LC_nav_bar em {
                   8768:   font-weight: bold;
                   8769:   font-style: normal;
1.807     droeschl 8770: }
                   8771: 
1.897     wenzelju 8772: ol.LC_primary_menu {
1.934     droeschl 8773:   margin: 0;
1.1076    raeburn  8774:   padding: 0;
1.807     droeschl 8775: }
                   8776: 
1.852     droeschl 8777: ol#LC_PathBreadcrumbs {
1.911     bisitz   8778:   margin: 0;
1.693     droeschl 8779: }
                   8780: 
1.897     wenzelju 8781: ol.LC_primary_menu li {
1.1076    raeburn  8782:   color: RGB(80, 80, 80);
                   8783:   vertical-align: middle;
                   8784:   text-align: left;
                   8785:   list-style: none;
1.1205    golterma 8786:   position: relative;
1.1076    raeburn  8787:   float: left;
1.1205    golterma 8788:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8789:   line-height: 1.5em;
1.1076    raeburn  8790: }
                   8791: 
1.1205    golterma 8792: ol.LC_primary_menu li a,
                   8793: ol.LC_primary_menu li p {
1.1076    raeburn  8794:   display: block;
                   8795:   margin: 0;
                   8796:   padding: 0 5px 0 10px;
                   8797:   text-decoration: none;
                   8798: }
                   8799: 
1.1205    golterma 8800: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8801:   display: inline-block;
                   8802:   width: 95%;
                   8803:   text-align: left;
                   8804: }
                   8805: 
                   8806: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8807:   display: inline-block;	
                   8808:   width: 5%;
                   8809:   float: right;
                   8810:   text-align: right;
                   8811:   font-size: 70%;
                   8812: }
                   8813: 
                   8814: ol.LC_primary_menu ul {
1.1076    raeburn  8815:   display: none;
1.1205    golterma 8816:   width: 15em;
1.1076    raeburn  8817:   background-color: $data_table_light;
1.1205    golterma 8818:   position: absolute;
                   8819:   top: 100%;
1.1076    raeburn  8820: }
                   8821: 
1.1205    golterma 8822: ol.LC_primary_menu ul ul {
                   8823:   left: 100%;
                   8824:   top: 0;
                   8825: }
                   8826: 
                   8827: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8828:   display: block;
                   8829:   position: absolute;
                   8830:   margin: 0;
                   8831:   padding: 0;
1.1078    raeburn  8832:   z-index: 2;
1.1076    raeburn  8833: }
                   8834: 
                   8835: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8836: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8837:   font-size: 90%;
1.911     bisitz   8838:   vertical-align: top;
1.1076    raeburn  8839:   float: none;
1.1079    raeburn  8840:   border-left: 1px solid black;
                   8841:   border-right: 1px solid black;
1.1205    golterma 8842: /* A dark bottom border to visualize different menu options; 
                   8843: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8844:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8845: }
                   8846: 
1.1205    golterma 8847: ol.LC_primary_menu li li p:hover {
                   8848:   color:$button_hover;
                   8849:   text-decoration:none;
                   8850:   background-color:$data_table_dark;
1.1076    raeburn  8851: }
                   8852: 
                   8853: ol.LC_primary_menu li li a:hover {
                   8854:    color:$button_hover;
                   8855:    background-color:$data_table_dark;
1.693     droeschl 8856: }
                   8857: 
1.1205    golterma 8858: /* Font-size equal to the size of the predecessors*/
                   8859: ol.LC_primary_menu li:hover li li {
                   8860:   font-size: 100%;
                   8861: }
                   8862: 
1.897     wenzelju 8863: ol.LC_primary_menu li img {
1.911     bisitz   8864:   vertical-align: bottom;
1.934     droeschl 8865:   height: 1.1em;
1.1077    raeburn  8866:   margin: 0.2em 0 0 0;
1.693     droeschl 8867: }
                   8868: 
1.897     wenzelju 8869: ol.LC_primary_menu a {
1.911     bisitz   8870:   color: RGB(80, 80, 80);
                   8871:   text-decoration: none;
1.693     droeschl 8872: }
1.795     www      8873: 
1.949     droeschl 8874: ol.LC_primary_menu a.LC_new_message {
                   8875:   font-weight:bold;
                   8876:   color: darkred;
                   8877: }
                   8878: 
1.975     raeburn  8879: ol.LC_docs_parameters {
                   8880:   margin-left: 0;
                   8881:   padding: 0;
                   8882:   list-style: none;
                   8883: }
                   8884: 
                   8885: ol.LC_docs_parameters li {
                   8886:   margin: 0;
                   8887:   padding-right: 20px;
                   8888:   display: inline;
                   8889: }
                   8890: 
1.976     raeburn  8891: ol.LC_docs_parameters li:before {
                   8892:   content: "\\002022 \\0020";
                   8893: }
                   8894: 
                   8895: li.LC_docs_parameters_title {
                   8896:   font-weight: bold;
                   8897: }
                   8898: 
                   8899: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8900:   content: "";
                   8901: }
                   8902: 
1.897     wenzelju 8903: ul#LC_secondary_menu {
1.1107    raeburn  8904:   clear: right;
1.911     bisitz   8905:   color: $fontmenu;
                   8906:   background: $tabbg;
                   8907:   list-style: none;
                   8908:   padding: 0;
                   8909:   margin: 0;
                   8910:   width: 100%;
1.995     raeburn  8911:   text-align: left;
1.1107    raeburn  8912:   float: left;
1.808     droeschl 8913: }
                   8914: 
1.897     wenzelju 8915: ul#LC_secondary_menu li {
1.911     bisitz   8916:   font-weight: bold;
                   8917:   line-height: 1.8em;
1.1107    raeburn  8918:   border-right: 1px solid black;
                   8919:   float: left;
                   8920: }
                   8921: 
                   8922: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8923:   background-color: $data_table_light;
                   8924: }
                   8925: 
                   8926: ul#LC_secondary_menu li a {
1.911     bisitz   8927:   padding: 0 0.8em;
1.1107    raeburn  8928: }
                   8929: 
                   8930: ul#LC_secondary_menu li ul {
                   8931:   display: none;
                   8932: }
                   8933: 
                   8934: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8935:   display: block;
                   8936:   position: absolute;
                   8937:   margin: 0;
                   8938:   padding: 0;
                   8939:   list-style:none;
                   8940:   float: none;
                   8941:   background-color: $data_table_light;
                   8942:   z-index: 2;
                   8943:   margin-left: -1px;
                   8944: }
                   8945: 
                   8946: ul#LC_secondary_menu li ul li {
                   8947:   font-size: 90%;
                   8948:   vertical-align: top;
                   8949:   border-left: 1px solid black;
1.911     bisitz   8950:   border-right: 1px solid black;
1.1119    raeburn  8951:   background-color: $data_table_light;
1.1107    raeburn  8952:   list-style:none;
                   8953:   float: none;
                   8954: }
                   8955: 
                   8956: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8957:   background-color: $data_table_dark;
1.807     droeschl 8958: }
                   8959: 
1.847     tempelho 8960: ul.LC_TabContent {
1.911     bisitz   8961:   display:block;
                   8962:   background: $sidebg;
                   8963:   border-bottom: solid 1px $lg_border_color;
                   8964:   list-style:none;
1.1020    raeburn  8965:   margin: -1px -10px 0 -10px;
1.911     bisitz   8966:   padding: 0;
1.693     droeschl 8967: }
                   8968: 
1.795     www      8969: ul.LC_TabContent li,
                   8970: ul.LC_TabContentBigger li {
1.911     bisitz   8971:   float:left;
1.741     harmsja  8972: }
1.795     www      8973: 
1.897     wenzelju 8974: ul#LC_secondary_menu li a {
1.911     bisitz   8975:   color: $fontmenu;
                   8976:   text-decoration: none;
1.693     droeschl 8977: }
1.795     www      8978: 
1.721     harmsja  8979: ul.LC_TabContent {
1.952     onken    8980:   min-height:20px;
1.721     harmsja  8981: }
1.795     www      8982: 
                   8983: ul.LC_TabContent li {
1.911     bisitz   8984:   vertical-align:middle;
1.959     onken    8985:   padding: 0 16px 0 10px;
1.911     bisitz   8986:   background-color:$tabbg;
                   8987:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8988:   border-left: solid 1px $font;
1.721     harmsja  8989: }
1.795     www      8990: 
1.847     tempelho 8991: ul.LC_TabContent .right {
1.911     bisitz   8992:   float:right;
1.847     tempelho 8993: }
                   8994: 
1.911     bisitz   8995: ul.LC_TabContent li a,
                   8996: ul.LC_TabContent li {
                   8997:   color:rgb(47,47,47);
                   8998:   text-decoration:none;
                   8999:   font-size:95%;
                   9000:   font-weight:bold;
1.952     onken    9001:   min-height:20px;
                   9002: }
                   9003: 
1.959     onken    9004: ul.LC_TabContent li a:hover,
                   9005: ul.LC_TabContent li a:focus {
1.952     onken    9006:   color: $button_hover;
1.959     onken    9007:   background:none;
                   9008:   outline:none;
1.952     onken    9009: }
                   9010: 
                   9011: ul.LC_TabContent li:hover {
                   9012:   color: $button_hover;
                   9013:   cursor:pointer;
1.721     harmsja  9014: }
1.795     www      9015: 
1.911     bisitz   9016: ul.LC_TabContent li.active {
1.952     onken    9017:   color: $font;
1.911     bisitz   9018:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    9019:   border-bottom:solid 1px #FFFFFF;
                   9020:   cursor: default;
1.744     ehlerst  9021: }
1.795     www      9022: 
1.959     onken    9023: ul.LC_TabContent li.active a {
                   9024:   color:$font;
                   9025:   background:#FFFFFF;
                   9026:   outline: none;
                   9027: }
1.1047    raeburn  9028: 
                   9029: ul.LC_TabContent li.goback {
                   9030:   float: left;
                   9031:   border-left: none;
                   9032: }
                   9033: 
1.870     tempelho 9034: #maincoursedoc {
1.911     bisitz   9035:   clear:both;
1.870     tempelho 9036: }
                   9037: 
                   9038: ul.LC_TabContentBigger {
1.911     bisitz   9039:   display:block;
                   9040:   list-style:none;
                   9041:   padding: 0;
1.870     tempelho 9042: }
                   9043: 
1.795     www      9044: ul.LC_TabContentBigger li {
1.911     bisitz   9045:   vertical-align:bottom;
                   9046:   height: 30px;
                   9047:   font-size:110%;
                   9048:   font-weight:bold;
                   9049:   color: #737373;
1.841     tempelho 9050: }
                   9051: 
1.957     onken    9052: ul.LC_TabContentBigger li.active {
                   9053:   position: relative;
                   9054:   top: 1px;
                   9055: }
                   9056: 
1.870     tempelho 9057: ul.LC_TabContentBigger li a {
1.911     bisitz   9058:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   9059:   height: 30px;
                   9060:   line-height: 30px;
                   9061:   text-align: center;
                   9062:   display: block;
                   9063:   text-decoration: none;
1.958     onken    9064:   outline: none;  
1.741     harmsja  9065: }
1.795     www      9066: 
1.870     tempelho 9067: ul.LC_TabContentBigger li.active a {
1.911     bisitz   9068:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   9069:   color:$font;
1.744     ehlerst  9070: }
1.795     www      9071: 
1.870     tempelho 9072: ul.LC_TabContentBigger li b {
1.911     bisitz   9073:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   9074:   display: block;
                   9075:   float: left;
                   9076:   padding: 0 30px;
1.957     onken    9077:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 9078: }
                   9079: 
1.956     onken    9080: ul.LC_TabContentBigger li:hover b {
                   9081:   color:$button_hover;
                   9082: }
                   9083: 
1.870     tempelho 9084: ul.LC_TabContentBigger li.active b {
1.911     bisitz   9085:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   9086:   color:$font;
1.957     onken    9087:   border: 0;
1.741     harmsja  9088: }
1.693     droeschl 9089: 
1.870     tempelho 9090: 
1.862     bisitz   9091: ul.LC_CourseBreadcrumbs {
                   9092:   background: $sidebg;
1.1020    raeburn  9093:   height: 2em;
1.862     bisitz   9094:   padding-left: 10px;
1.1020    raeburn  9095:   margin: 0;
1.862     bisitz   9096:   list-style-position: inside;
                   9097: }
                   9098: 
1.911     bisitz   9099: ol#LC_MenuBreadcrumbs,
1.862     bisitz   9100: ol#LC_PathBreadcrumbs {
1.911     bisitz   9101:   padding-left: 10px;
                   9102:   margin: 0;
1.933     droeschl 9103:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 9104: }
                   9105: 
1.911     bisitz   9106: ol#LC_MenuBreadcrumbs li,
                   9107: ol#LC_PathBreadcrumbs li,
1.862     bisitz   9108: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   9109:   display: inline;
1.933     droeschl 9110:   white-space: normal;  
1.693     droeschl 9111: }
                   9112: 
1.823     bisitz   9113: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   9114: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   9115:   text-decoration: none;
                   9116:   font-size:90%;
1.693     droeschl 9117: }
1.795     www      9118: 
1.969     droeschl 9119: ol#LC_MenuBreadcrumbs h1 {
                   9120:   display: inline;
                   9121:   font-size: 90%;
                   9122:   line-height: 2.5em;
                   9123:   margin: 0;
                   9124:   padding: 0;
                   9125: }
                   9126: 
1.795     www      9127: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   9128:   text-decoration:none;
                   9129:   font-size:100%;
                   9130:   font-weight:bold;
1.693     droeschl 9131: }
1.795     www      9132: 
1.840     bisitz   9133: .LC_Box {
1.911     bisitz   9134:   border: solid 1px $lg_border_color;
                   9135:   padding: 0 10px 10px 10px;
1.746     neumanie 9136: }
1.795     www      9137: 
1.1020    raeburn  9138: .LC_DocsBox {
                   9139:   border: solid 1px $lg_border_color;
                   9140:   padding: 0 0 10px 10px;
                   9141: }
                   9142: 
1.795     www      9143: .LC_AboutMe_Image {
1.911     bisitz   9144:   float:left;
                   9145:   margin-right:10px;
1.747     neumanie 9146: }
1.795     www      9147: 
                   9148: .LC_Clear_AboutMe_Image {
1.911     bisitz   9149:   clear:left;
1.747     neumanie 9150: }
1.795     www      9151: 
1.721     harmsja  9152: dl.LC_ListStyleClean dt {
1.911     bisitz   9153:   padding-right: 5px;
                   9154:   display: table-header-group;
1.693     droeschl 9155: }
                   9156: 
1.721     harmsja  9157: dl.LC_ListStyleClean dd {
1.911     bisitz   9158:   display: table-row;
1.693     droeschl 9159: }
                   9160: 
1.721     harmsja  9161: .LC_ListStyleClean,
                   9162: .LC_ListStyleSimple,
                   9163: .LC_ListStyleNormal,
1.795     www      9164: .LC_ListStyleSpecial {
1.911     bisitz   9165:   /* display:block; */
                   9166:   list-style-position: inside;
                   9167:   list-style-type: none;
                   9168:   overflow: hidden;
                   9169:   padding: 0;
1.693     droeschl 9170: }
                   9171: 
1.721     harmsja  9172: .LC_ListStyleSimple li,
                   9173: .LC_ListStyleSimple dd,
                   9174: .LC_ListStyleNormal li,
                   9175: .LC_ListStyleNormal dd,
                   9176: .LC_ListStyleSpecial li,
1.795     www      9177: .LC_ListStyleSpecial dd {
1.911     bisitz   9178:   margin: 0;
                   9179:   padding: 5px 5px 5px 10px;
                   9180:   clear: both;
1.693     droeschl 9181: }
                   9182: 
1.721     harmsja  9183: .LC_ListStyleClean li,
                   9184: .LC_ListStyleClean dd {
1.911     bisitz   9185:   padding-top: 0;
                   9186:   padding-bottom: 0;
1.693     droeschl 9187: }
                   9188: 
1.721     harmsja  9189: .LC_ListStyleSimple dd,
1.795     www      9190: .LC_ListStyleSimple li {
1.911     bisitz   9191:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9192: }
                   9193: 
1.721     harmsja  9194: .LC_ListStyleSpecial li,
                   9195: .LC_ListStyleSpecial dd {
1.911     bisitz   9196:   list-style-type: none;
                   9197:   background-color: RGB(220, 220, 220);
                   9198:   margin-bottom: 4px;
1.693     droeschl 9199: }
                   9200: 
1.721     harmsja  9201: table.LC_SimpleTable {
1.911     bisitz   9202:   margin:5px;
                   9203:   border:solid 1px $lg_border_color;
1.795     www      9204: }
1.693     droeschl 9205: 
1.721     harmsja  9206: table.LC_SimpleTable tr {
1.911     bisitz   9207:   padding: 0;
                   9208:   border:solid 1px $lg_border_color;
1.693     droeschl 9209: }
1.795     www      9210: 
                   9211: table.LC_SimpleTable thead {
1.911     bisitz   9212:   background:rgb(220,220,220);
1.693     droeschl 9213: }
                   9214: 
1.721     harmsja  9215: div.LC_columnSection {
1.911     bisitz   9216:   display: block;
                   9217:   clear: both;
                   9218:   overflow: hidden;
                   9219:   margin: 0;
1.693     droeschl 9220: }
                   9221: 
1.721     harmsja  9222: div.LC_columnSection>* {
1.911     bisitz   9223:   float: left;
                   9224:   margin: 10px 20px 10px 0;
                   9225:   overflow:hidden;
1.693     droeschl 9226: }
1.721     harmsja  9227: 
1.795     www      9228: table em {
1.911     bisitz   9229:   font-weight: bold;
                   9230:   font-style: normal;
1.748     schulted 9231: }
1.795     www      9232: 
1.779     bisitz   9233: table.LC_tableBrowseRes,
1.795     www      9234: table.LC_tableOfContent {
1.911     bisitz   9235:   border:none;
                   9236:   border-spacing: 1px;
                   9237:   padding: 3px;
                   9238:   background-color: #FFFFFF;
                   9239:   font-size: 90%;
1.753     droeschl 9240: }
1.789     droeschl 9241: 
1.911     bisitz   9242: table.LC_tableOfContent {
                   9243:   border-collapse: collapse;
1.789     droeschl 9244: }
                   9245: 
1.771     droeschl 9246: table.LC_tableBrowseRes a,
1.768     schulted 9247: table.LC_tableOfContent a {
1.911     bisitz   9248:   background-color: transparent;
                   9249:   text-decoration: none;
1.753     droeschl 9250: }
                   9251: 
1.795     www      9252: table.LC_tableOfContent img {
1.911     bisitz   9253:   border: none;
                   9254:   height: 1.3em;
                   9255:   vertical-align: text-bottom;
                   9256:   margin-right: 0.3em;
1.753     droeschl 9257: }
1.757     schulted 9258: 
1.795     www      9259: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9260:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9261: }
                   9262: 
1.795     www      9263: a#LC_content_toolbar_everything {
1.911     bisitz   9264:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9265: }
                   9266: 
1.795     www      9267: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9268:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9269: }
                   9270: 
1.795     www      9271: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9272:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9273: }
                   9274: 
1.795     www      9275: a#LC_content_toolbar_changefolder {
1.911     bisitz   9276:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9277: }
                   9278: 
1.795     www      9279: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9280:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9281: }
                   9282: 
1.1043    raeburn  9283: a#LC_content_toolbar_edittoplevel {
                   9284:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9285: }
                   9286: 
1.1384    raeburn  9287: a#LC_content_toolbar_printout {
                   9288:   background-image:url(/res/adm/pages/printout.gif);
                   9289: }
                   9290: 
1.795     www      9291: ul#LC_toolbar li a:hover {
1.911     bisitz   9292:   background-position: bottom center;
1.757     schulted 9293: }
                   9294: 
1.795     www      9295: ul#LC_toolbar {
1.911     bisitz   9296:   padding: 0;
                   9297:   margin: 2px;
                   9298:   list-style:none;
1.1449    raeburn  9299:   display:inline;
1.911     bisitz   9300:   background-color:white;
1.1082    raeburn  9301:   overflow: auto;
1.757     schulted 9302: }
                   9303: 
1.795     www      9304: ul#LC_toolbar li {
1.911     bisitz   9305:   border:1px solid white;
                   9306:   padding: 0;
                   9307:   margin: 0;
                   9308:   float: left;
                   9309:   display:inline;
                   9310:   vertical-align:middle;
1.1082    raeburn  9311:   white-space: nowrap;
1.911     bisitz   9312: }
1.757     schulted 9313: 
1.783     amueller 9314: 
1.795     www      9315: a.LC_toolbarItem {
1.911     bisitz   9316:   display:block;
                   9317:   padding: 0;
                   9318:   margin: 0;
                   9319:   height: 32px;
                   9320:   width: 32px;
                   9321:   color:white;
                   9322:   border: none;
                   9323:   background-repeat:no-repeat;
                   9324:   background-color:transparent;
1.757     schulted 9325: }
                   9326: 
1.1449    raeburn  9327: .LC_navtools {
                   9328:   display: inline-block;
                   9329:   padding: 0;
                   9330:   margin: 2px;
                   9331:   vertical-align: middle;
                   9332: }
                   9333: 
1.915     droeschl 9334: ul.LC_funclist {
                   9335:     margin: 0;
                   9336:     padding: 0.5em 1em 0.5em 0;
                   9337: }
                   9338: 
1.933     droeschl 9339: ul.LC_funclist > li:first-child {
                   9340:     font-weight:bold; 
                   9341:     margin-left:0.8em;
                   9342: }
                   9343: 
1.915     droeschl 9344: ul.LC_funclist + ul.LC_funclist {
                   9345:     /* 
                   9346:        left border as a seperator if we have more than
                   9347:        one list 
                   9348:     */
                   9349:     border-left: 1px solid $sidebg;
                   9350:     /* 
                   9351:        this hides the left border behind the border of the 
                   9352:        outer box if element is wrapped to the next 'line' 
                   9353:     */
                   9354:     margin-left: -1px;
                   9355: }
                   9356: 
1.843     bisitz   9357: ul.LC_funclist li {
1.915     droeschl 9358:   display: inline;
1.782     bisitz   9359:   white-space: nowrap;
1.915     droeschl 9360:   margin: 0 0 0 25px;
                   9361:   line-height: 150%;
1.782     bisitz   9362: }
                   9363: 
1.974     wenzelju 9364: .LC_hidden {
                   9365:   display: none;
                   9366: }
                   9367: 
1.1030    www      9368: .LCmodal-overlay {
                   9369: 		position:fixed;
                   9370: 		top:0;
                   9371: 		right:0;
                   9372: 		bottom:0;
                   9373: 		left:0;
                   9374: 		height:100%;
                   9375: 		width:100%;
                   9376: 		margin:0;
                   9377: 		padding:0;
                   9378: 		background:#999;
                   9379: 		opacity:.75;
                   9380: 		filter: alpha(opacity=75);
                   9381: 		-moz-opacity: 0.75;
                   9382: 		z-index:101;
                   9383: }
                   9384: 
                   9385: * html .LCmodal-overlay {   
                   9386: 		position: absolute;
                   9387: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9388: }
                   9389: 
                   9390: .LCmodal-window {
                   9391: 		position:fixed;
                   9392: 		top:50%;
                   9393: 		left:50%;
                   9394: 		margin:0;
                   9395: 		padding:0;
                   9396: 		z-index:102;
                   9397: 	}
                   9398: 
                   9399: * html .LCmodal-window {
                   9400: 		position:absolute;
                   9401: }
                   9402: 
                   9403: .LCclose-window {
                   9404: 		position:absolute;
                   9405: 		width:32px;
                   9406: 		height:32px;
                   9407: 		right:8px;
                   9408: 		top:8px;
                   9409: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9410: 		text-indent:-99999px;
                   9411: 		overflow:hidden;
                   9412: 		cursor:pointer;
                   9413: }
                   9414: 
1.1369    raeburn  9415: .LCisDisabled {
                   9416:   cursor: not-allowed;
                   9417:   opacity: 0.5;
                   9418: }
                   9419: 
                   9420: a[aria-disabled="true"] {
                   9421:   color: currentColor;
                   9422:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9423:   pointer-events: none;
                   9424:   text-decoration: none;
                   9425: }
                   9426: 
1.1335    raeburn  9427: pre.LC_wordwrap {
                   9428:   white-space: pre-wrap;
                   9429:   white-space: -moz-pre-wrap;
                   9430:   white-space: -pre-wrap;
                   9431:   white-space: -o-pre-wrap;
                   9432:   word-wrap: break-word;
                   9433: }
                   9434: 
1.1100    raeburn  9435: /*
1.1231    damieng  9436:   styles used for response display
                   9437: */
1.1464    raeburn  9438: div.LC_radiofoil, div.LC_rankfoil, div.LC_optionfoil, div.LC_matchfoil, div.LC_login_links {
1.1231    damieng  9439:   margin: .5em 0em .5em 0em;
                   9440: }
                   9441: table.LC_itemgroup {
                   9442:   margin-top: 1em;
                   9443: }
                   9444: 
1.1462    raeburn  9445: table.LC_itemgroup tr th {
                   9446:   font-weight: normal;
                   9447: }
                   9448: 
                   9449: fieldset.LC_webbubbles {
                   9450:   margin: 2px 0 0 0;
                   9451:   padding: 0;
                   9452:   border: 0;
                   9453: }
                   9454: 
                   9455: ul.LC_webbubbles {
                   9456:   list-style: none;
                   9457:   padding: 0;
                   9458:   margin: 0;
                   9459:   text-align: left;
                   9460:   float: left;
                   9461: }
                   9462: 
                   9463: ul.LC_webbubbles li {
                   9464:   line-height: 1.8em;
                   9465:   border: 1px solid black;
                   9466:   padding: 0 2px 0 5px;
                   9467:   margin: 0 0 0 -1px;
                   9468:   float: left;
                   9469: }
                   9470: 
1.1231    damieng  9471: /*
1.1100    raeburn  9472:   styles used by TTH when "Default set of options to pass to tth/m
                   9473:   when converting TeX" in course settings has been set
                   9474: 
                   9475:   option passed: -t
                   9476: 
                   9477: */
                   9478: 
                   9479: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9480: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9481: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9482: td div.norm {line-height:normal;}
                   9483: 
                   9484: /*
                   9485:   option passed -y3
                   9486: */
                   9487: 
                   9488: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9489: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9490: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9491: 
1.1230    damieng  9492: /*
                   9493:   sections with roles, for content only
                   9494: */
                   9495: section[class^="role-"] {
                   9496:   padding-left: 10px;
                   9497:   padding-right: 5px;
                   9498:   margin-top: 8px;
                   9499:   margin-bottom: 8px;
                   9500:   border: 1px solid #2A4;
                   9501:   border-radius: 5px;
                   9502:   box-shadow: 0px 1px 1px #BBB;
                   9503: }
                   9504: section[class^="role-"]>h1 {
                   9505:   position: relative;
                   9506:   margin: 0px;
                   9507:   padding-top: 10px;
                   9508:   padding-left: 40px;
                   9509: }
                   9510: section[class^="role-"]>h1:before {
                   9511:   position: absolute;
                   9512:   left: -5px;
                   9513:   top: 5px;
                   9514: }
                   9515: section.role-activity>h1:before {
                   9516:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9517: }
                   9518: section.role-advice>h1:before {
                   9519:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9520: }
                   9521: section.role-bibliography>h1:before {
                   9522:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9523: }
                   9524: section.role-citation>h1:before {
                   9525:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9526: }
                   9527: section.role-conclusion>h1:before {
                   9528:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9529: }
                   9530: section.role-definition>h1:before {
                   9531:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9532: }
                   9533: section.role-demonstration>h1:before {
                   9534:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9535: }
                   9536: section.role-example>h1:before {
                   9537:   content:url('/adm/daxe/images/section_icons/example.png');
                   9538: }
                   9539: section.role-explanation>h1:before {
                   9540:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9541: }
                   9542: section.role-introduction>h1:before {
                   9543:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9544: }
                   9545: section.role-method>h1:before {
                   9546:   content:url('/adm/daxe/images/section_icons/method.png');
                   9547: }
                   9548: section.role-more_information>h1:before {
                   9549:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9550: }
                   9551: section.role-objectives>h1:before {
                   9552:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9553: }
                   9554: section.role-prerequisites>h1:before {
                   9555:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9556: }
                   9557: section.role-remark>h1:before {
                   9558:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9559: }
                   9560: section.role-reminder>h1:before {
                   9561:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9562: }
                   9563: section.role-summary>h1:before {
                   9564:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9565: }
                   9566: section.role-syntax>h1:before {
                   9567:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9568: }
                   9569: section.role-warning>h1:before {
                   9570:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9571: }
                   9572: 
1.1269    raeburn  9573: #LC_minitab_header {
                   9574:   float:left;
                   9575:   width:100%;
                   9576:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9577:   font-size:93%;
                   9578:   line-height:normal;
                   9579:   margin: 0.5em 0 0.5em 0;
                   9580: }
                   9581: #LC_minitab_header ul {
                   9582:   margin:0;
                   9583:   padding:10px 10px 0;
                   9584:   list-style:none;
                   9585: }
                   9586: #LC_minitab_header li {
                   9587:   float:left;
                   9588:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9589:   margin:0;
                   9590:   padding:0 0 0 9px;
                   9591: }
                   9592: #LC_minitab_header a {
                   9593:   display:block;
                   9594:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9595:   padding:5px 15px 4px 6px;
                   9596: }
                   9597: #LC_minitab_header #LC_current_minitab {
                   9598:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9599: }
                   9600: #LC_minitab_header #LC_current_minitab a {
                   9601:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9602:   padding-bottom:5px;
                   9603: }
                   9604: 
                   9605: 
1.343     albertel 9606: END
                   9607: }
                   9608: 
1.306     albertel 9609: =pod
                   9610: 
                   9611: =item * &headtag()
                   9612: 
                   9613: Returns a uniform footer for LON-CAPA web pages.
                   9614: 
1.307     albertel 9615: Inputs: $title - optional title for the head
                   9616:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9617:         $args - optional arguments
1.319     albertel 9618:             force_register - if is true call registerurl so the remote is 
                   9619:                              informed
1.415     albertel 9620:             redirect       -> array ref of
                   9621:                                    1- seconds before redirect occurs
                   9622:                                    2- url to redirect to
                   9623:                                    3- whether the side effect should occur
1.315     albertel 9624:                            (side effect of setting 
                   9625:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9626:                                redirected to)
                   9627:                                    4- whether the redirect target should be
                   9628:                                       the opener of the current (pop-up)
                   9629:                                       window (side effect of setting
                   9630:                                       $env{'internal.head.to_opener'} to
                   9631:                                       1, if true.
1.1388    raeburn  9632:                                    5- whether encrypt check should be skipped
1.352     albertel 9633:             domain         -> force to color decorate a page for a specific
                   9634:                                domain
                   9635:             function       -> force usage of a specific rolish color scheme
                   9636:             bgcolor        -> override the default page bgcolor
1.460     albertel 9637:             no_auto_mt_title
                   9638:                            -> prevent &mt()ing the title arg
1.464     albertel 9639: 
1.306     albertel 9640: =cut
                   9641: 
                   9642: sub headtag {
1.313     albertel 9643:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9644:     
1.363     albertel 9645:     my $function = $args->{'function'} || &get_users_function();
                   9646:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9647:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9648:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9649:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9650: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9651: 		   #time(),
1.418     albertel 9652: 		   $env{'environment.color.timestamp'},
1.363     albertel 9653: 		   $function,$domain,$bgcolor);
                   9654: 
1.369     www      9655:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9656: 
1.308     albertel 9657:     my $result =
                   9658: 	'<head>'.
1.1160    raeburn  9659: 	&font_settings($args);
1.319     albertel 9660: 
1.1188    raeburn  9661:     my $inhibitprint;
                   9662:     if ($args->{'print_suppress'}) {
                   9663:         $inhibitprint = &print_suppression();
                   9664:     }
1.1064    raeburn  9665: 
1.1439    raeburn  9666:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9667: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9668:     }
1.962     droeschl 9669:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9670:         $result .= Apache::lonxml::display_title();
1.319     albertel 9671:     }
1.436     albertel 9672:     if (!$args->{'no_nav_bar'} 
                   9673: 	&& !$args->{'only_body'}
1.1438    raeburn  9674: 	&& !$args->{'frameset'}
                   9675: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9676: 	$result .= &help_menu_js($httphost);
1.1032    www      9677:         $result.=&modal_window();
1.1038    www      9678:         $result.=&togglebox_script();
1.1034    www      9679:         $result.=&wishlist_window();
1.1041    www      9680:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9681:     } else {
                   9682:         if ($args->{'add_modal'}) {
                   9683:            $result.=&modal_window();
                   9684:         }
                   9685:         if ($args->{'add_wishlist'}) {
                   9686:            $result.=&wishlist_window();
                   9687:         }
1.1038    www      9688:         if ($args->{'add_togglebox'}) {
                   9689:            $result.=&togglebox_script();
                   9690:         }
1.1041    www      9691:         if ($args->{'add_progressbar'}) {
                   9692:            $result.=&LCprogressbarUpdate_script();
                   9693:         }
1.436     albertel 9694:     }
1.314     albertel 9695:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9696: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9697:         if (!$skip_enc_check) {
                   9698:             $url = &Apache::lonenc::check_encrypt($url);
                   9699:         }
1.414     albertel 9700: 	if (!$inhibit_continue) {
                   9701: 	    $env{'internal.head.redirect'} = $url;
                   9702: 	}
1.1386    raeburn  9703: 	$result.=<<"ADDMETA";
1.313     albertel 9704: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9705: ADDMETA
                   9706:         if ($to_opener) {
                   9707:             $env{'internal.head.to_opener'} = 1;
                   9708:             my $dest = &js_escape($url);
                   9709:             my $timeout = int($time * 1000);
                   9710:             $result .=<<"ENDJS";
                   9711: <script type="text/javascript">
                   9712: // <![CDATA[
                   9713: function LC_To_Opener() {
                   9714:     var dest = '$dest';
                   9715:     if (dest != '') {
                   9716:         if (window.opener != null && !window.opener.closed) {
                   9717:             window.opener.location.href=dest;
                   9718:             window.close();
                   9719:         } else {
                   9720:             window.location.href=dest;
                   9721:         }
                   9722:     }
                   9723: }
                   9724: \$(document).ready(function () {
                   9725:     setTimeout('LC_To_Opener()',$timeout);
                   9726: });
                   9727: // ]]>
                   9728: </script>
                   9729: ENDJS
                   9730:         } else {
                   9731:             $result.=<<"ADDMETA";
1.344     albertel 9732: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9733: ADDMETA
1.1386    raeburn  9734:         }
1.1210    raeburn  9735:     } else {
                   9736:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9737:             my $requrl = $env{'request.uri'};
                   9738:             if ($requrl eq '') {
                   9739:                 $requrl = $ENV{'REQUEST_URI'};
                   9740:                 $requrl =~ s/\?.+$//;
                   9741:             }
                   9742:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9743:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9744:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9745:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9746:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9747:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9748:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9749:                     my ($offload,$offloadoth);
1.1210    raeburn  9750:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9751:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9752:                             $offload = 1;
1.1353    raeburn  9753:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9754:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9755:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9756:                                     $offloadoth = 1;
                   9757:                                     $dom_in_use = $env{'user.domain'};
                   9758:                                 }
                   9759:                             }
1.1340    raeburn  9760:                         }
                   9761:                     }
                   9762:                     unless ($offload) {
                   9763:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9764:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9765:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9766:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9767:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9768:                                         $offload = 1;
1.1352    raeburn  9769:                                         $offloadoth = 1;
1.1340    raeburn  9770:                                         $dom_in_use = $env{'user.domain'};
                   9771:                                     }
1.1210    raeburn  9772:                                 }
1.1340    raeburn  9773:                             }
                   9774:                         }
                   9775:                     }
                   9776:                     if ($offload) {
1.1358    raeburn  9777:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9778:                         if (($newserver eq '') && ($offloadoth)) {
                   9779:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9780:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9781:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9782:                             }
                   9783:                         }
1.1340    raeburn  9784:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9785:                             my $numsec = 5;
                   9786:                             my $timeout = $numsec * 1000;
                   9787:                             my ($newurl,$locknum,%locks,$msg);
                   9788:                             if ($env{'request.role.adv'}) {
                   9789:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9790:                             }
                   9791:                             my $disable_submit = 0;
                   9792:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9793:                                 $disable_submit = 1;
                   9794:                             }
                   9795:                             if ($locknum) {
                   9796:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9797:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9798:                                        join(", ",sort(values(%locks)))."\n";
                   9799:                                 if (&show_course()) {
                   9800:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9801:                                 } else {
                   9802:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9803:                                 }
1.1340    raeburn  9804:                             } else {
                   9805:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9806:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9807:                                 }
                   9808:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9809:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9810:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9811:                                     $newurl .= '&role='.$env{'request.role'};
                   9812:                                 }
                   9813:                                 if ($env{'request.symb'}) {
                   9814:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9815:                                     if ($shownsymb =~ m{^/enc/}) {
                   9816:                                         my $reqdmajor = 2;
                   9817:                                         my $reqdminor = 11;
                   9818:                                         my $reqdsubminor = 3;
                   9819:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9820:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9821:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9822:                                         if (($major eq '' && $minor eq '') ||
                   9823:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9824:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9825:                                              ($reqdsubminor > $subminor))))) {
                   9826:                                             undef($shownsymb);
                   9827:                                         }
1.1210    raeburn  9828:                                     }
1.1340    raeburn  9829:                                     if ($shownsymb) {
                   9830:                                         &js_escape(\$shownsymb);
                   9831:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9832:                                     }
1.1340    raeburn  9833:                                 } else {
                   9834:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9835:                                     &js_escape(\$shownurl);
                   9836:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9837:                                 }
1.1340    raeburn  9838:                             }
                   9839:                             &js_escape(\$msg);
                   9840:                             $result.=<<OFFLOAD
1.1210    raeburn  9841: <meta http-equiv="pragma" content="no-cache" />
                   9842: <script type="text/javascript">
1.1215    raeburn  9843: // <![CDATA[
1.1210    raeburn  9844: function LC_Offload_Now() {
                   9845:     var dest = "$newurl";
                   9846:     if (dest != '') {
                   9847:         window.location.href="$newurl";
                   9848:     }
                   9849: }
1.1214    raeburn  9850: \$(document).ready(function () {
                   9851:     window.alert('$msg');
                   9852:     if ($disable_submit) {
1.1210    raeburn  9853:         \$(".LC_hwk_submit").prop("disabled", true);
                   9854:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9855:     }
                   9856:     setTimeout('LC_Offload_Now()', $timeout);
                   9857: });
1.1215    raeburn  9858: // ]]>
1.1210    raeburn  9859: </script>
                   9860: OFFLOAD
                   9861:                         }
                   9862:                     }
                   9863:                 }
                   9864:             }
                   9865:         }
1.313     albertel 9866:     }
1.306     albertel 9867:     if (!defined($title)) {
                   9868: 	$title = 'The LearningOnline Network with CAPA';
                   9869:     }
1.460     albertel 9870:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9871:     if ($title =~ /^LON-CAPA\s+/) {
                   9872:         $result .= '<title> '.$title.'</title>';
                   9873:     } else {
                   9874:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9875:     }
                   9876:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9877:     if (!$args->{'frameset'}) {
                   9878:         $result .= ' /';
                   9879:     }
                   9880:     $result .= '>' 
1.1064    raeburn  9881:         .$inhibitprint
1.414     albertel 9882: 	.$head_extra;
1.1242    raeburn  9883:     my $clientmobile;
                   9884:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9885:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9886:     } else {
                   9887:         $clientmobile = $env{'browser.mobile'};
                   9888:     }
                   9889:     if ($clientmobile) {
1.1137    raeburn  9890:         $result .= '
1.1435    raeburn  9891: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9892: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9893:     }
1.1455    raeburn  9894:     $result .= '<meta name="google" content="notranslate"';
                   9895:     if (!$args->{'frameset'}) {
                   9896:         $result .= ' /';
                   9897:     }
                   9898:     $result .= '>'."\n";
1.962     droeschl 9899:     return $result.'</head>';
1.306     albertel 9900: }
                   9901: 
                   9902: =pod
                   9903: 
1.340     albertel 9904: =item * &font_settings()
                   9905: 
                   9906: Returns neccessary <meta> to set the proper encoding
                   9907: 
1.1160    raeburn  9908: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9909: 
                   9910: =cut
                   9911: 
                   9912: sub font_settings {
1.1160    raeburn  9913:     my ($args) = @_;
1.340     albertel 9914:     my $headerstring='';
1.1160    raeburn  9915:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9916:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9917:         $headerstring.=
                   9918:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9919:         if (!$args->{'frameset'}) {
                   9920: 	    $headerstring.= ' /';
                   9921:         }
                   9922: 	$headerstring .= '>'."\n";
1.340     albertel 9923:     }
                   9924:     return $headerstring;
                   9925: }
                   9926: 
1.341     albertel 9927: =pod
                   9928: 
1.1064    raeburn  9929: =item * &print_suppression()
                   9930: 
                   9931: In course context returns css which causes the body to be blank when media="print",
                   9932: if printout generation is unavailable for the current resource.
                   9933: 
                   9934: This could be because:
                   9935: 
                   9936: (a) printstartdate is in the future
                   9937: 
                   9938: (b) printenddate is in the past
                   9939: 
                   9940: (c) there is an active exam block with "printout"
                   9941: functionality blocked
                   9942: 
                   9943: Users with pav, pfo or evb privileges are exempt.
                   9944: 
                   9945: Inputs: none
                   9946: 
                   9947: =cut
                   9948: 
                   9949: 
                   9950: sub print_suppression {
                   9951:     my $noprint;
                   9952:     if ($env{'request.course.id'}) {
                   9953:         my $scope = $env{'request.course.id'};
                   9954:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9955:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9956:             return;
                   9957:         }
                   9958:         if ($env{'request.course.sec'} ne '') {
                   9959:             $scope .= "/$env{'request.course.sec'}";
                   9960:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9961:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9962:                 return;
1.1064    raeburn  9963:             }
                   9964:         }
                   9965:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9966:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9967:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9968:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9969:         if ($blocked) {
                   9970:             my $checkrole = "cm./$cdom/$cnum";
                   9971:             if ($env{'request.course.sec'} ne '') {
                   9972:                 $checkrole .= "/$env{'request.course.sec'}";
                   9973:             }
                   9974:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9975:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9976:                 $noprint = 1;
                   9977:             }
                   9978:         }
                   9979:         unless ($noprint) {
                   9980:             my $symb = &Apache::lonnet::symbread();
                   9981:             if ($symb ne '') {
                   9982:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9983:                 if (ref($navmap)) {
                   9984:                     my $res = $navmap->getBySymb($symb);
                   9985:                     if (ref($res)) {
                   9986:                         if (!$res->resprintable()) {
                   9987:                             $noprint = 1;
                   9988:                         }
                   9989:                     }
                   9990:                 }
                   9991:             }
                   9992:         }
                   9993:         if ($noprint) {
                   9994:             return <<"ENDSTYLE";
                   9995: <style type="text/css" media="print">
                   9996:     body { display:none }
                   9997: </style>
                   9998: ENDSTYLE
                   9999:         }
                   10000:     }
                   10001:     return;
                   10002: }
                   10003: 
                   10004: =pod
                   10005: 
1.341     albertel 10006: =item * &xml_begin()
                   10007: 
                   10008: Returns the needed doctype and <html>
                   10009: 
                   10010: Inputs: none
                   10011: 
                   10012: =cut
                   10013: 
                   10014: sub xml_begin {
1.1168    raeburn  10015:     my ($is_frameset) = @_;
1.341     albertel 10016:     my $output='';
                   10017: 
                   10018:     if ($env{'browser.mathml'}) {
                   10019: 	$output='<?xml version="1.0"?>'
                   10020:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   10021: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   10022:             
                   10023: #	    .'<!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">] >'
                   10024: 	    .'<!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">'
                   10025:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   10026: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  10027:     } elsif ($is_frameset) {
                   10028:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
1.1459    raeburn  10029:                 '<html lang="en">'."\n";
1.341     albertel 10030:     } else {
1.1168    raeburn  10031: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   10032:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 10033:     }
                   10034:     return $output;
                   10035: }
1.340     albertel 10036: 
                   10037: =pod
                   10038: 
1.306     albertel 10039: =item * &start_page()
                   10040: 
                   10041: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   10042: 
1.648     raeburn  10043: Inputs:
                   10044: 
                   10045: =over 4
                   10046: 
                   10047: $title - optional title for the page
                   10048: 
                   10049: $head_extra - optional extra HTML to incude inside the <head>
                   10050: 
                   10051: $args - additional optional args supported are:
                   10052: 
                   10053: =over 8
                   10054: 
                   10055:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 10056:                                     arg on
1.814     bisitz   10057:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  10058:              add_entries    -> additional attributes to add to the  <body>
                   10059:              domain         -> force to color decorate a page for a 
1.317     albertel 10060:                                     specific domain
1.648     raeburn  10061:              function       -> force usage of a specific rolish color
1.317     albertel 10062:                                     scheme
1.648     raeburn  10063:              redirect       -> see &headtag()
                   10064:              bgcolor        -> override the default page bg color
                   10065:              js_ready       -> return a string ready for being used in 
1.317     albertel 10066:                                     a javascript writeln
1.648     raeburn  10067:              html_encode    -> return a string ready for being used in 
1.320     albertel 10068:                                     a html attribute
1.648     raeburn  10069:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 10070:                                     $forcereg arg
1.648     raeburn  10071:              frameset       -> if true will start with a <frameset>
1.330     albertel 10072:                                     rather than <body>
1.648     raeburn  10073:              skip_phases    -> hash ref of 
1.338     albertel 10074:                                     head -> skip the <html><head> generation
                   10075:                                     body -> skip all <body> generation
1.648     raeburn  10076:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 10077:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  10078:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  10079:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   10080:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   10081:                                    to override those values, or add to them, specify the value to
                   10082:                                    include in the style attribute to include in the div tag by using
                   10083:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  10084:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   10085:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  10086:              group          -> includes the current group, if page is for a 
1.1274    raeburn  10087:                                specific group
                   10088:              use_absolute   -> for request for external resource or syllabus, this
                   10089:                                will contain https://<hostname> if server uses
                   10090:                                https (as per hosts.tab), but request is for http
                   10091:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  10092:              links_disabled -> Links in primary and secondary menus are disabled
                   10093:                                (Can enable them once page has loaded - see lonroles.pm
                   10094:                                for an example).
1.1380    raeburn  10095:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 10096: 
1.648     raeburn  10097: =back
1.460     albertel 10098: 
1.648     raeburn  10099: =back
1.562     albertel 10100: 
1.306     albertel 10101: =cut
                   10102: 
                   10103: sub start_page {
1.309     albertel 10104:     my ($title,$head_extra,$args) = @_;
1.318     albertel 10105:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 10106: 
1.315     albertel 10107:     $env{'internal.start_page'}++;
1.1359    raeburn  10108:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 10109: 
1.338     albertel 10110:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  10111:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 10112:     }
1.1316    raeburn  10113: 
                   10114:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  10115:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   10116:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   10117:                 $args->{'no_primary_menu'} = 1;
                   10118:             }
                   10119:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   10120:                 $args->{'no_inline_menu'} = 1;
                   10121:             }
                   10122:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   10123:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   10124:             }
                   10125:         } else {
                   10126:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10127:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   10128:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   10129:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   10130:                     $args->{'no_primary_menu'} = 1;
                   10131:                 }
                   10132:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   10133:                     $args->{'no_inline_menu'} = 1;
                   10134:                 }
                   10135:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   10136:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   10137:                 }
                   10138:             }
                   10139:         }
1.1316    raeburn  10140:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   10141:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   10142:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  10143:     } elsif ($env{'request.course.id'}) {
                   10144:         my $expiretime=600;
                   10145:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   10146:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   10147:         }
                   10148:         my ($deeplinkmenu,$menuref);
                   10149:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   10150:         if ($menucoll) {
                   10151:             if (ref($menuref) eq 'HASH') {
                   10152:                 %menu = %{$menuref};
                   10153:             }
                   10154:             if ($menu{'top'} eq 'n') {
                   10155:                 $args->{'no_primary_menu'} = 1;
                   10156:             }
                   10157:             if ($menu{'inline'} eq 'n') {
                   10158:                 unless (&Apache::lonnet::allowed('opa')) {
                   10159:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10160:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10161:                     my $crstype = &course_type();
                   10162:                     my $now = time;
                   10163:                     my $ccrole;
                   10164:                     if ($crstype eq 'Community') {
                   10165:                         $ccrole = 'co';
                   10166:                     } else {
                   10167:                         $ccrole = 'cc';
                   10168:                     }
                   10169:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   10170:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   10171:                         if ((($start) && ($start<0)) ||
                   10172:                             (($end) && ($end<$now))  ||
                   10173:                             (($start) && ($now<$start))) {
                   10174:                             $args->{'no_inline_menu'} = 1;
                   10175:                         }
                   10176:                     } else {
                   10177:                         $args->{'no_inline_menu'} = 1;
                   10178:                     }
                   10179:                 }
                   10180:             }
                   10181:         }
1.1316    raeburn  10182:     }
1.1359    raeburn  10183: 
1.1385    raeburn  10184:     my $showncrumbs;
1.338     albertel 10185:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10186: 	if ($args->{'frameset'}) {
                   10187: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10188: 						$args->{'add_entries'});
                   10189: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10190:         } else {
                   10191:             $result .=
                   10192:                 &bodytag($title, 
                   10193:                          $args->{'function'},       $args->{'add_entries'},
                   10194:                          $args->{'only_body'},      $args->{'domain'},
                   10195:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10196:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10197:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10198:                          \%menu,\$showncrumbs);
1.831     bisitz   10199:         }
1.330     albertel 10200:     }
1.338     albertel 10201: 
1.315     albertel 10202:     if ($args->{'js_ready'}) {
1.713     kaisler  10203: 		$result = &js_ready($result);
1.315     albertel 10204:     }
1.320     albertel 10205:     if ($args->{'html_encode'}) {
1.713     kaisler  10206: 		$result = &html_encode($result);
                   10207:     }
                   10208: 
1.813     bisitz   10209:     # Preparation for new and consistent functionlist at top of screen
                   10210:     # if ($args->{'functionlist'}) {
                   10211:     #            $result .= &build_functionlist();
                   10212:     #}
                   10213: 
1.964     droeschl 10214:     # Don't add anything more if only_body wanted or in const space
                   10215:     return $result if    $args->{'only_body'} 
                   10216:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10217: 
                   10218:     #Breadcrumbs
1.758     kaisler  10219:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10220:         unless ($showncrumbs) {
1.758     kaisler  10221: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10222: 		#if any br links exists, add them to the breadcrumbs
                   10223: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10224: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10225: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10226: 			}
                   10227: 		}
1.1096    raeburn  10228:                 # if @advtools array contains items add then to the breadcrumbs
                   10229:                 if (@advtools > 0) {
                   10230:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10231:                 }
1.1272    raeburn  10232:                 my $menulink;
                   10233:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10234:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10235:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10236:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10237:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10238:                      (!$env{'request.role.adv'}))) {
                   10239:                     $menulink = 0;
                   10240:                 } else {
                   10241:                     undef($menulink);
                   10242:                 }
1.1385    raeburn  10243:                 my $linkprotout;
                   10244:                 if ($env{'request.deeplink.login'}) {
                   10245:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10246:                     if ($linkprotout) {
                   10247:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10248:                     }
                   10249:                 }
1.758     kaisler  10250: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10251: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10252: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10253:                                                                        '',$menulink,'',
                   10254:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10255:                 } else {
1.1437    raeburn  10256: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10257:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10258: 		}
1.1385    raeburn  10259:         }
1.320     albertel 10260:     }
1.315     albertel 10261:     return $result;
1.306     albertel 10262: }
                   10263: 
                   10264: sub end_page {
1.315     albertel 10265:     my ($args) = @_;
                   10266:     $env{'internal.end_page'}++;
1.330     albertel 10267:     my $result;
1.335     albertel 10268:     if ($args->{'discussion'}) {
                   10269: 	my ($target,$parser);
                   10270: 	if (ref($args->{'discussion'})) {
                   10271: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10272: 				$args->{'discussion'}{'parser'});
                   10273: 	}
                   10274: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10275:     }
1.330     albertel 10276:     if ($args->{'frameset'}) {
                   10277: 	$result .= '</frameset>';
                   10278:     } else {
1.635     raeburn  10279: 	$result .= &endbodytag($args);
1.330     albertel 10280:     }
1.1080    raeburn  10281:     unless ($args->{'notbody'}) {
                   10282:         $result .= "\n</html>";
                   10283:     }
1.330     albertel 10284: 
1.315     albertel 10285:     if ($args->{'js_ready'}) {
1.317     albertel 10286: 	$result = &js_ready($result);
1.315     albertel 10287:     }
1.335     albertel 10288: 
1.320     albertel 10289:     if ($args->{'html_encode'}) {
                   10290: 	$result = &html_encode($result);
                   10291:     }
1.335     albertel 10292: 
1.315     albertel 10293:     return $result;
                   10294: }
                   10295: 
1.1359    raeburn  10296: sub menucoll_in_effect {
                   10297:     my ($menucoll,$deeplinkmenu,%menu);
                   10298:     if ($env{'request.course.id'}) {
                   10299:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10300:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10301:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10302:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10303:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10304:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10305:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10306:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10307:                     if (ref($navmap)) {
                   10308:                         $deeplink = $navmap->get_mapparam(undef,
                   10309:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10310:                                                           '0.deeplink');
1.1370    raeburn  10311:                     } else {
                   10312:                         $check_login_symb = 1;
1.1362    raeburn  10313:                     }
                   10314:                 } else {
1.1370    raeburn  10315:                     my $symb = &Apache::lonnet::symbread();
                   10316:                     if ($symb) {
                   10317:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10318:                     } else {
                   10319:                         $check_login_symb = 1;
                   10320:                     }
1.1362    raeburn  10321:                 }
                   10322:             } else {
1.1370    raeburn  10323:                 $check_login_symb = 1;
                   10324:             }
                   10325:             if ($check_login_symb) {
1.1362    raeburn  10326:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10327:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10328:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10329:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10330:                     if (ref($navmap)) {
                   10331:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10332:                     }
                   10333:                 } else {
                   10334:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10335:                 }
                   10336:             }
1.1359    raeburn  10337:             if ($deeplink ne '') {
1.1378    raeburn  10338:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10339:                 if ($display =~ /^\d+$/) {
                   10340:                     $deeplinkmenu = 1;
                   10341:                     $menucoll = $display;
                   10342:                 }
                   10343:             }
                   10344:         }
                   10345:         if ($menucoll) {
                   10346:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10347:         }
                   10348:     }
                   10349:     return ($menucoll,$deeplinkmenu,\%menu);
                   10350: }
                   10351: 
1.1362    raeburn  10352: sub deeplink_login_symb {
                   10353:     my ($cnum,$cdom) = @_;
                   10354:     my $login_symb;
                   10355:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10356:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10357:     }
                   10358:     return $login_symb;
                   10359: }
                   10360: 
                   10361: sub symb_from_tinyurl {
                   10362:     my ($url,$cnum,$cdom) = @_;
                   10363:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10364:         my $key = $1;
                   10365:         my ($tinyurl,$login);
                   10366:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10367:         if (defined($cached)) {
                   10368:             $tinyurl = $result;
                   10369:         } else {
                   10370:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10371:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10372:             if ($currtiny{$key} ne '') {
                   10373:                 $tinyurl = $currtiny{$key};
                   10374:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10375:             }
1.1364    raeburn  10376:         }
                   10377:         if ($tinyurl ne '') {
                   10378:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10379:             if (wantarray) {
                   10380:                 return ($cnumreq,$symb);
                   10381:             } elsif ($cnumreq eq $cnum) {
                   10382:                 return $symb;
1.1362    raeburn  10383:             }
                   10384:         }
                   10385:     }
1.1364    raeburn  10386:     if (wantarray) {
                   10387:         return ();
                   10388:     } else {
                   10389:         return;
                   10390:     }
1.1362    raeburn  10391: }
                   10392: 
1.1405    raeburn  10393: sub usable_exttools {
                   10394:     my %tooltypes;
                   10395:     if ($env{'request.course.id'}) {
                   10396:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10397:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10398:                %tooltypes = (
                   10399:                              crs => 1,
                   10400:                              dom => 1,
                   10401:                             );
                   10402:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10403:                $tooltypes{'crs'} = 1;
                   10404:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10405:                $tooltypes{'dom'} = 1;
                   10406:            }
                   10407:         } else {
                   10408:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10409:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10410:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10411:             if ($crstype eq '') {
                   10412:                 $crstype = 'course';
                   10413:             }
                   10414:             if ($crstype eq 'course') {
                   10415:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10416:                     $crstype = 'official';
                   10417:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10418:                     $crstype = 'textbook';
                   10419:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10420:                     $crstype = 'lti';
                   10421:                 } else {
                   10422:                     $crstype = 'unofficial';
                   10423:                 }
                   10424:             }
                   10425:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10426:             if ($domdefaults{$crstype.'domexttool'}) {
                   10427:                 $tooltypes{'dom'} = 1;
                   10428:             }
                   10429:             if ($domdefaults{$crstype.'exttool'}) {
                   10430:                 $tooltypes{'crs'} = 1;
                   10431:             }
                   10432:         }
                   10433:     }
                   10434:     return %tooltypes;
                   10435: }
                   10436: 
1.1034    www      10437: sub wishlist_window {
                   10438:     return(<<'ENDWISHLIST');
1.1046    raeburn  10439: <script type="text/javascript">
1.1034    www      10440: // <![CDATA[
                   10441: // <!-- BEGIN LON-CAPA Internal
                   10442: function set_wishlistlink(title, path) {
                   10443:     if (!title) {
                   10444:         title = document.title;
                   10445:         title = title.replace(/^LON-CAPA /,'');
                   10446:     }
1.1175    raeburn  10447:     title = encodeURIComponent(title);
1.1203    raeburn  10448:     title = title.replace("'","\\\'");
1.1034    www      10449:     if (!path) {
                   10450:         path = location.pathname;
                   10451:     }
1.1175    raeburn  10452:     path = encodeURIComponent(path);
1.1203    raeburn  10453:     path = path.replace("'","\\\'");
1.1034    www      10454:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10455:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10456: }
                   10457: // END LON-CAPA Internal -->
                   10458: // ]]>
                   10459: </script>
                   10460: ENDWISHLIST
                   10461: }
                   10462: 
1.1030    www      10463: sub modal_window {
                   10464:     return(<<'ENDMODAL');
1.1046    raeburn  10465: <script type="text/javascript">
1.1030    www      10466: // <![CDATA[
                   10467: // <!-- BEGIN LON-CAPA Internal
                   10468: var modalWindow = {
                   10469: 	parent:"body",
                   10470: 	windowId:null,
                   10471: 	content:null,
                   10472: 	width:null,
                   10473: 	height:null,
                   10474: 	close:function()
                   10475: 	{
                   10476: 	        $(".LCmodal-window").remove();
                   10477: 	        $(".LCmodal-overlay").remove();
                   10478: 	},
                   10479: 	open:function()
                   10480: 	{
                   10481: 		var modal = "";
                   10482: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10483: 		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;\">";
                   10484: 		modal += this.content;
                   10485: 		modal += "</div>";	
                   10486: 
                   10487: 		$(this.parent).append(modal);
                   10488: 
                   10489: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10490: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10491: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10492: 	}
                   10493: };
1.1140    raeburn  10494: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10495: 	{
1.1266    raeburn  10496:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10497: 		modalWindow.windowId = "myModal";
                   10498: 		modalWindow.width = width;
                   10499: 		modalWindow.height = height;
1.1196    raeburn  10500: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10501: 		modalWindow.open();
1.1208    raeburn  10502: 	};
1.1030    www      10503: // END LON-CAPA Internal -->
                   10504: // ]]>
                   10505: </script>
                   10506: ENDMODAL
                   10507: }
                   10508: 
                   10509: sub modal_link {
1.1140    raeburn  10510:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10511:     unless ($width) { $width=480; }
                   10512:     unless ($height) { $height=400; }
1.1031    www      10513:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10514:     unless ($transparency) { $transparency='true'; }
                   10515: 
1.1074    raeburn  10516:     my $target_attr;
                   10517:     if (defined($target)) {
                   10518:         $target_attr = 'target="'.$target.'"';
                   10519:     }
                   10520:     return <<"ENDLINK";
1.1336    raeburn  10521: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10522: ENDLINK
1.1030    www      10523: }
                   10524: 
1.1032    www      10525: sub modal_adhoc_script {
1.1365    raeburn  10526:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10527:     my $mathjax;
                   10528:     if ($possmathjax) {
                   10529:         $mathjax = <<'ENDJAX';
                   10530:                if (typeof MathJax == 'object') {
                   10531:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10532:                }
                   10533: ENDJAX
                   10534:     }
1.1032    www      10535:     return (<<ENDADHOC);
1.1046    raeburn  10536: <script type="text/javascript">
1.1032    www      10537: // <![CDATA[
                   10538:         var $funcname = function()
                   10539:         {
                   10540:                 modalWindow.windowId = "myModal";
                   10541:                 modalWindow.width = $width;
                   10542:                 modalWindow.height = $height;
                   10543:                 modalWindow.content = '$content';
                   10544:                 modalWindow.open();
1.1365    raeburn  10545:                 $mathjax
1.1032    www      10546:         };  
                   10547: // ]]>
                   10548: </script>
                   10549: ENDADHOC
                   10550: }
                   10551: 
1.1041    www      10552: sub modal_adhoc_inner {
1.1365    raeburn  10553:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10554:     my $innerwidth=$width-20;
                   10555:     $content=&js_ready(
1.1140    raeburn  10556:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10557:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10558:                  $content.
1.1041    www      10559:                  &end_scrollbox().
1.1140    raeburn  10560:                  &end_page()
1.1041    www      10561:              );
1.1365    raeburn  10562:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10563: }
                   10564: 
                   10565: sub modal_adhoc_window {
1.1365    raeburn  10566:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10567:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10568:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10569: }
                   10570: 
                   10571: sub modal_adhoc_launch {
                   10572:     my ($funcname,$width,$height,$content)=@_;
                   10573:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10574: <script type="text/javascript">
                   10575: // <![CDATA[
                   10576: $funcname();
                   10577: // ]]>
                   10578: </script>
                   10579: ENDLAUNCH
                   10580: }
                   10581: 
                   10582: sub modal_adhoc_close {
                   10583:     return (<<ENDCLOSE);
                   10584: <script type="text/javascript">
                   10585: // <![CDATA[
                   10586: modalWindow.close();
                   10587: // ]]>
                   10588: </script>
                   10589: ENDCLOSE
                   10590: }
                   10591: 
1.1038    www      10592: sub togglebox_script {
                   10593:    return(<<ENDTOGGLE);
                   10594: <script type="text/javascript"> 
                   10595: // <![CDATA[
                   10596: function LCtoggleDisplay(id,hidetext,showtext) {
                   10597:    link = document.getElementById(id + "link").childNodes[0];
                   10598:    with (document.getElementById(id).style) {
                   10599:       if (display == "none" ) {
                   10600:           display = "inline";
                   10601:           link.nodeValue = hidetext;
                   10602:         } else {
                   10603:           display = "none";
                   10604:           link.nodeValue = showtext;
                   10605:        }
                   10606:    }
                   10607: }
                   10608: // ]]>
                   10609: </script>
                   10610: ENDTOGGLE
                   10611: }
                   10612: 
1.1039    www      10613: sub start_togglebox {
                   10614:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10615:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10616:     unless ($showtext) { $showtext=&mt('show'); }
                   10617:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10618:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10619:     return &start_data_table().
                   10620:            &start_data_table_header_row().
                   10621:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10622:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10623:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10624:            &end_data_table_header_row().
                   10625:            '<tr id="'.$id.'" style="display:none""><td>';
                   10626: }
                   10627: 
                   10628: sub end_togglebox {
                   10629:     return '</td></tr>'.&end_data_table();
                   10630: }
                   10631: 
1.1041    www      10632: sub LCprogressbar_script {
1.1302    raeburn  10633:    my ($id,$number_to_do)=@_;
                   10634:    if ($number_to_do) {
                   10635:        return(<<ENDPROGRESS);
1.1041    www      10636: <script type="text/javascript">
                   10637: // <![CDATA[
1.1045    www      10638: \$('#progressbar$id').progressbar({
1.1041    www      10639:   value: 0,
                   10640:   change: function(event, ui) {
                   10641:     var newVal = \$(this).progressbar('option', 'value');
                   10642:     \$('.pblabel', this).text(LCprogressTxt);
                   10643:   }
                   10644: });
                   10645: // ]]>
                   10646: </script>
                   10647: ENDPROGRESS
1.1302    raeburn  10648:    } else {
                   10649:        return(<<ENDPROGRESS);
                   10650: <script type="text/javascript">
                   10651: // <![CDATA[
                   10652: \$('#progressbar$id').progressbar({
                   10653:   value: false,
                   10654:   create: function(event, ui) {
                   10655:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10656:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10657:   }
                   10658: });
                   10659: // ]]>
                   10660: </script>
                   10661: ENDPROGRESS
                   10662:    }
1.1041    www      10663: }
                   10664: 
                   10665: sub LCprogressbarUpdate_script {
                   10666:    return(<<ENDPROGRESSUPDATE);
                   10667: <style type="text/css">
                   10668: .ui-progressbar { position:relative; }
1.1302    raeburn  10669: .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      10670: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10671: </style>
                   10672: <script type="text/javascript">
                   10673: // <![CDATA[
1.1045    www      10674: var LCprogressTxt='---';
                   10675: 
1.1302    raeburn  10676: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10677:    LCprogressTxt=progresstext;
1.1302    raeburn  10678:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10679:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10680:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10681:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10682:    } else {
                   10683:        \$('#progressbar'+id).progressbar('value',percent);
                   10684:    }
1.1041    www      10685: }
                   10686: // ]]>
                   10687: </script>
                   10688: ENDPROGRESSUPDATE
                   10689: }
                   10690: 
1.1042    www      10691: my $LClastpercent;
1.1045    www      10692: my $LCidcnt;
                   10693: my $LCcurrentid;
1.1042    www      10694: 
1.1041    www      10695: sub LCprogressbar {
1.1302    raeburn  10696:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10697:     $LClastpercent=0;
1.1045    www      10698:     $LCidcnt++;
                   10699:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10700:     my ($starting,$content);
                   10701:     if ($number_to_do) {
                   10702:         $starting=&mt('Starting');
                   10703:         $content=(<<ENDPROGBAR);
                   10704: $preamble
1.1045    www      10705:   <div id="progressbar$LCcurrentid">
1.1041    www      10706:     <span class="pblabel">$starting</span>
                   10707:   </div>
                   10708: ENDPROGBAR
1.1302    raeburn  10709:     } else {
                   10710:         $starting=&mt('Loading...');
                   10711:         $LClastpercent='false';
                   10712:         $content=(<<ENDPROGBAR);
                   10713: $preamble
                   10714:   <div id="progressbar$LCcurrentid">
                   10715:       <div class="progress-label">$starting</div>
                   10716:   </div>
                   10717: ENDPROGBAR
                   10718:     }
                   10719:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10720: }
                   10721: 
                   10722: sub LCprogressbarUpdate {
1.1302    raeburn  10723:     my ($r,$val,$text,$number_to_do)=@_;
                   10724:     if ($number_to_do) {
                   10725:         unless ($val) { 
                   10726:             if ($LClastpercent) {
                   10727:                 $val=$LClastpercent;
                   10728:             } else {
                   10729:                 $val=0;
                   10730:             }
                   10731:         }
                   10732:         if ($val<0) { $val=0; }
                   10733:         if ($val>100) { $val=0; }
                   10734:         $LClastpercent=$val;
                   10735:         unless ($text) { $text=$val.'%'; }
                   10736:     } else {
                   10737:         $val = 'false';
1.1042    www      10738:     }
1.1041    www      10739:     $text=&js_ready($text);
1.1044    www      10740:     &r_print($r,<<ENDUPDATE);
1.1041    www      10741: <script type="text/javascript">
                   10742: // <![CDATA[
1.1302    raeburn  10743: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10744: // ]]>
                   10745: </script>
                   10746: ENDUPDATE
1.1035    www      10747: }
                   10748: 
1.1042    www      10749: sub LCprogressbarClose {
                   10750:     my ($r)=@_;
                   10751:     $LClastpercent=0;
1.1044    www      10752:     &r_print($r,<<ENDCLOSE);
1.1042    www      10753: <script type="text/javascript">
                   10754: // <![CDATA[
1.1045    www      10755: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10756: // ]]>
                   10757: </script>
                   10758: ENDCLOSE
1.1044    www      10759: }
                   10760: 
                   10761: sub r_print {
                   10762:     my ($r,$to_print)=@_;
                   10763:     if ($r) {
                   10764:       $r->print($to_print);
                   10765:       $r->rflush();
                   10766:     } else {
                   10767:       print($to_print);
                   10768:     }
1.1042    www      10769: }
                   10770: 
1.320     albertel 10771: sub html_encode {
                   10772:     my ($result) = @_;
                   10773: 
1.322     albertel 10774:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10775:     
                   10776:     return $result;
                   10777: }
1.1044    www      10778: 
1.317     albertel 10779: sub js_ready {
                   10780:     my ($result) = @_;
                   10781: 
1.323     albertel 10782:     $result =~ s/[\n\r]/ /xmsg;
                   10783:     $result =~ s/\\/\\\\/xmsg;
                   10784:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10785:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10786:     
                   10787:     return $result;
                   10788: }
                   10789: 
1.315     albertel 10790: sub validate_page {
                   10791:     if (  exists($env{'internal.start_page'})
1.316     albertel 10792: 	  &&     $env{'internal.start_page'} > 1) {
                   10793: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10794: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10795: 				 $ENV{'request.filename'});
1.315     albertel 10796:     }
                   10797:     if (  exists($env{'internal.end_page'})
1.316     albertel 10798: 	  &&     $env{'internal.end_page'} > 1) {
                   10799: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10800: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10801: 				 $env{'request.filename'});
1.315     albertel 10802:     }
                   10803:     if (     exists($env{'internal.start_page'})
                   10804: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10805: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10806: 				 $env{'request.filename'});
1.315     albertel 10807:     }
                   10808:     if (   ! exists($env{'internal.start_page'})
                   10809: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10810: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10811: 				 $env{'request.filename'});
1.315     albertel 10812:     }
1.306     albertel 10813: }
1.315     albertel 10814: 
1.996     www      10815: 
                   10816: sub start_scrollbox {
1.1140    raeburn  10817:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10818:     unless ($outerwidth) { $outerwidth='520px'; }
                   10819:     unless ($width) { $width='500px'; }
                   10820:     unless ($height) { $height='200px'; }
1.1075    raeburn  10821:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10822:     if ($id ne '') {
1.1140    raeburn  10823:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10824:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10825:     }
1.1075    raeburn  10826:     if ($bgcolor ne '') {
                   10827:         $tdcol = "background-color: $bgcolor;";
                   10828:     }
1.1137    raeburn  10829:     my $nicescroll_js;
                   10830:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10831:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10832:     }
                   10833:     return <<"END";
                   10834: $nicescroll_js
                   10835: 
                   10836: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10837: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10838: END
                   10839: }
                   10840: 
                   10841: sub end_scrollbox {
                   10842:     return '</div></td></tr></table>';
                   10843: }
                   10844: 
                   10845: sub nicescroll_javascript {
                   10846:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10847:     my %options;
                   10848:     if (ref($cursor) eq 'HASH') {
                   10849:         %options = %{$cursor};
                   10850:     }
                   10851:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10852:         $options{'railalign'} = 'left';
                   10853:     }
                   10854:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10855:         my $function  = &get_users_function();
                   10856:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10857:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10858:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10859:         }
1.1140    raeburn  10860:     }
                   10861:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10862:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10863:             $options{'cursoropacity'}='1.0';
                   10864:         }
1.1140    raeburn  10865:     } else {
                   10866:         $options{'cursoropacity'}='1.0';
                   10867:     }
                   10868:     if ($options{'cursorfixedheight'} eq 'none') {
                   10869:         delete($options{'cursorfixedheight'});
                   10870:     } else {
                   10871:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10872:     }
                   10873:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10874:         delete($options{'railoffset'});
                   10875:     }
                   10876:     my @niceoptions;
                   10877:     while (my($key,$value) = each(%options)) {
                   10878:         if ($value =~ /^\{.+\}$/) {
                   10879:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10880:         } else {
1.1140    raeburn  10881:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10882:         }
1.1140    raeburn  10883:     }
                   10884:     my $nicescroll_js = '
1.1137    raeburn  10885: $(document).ready(
1.1140    raeburn  10886:       function() {
                   10887:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10888:       }
1.1137    raeburn  10889: );
                   10890: ';
1.1140    raeburn  10891:     if ($framecheck) {
                   10892:         $nicescroll_js .= '
                   10893: function expand_div(caller) {
                   10894:     if (top === self) {
                   10895:         document.getElementById("'.$id.'").style.width = "auto";
                   10896:         document.getElementById("'.$id.'").style.height = "auto";
                   10897:     } else {
                   10898:         try {
                   10899:             if (parent.frames) {
                   10900:                 if (parent.frames.length > 1) {
                   10901:                     var framesrc = parent.frames[1].location.href;
                   10902:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10903:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10904:                         document.getElementById("'.$id.'").style.width = "auto";
                   10905:                         document.getElementById("'.$id.'").style.height = "auto";
                   10906:                     }
                   10907:                 }
                   10908:             }
                   10909:         } catch (e) {
                   10910:             return;
                   10911:         }
1.1137    raeburn  10912:     }
1.1140    raeburn  10913:     return;
1.996     www      10914: }
1.1140    raeburn  10915: ';
                   10916:     }
                   10917:     if ($needjsready) {
                   10918:         $nicescroll_js = '
                   10919: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10920:     } else {
                   10921:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10922:     }
                   10923:     return $nicescroll_js;
1.996     www      10924: }
                   10925: 
1.318     albertel 10926: sub simple_error_page {
1.1150    bisitz   10927:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10928:     my %displayargs;
1.1151    raeburn  10929:     if (ref($args) eq 'HASH') {
                   10930:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10931:         if ($args->{'only_body'}) {
                   10932:             $displayargs{'only_body'} = 1;
                   10933:         }
                   10934:         if ($args->{'no_nav_bar'}) {
                   10935:             $displayargs{'no_nav_bar'} = 1;
                   10936:         }
1.1151    raeburn  10937:     } else {
                   10938:         $msg = &mt($msg);
                   10939:     }
1.1150    bisitz   10940: 
1.318     albertel 10941:     my $page =
1.1459    raeburn  10942: 	&Apache::loncommon::start_page($title,'',\%displayargs)."\n".
1.1460    raeburn  10943:         '<div class="LC_landmark" style="clear:both" role="main">'.
1.1150    bisitz   10944: 	'<p class="LC_error">'.$msg.'</p>'.
1.1459    raeburn  10945:         '</div>'.
1.318     albertel 10946: 	&Apache::loncommon::end_page();
                   10947:     if (ref($r)) {
                   10948: 	$r->print($page);
1.327     albertel 10949: 	return;
1.318     albertel 10950:     }
                   10951:     return $page;
                   10952: }
1.347     albertel 10953: 
                   10954: {
1.610     albertel 10955:     my @row_count;
1.961     onken    10956: 
                   10957:     sub start_data_table_count {
                   10958:         unshift(@row_count, 0);
                   10959:         return;
                   10960:     }
                   10961: 
                   10962:     sub end_data_table_count {
                   10963:         shift(@row_count);
                   10964:         return;
                   10965:     }
                   10966: 
1.1466    raeburn  10967:     sub set_data_table_count {
                   10968:         my ($count) = @_;
                   10969:         unshift(@row_count,$count);
                   10970:     }
                   10971: 
1.347     albertel 10972:     sub start_data_table {
1.1018    raeburn  10973: 	my ($add_class,$id) = @_;
1.422     albertel 10974: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10975:         my $table_id;
                   10976:         if (defined($id)) {
                   10977:             $table_id = ' id="'.$id.'"';
                   10978:         }
1.961     onken    10979: 	&start_data_table_count();
1.1018    raeburn  10980: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10981:     }
                   10982: 
                   10983:     sub end_data_table {
1.961     onken    10984: 	&end_data_table_count();
1.389     albertel 10985: 	return '</table>'."\n";;
1.347     albertel 10986:     }
                   10987: 
                   10988:     sub start_data_table_row {
1.974     wenzelju 10989: 	my ($add_class, $id) = @_;
1.610     albertel 10990: 	$row_count[0]++;
                   10991: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10992: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10993:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10994:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10995:     }
1.471     banghart 10996:     
                   10997:     sub continue_data_table_row {
1.974     wenzelju 10998: 	my ($add_class, $id) = @_;
1.610     albertel 10999: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 11000: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   11001:         $id = (' id="'.$id.'"') unless ($id eq '');
                   11002:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 11003:     }
1.347     albertel 11004: 
                   11005:     sub end_data_table_row {
1.389     albertel 11006: 	return '</tr>'."\n";;
1.347     albertel 11007:     }
1.367     www      11008: 
1.421     albertel 11009:     sub start_data_table_empty_row {
1.707     bisitz   11010: #	$row_count[0]++;
1.421     albertel 11011: 	return  '<tr class="LC_empty_row" >'."\n";;
                   11012:     }
                   11013: 
                   11014:     sub end_data_table_empty_row {
                   11015: 	return '</tr>'."\n";;
                   11016:     }
                   11017: 
1.367     www      11018:     sub start_data_table_header_row {
1.1465    raeburn  11019: 	my ($add_class,$id) = @_;
                   11020: 	my $css_class = 'LC_header_row';
                   11021: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   11022: 	$id = (' id="'.$id.'"') unless ($id eq '');
                   11023: 	return '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.367     www      11024:     }
                   11025: 
                   11026:     sub end_data_table_header_row {
1.389     albertel 11027: 	return '</tr>'."\n";;
1.367     www      11028:     }
1.890     droeschl 11029: 
                   11030:     sub data_table_caption {
1.1468    raeburn  11031:         my ($caption,$css_class) = @_;
                   11032:         return "<caption class=\"LC_caption $css_class\">$caption</caption>";
1.890     droeschl 11033:     }
1.347     albertel 11034: }
                   11035: 
1.548     albertel 11036: =pod
                   11037: 
                   11038: =item * &inhibit_menu_check($arg)
                   11039: 
                   11040: Checks for a inhibitmenu state and generates output to preserve it
                   11041: 
                   11042: Inputs:         $arg - can be any of
                   11043:                      - undef - in which case the return value is a string 
                   11044:                                to add  into arguments list of a uri
                   11045:                      - 'input' - in which case the return value is a HTML
                   11046:                                  <form> <input> field of type hidden to
                   11047:                                  preserve the value
                   11048:                      - a url - in which case the return value is the url with
                   11049:                                the neccesary cgi args added to preserve the
                   11050:                                inhibitmenu state
                   11051:                      - a ref to a url - no return value, but the string is
                   11052:                                         updated to include the neccessary cgi
                   11053:                                         args to preserve the inhibitmenu state
                   11054: 
                   11055: =cut
                   11056: 
                   11057: sub inhibit_menu_check {
                   11058:     my ($arg) = @_;
                   11059:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   11060:     if ($arg eq 'input') {
                   11061: 	if ($env{'form.inhibitmenu'}) {
                   11062: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   11063: 	} else {
                   11064: 	    return
                   11065: 	}
                   11066:     }
                   11067:     if ($env{'form.inhibitmenu'}) {
                   11068: 	if (ref($arg)) {
                   11069: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   11070: 	} elsif ($arg eq '') {
                   11071: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   11072: 	} else {
                   11073: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   11074: 	}
                   11075:     }
                   11076:     if (!ref($arg)) {
                   11077: 	return $arg;
                   11078:     }
                   11079: }
                   11080: 
1.251     albertel 11081: ###############################################
1.182     matthew  11082: 
                   11083: =pod
                   11084: 
1.549     albertel 11085: =back
                   11086: 
                   11087: =head1 User Information Routines
                   11088: 
                   11089: =over 4
                   11090: 
1.405     albertel 11091: =item * &get_users_function()
1.182     matthew  11092: 
                   11093: Used by &bodytag to determine the current users primary role.
                   11094: Returns either 'student','coordinator','admin', or 'author'.
                   11095: 
                   11096: =cut
                   11097: 
                   11098: ###############################################
                   11099: sub get_users_function {
1.815     tempelho 11100:     my $function = 'norole';
1.818     tempelho 11101:     if ($env{'request.role'}=~/^(st)/) {
                   11102:         $function='student';
                   11103:     }
1.907     raeburn  11104:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  11105:         $function='coordinator';
                   11106:     }
1.258     albertel 11107:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  11108:         $function='admin';
                   11109:     }
1.826     bisitz   11110:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  11111:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  11112:         $function='author';
                   11113:     }
                   11114:     return $function;
1.54      www      11115: }
1.99      www      11116: 
                   11117: ###############################################
                   11118: 
1.233     raeburn  11119: =pod
                   11120: 
1.821     raeburn  11121: =item * &show_course()
                   11122: 
                   11123: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   11124: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   11125: 
                   11126: Inputs:
                   11127: None
                   11128: 
                   11129: Outputs:
                   11130: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   11131: 
                   11132: =cut
                   11133: 
                   11134: ###############################################
                   11135: sub show_course {
1.1408    raeburn  11136:     my ($udom,$uname) = @_;
                   11137:     if (($udom ne '') && ($uname ne '')) {
                   11138:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  11139:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  11140:                 return 0;
                   11141:             } else {
                   11142:                 return 1;
                   11143:             }
                   11144:         }
                   11145:     }
1.821     raeburn  11146:     my $course = !$env{'user.adv'};
                   11147:     if (!$env{'user.adv'}) {
                   11148:         foreach my $env (keys(%env)) {
                   11149:             next if ($env !~ m/^user\.priv\./);
                   11150:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   11151:                 $course = 0;
                   11152:                 last;
                   11153:             }
                   11154:         }
                   11155:     }
                   11156:     return $course;
                   11157: }
                   11158: 
                   11159: ###############################################
                   11160: 
                   11161: =pod
                   11162: 
1.542     raeburn  11163: =item * &check_user_status()
1.274     raeburn  11164: 
                   11165: Determines current status of supplied role for a
                   11166: specific user. Roles can be active, previous or future.
                   11167: 
                   11168: Inputs: 
                   11169: user's domain, user's username, course's domain,
1.375     raeburn  11170: course's number, optional section ID.
1.274     raeburn  11171: 
                   11172: Outputs:
                   11173: role status: active, previous or future. 
                   11174: 
                   11175: =cut
                   11176: 
                   11177: sub check_user_status {
1.412     raeburn  11178:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  11179:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  11180:     my @uroles = keys(%userinfo);
1.274     raeburn  11181:     my $srchstr;
                   11182:     my $active_chk = 'none';
1.412     raeburn  11183:     my $now = time;
1.274     raeburn  11184:     if (@uroles > 0) {
1.908     raeburn  11185:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11186:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11187:         } else {
1.412     raeburn  11188:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11189:         }
                   11190:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11191:             my $role_end = 0;
                   11192:             my $role_start = 0;
                   11193:             $active_chk = 'active';
1.412     raeburn  11194:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11195:                 $role_end = $1;
                   11196:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11197:                     $role_start = $1;
1.274     raeburn  11198:                 }
                   11199:             }
                   11200:             if ($role_start > 0) {
1.412     raeburn  11201:                 if ($now < $role_start) {
1.274     raeburn  11202:                     $active_chk = 'future';
                   11203:                 }
                   11204:             }
                   11205:             if ($role_end > 0) {
1.412     raeburn  11206:                 if ($now > $role_end) {
1.274     raeburn  11207:                     $active_chk = 'previous';
                   11208:                 }
                   11209:             }
                   11210:         }
                   11211:     }
                   11212:     return $active_chk;
                   11213: }
                   11214: 
                   11215: ###############################################
                   11216: 
                   11217: =pod
                   11218: 
1.405     albertel 11219: =item * &get_sections()
1.233     raeburn  11220: 
                   11221: Determines all the sections for a course including
                   11222: sections with students and sections containing other roles.
1.419     raeburn  11223: Incoming parameters: 
                   11224: 
                   11225: 1. domain
                   11226: 2. course number 
                   11227: 3. reference to array containing roles for which sections should 
                   11228: be gathered (optional).
                   11229: 4. reference to array containing status types for which sections 
                   11230: should be gathered (optional).
                   11231: 
                   11232: If the third argument is undefined, sections are gathered for any role. 
                   11233: If the fourth argument is undefined, sections are gathered for any status.
                   11234: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11235:  
1.374     raeburn  11236: Returns section hash (keys are section IDs, values are
                   11237: number of users in each section), subject to the
1.419     raeburn  11238: optional roles filter, optional status filter 
1.233     raeburn  11239: 
                   11240: =cut
                   11241: 
                   11242: ###############################################
                   11243: sub get_sections {
1.419     raeburn  11244:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11245:     if (!defined($cdom) || !defined($cnum)) {
                   11246:         my $cid =  $env{'request.course.id'};
                   11247: 
                   11248: 	return if (!defined($cid));
                   11249: 
                   11250:         $cdom = $env{'course.'.$cid.'.domain'};
                   11251:         $cnum = $env{'course.'.$cid.'.num'};
                   11252:     }
                   11253: 
                   11254:     my %sectioncount;
1.419     raeburn  11255:     my $now = time;
1.240     albertel 11256: 
1.1118    raeburn  11257:     my $check_students = 1;
                   11258:     my $only_students = 0;
                   11259:     if (ref($possible_roles) eq 'ARRAY') {
                   11260:         if (grep(/^st$/,@{$possible_roles})) {
                   11261:             if (@{$possible_roles} == 1) {
                   11262:                 $only_students = 1;
                   11263:             }
                   11264:         } else {
                   11265:             $check_students = 0;
                   11266:         }
                   11267:     }
                   11268: 
                   11269:     if ($check_students) { 
1.276     albertel 11270: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11271: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11272: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11273:         my $start_index = &Apache::loncoursedata::CL_START();
                   11274:         my $end_index = &Apache::loncoursedata::CL_END();
                   11275:         my $status;
1.366     albertel 11276: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11277: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11278: 				                     $data->[$status_index],
                   11279:                                                      $data->[$start_index],
                   11280:                                                      $data->[$end_index]);
                   11281:             if ($stu_status eq 'Active') {
                   11282:                 $status = 'active';
                   11283:             } elsif ($end < $now) {
                   11284:                 $status = 'previous';
                   11285:             } elsif ($start > $now) {
                   11286:                 $status = 'future';
                   11287:             } 
                   11288: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11289:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11290:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11291: 		    $sectioncount{$section}++;
                   11292:                 }
1.240     albertel 11293: 	    }
                   11294: 	}
                   11295:     }
1.1118    raeburn  11296:     if ($only_students) {
                   11297:         return %sectioncount;
                   11298:     }
1.240     albertel 11299:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11300:     foreach my $user (sort(keys(%courseroles))) {
                   11301: 	if ($user !~ /^(\w{2})/) { next; }
                   11302: 	my ($role) = ($user =~ /^(\w{2})/);
                   11303: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11304: 	my ($section,$status);
1.240     albertel 11305: 	if ($role eq 'cr' &&
                   11306: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11307: 	    $section=$1;
                   11308: 	}
                   11309: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11310: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11311:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11312:         if ($end == -1 && $start == -1) {
                   11313:             next; #deleted role
                   11314:         }
                   11315:         if (!defined($possible_status)) { 
                   11316:             $sectioncount{$section}++;
                   11317:         } else {
                   11318:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11319:                 $status = 'active';
                   11320:             } elsif ($end < $now) {
                   11321:                 $status = 'future';
                   11322:             } elsif ($start > $now) {
                   11323:                 $status = 'previous';
                   11324:             }
                   11325:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11326:                 $sectioncount{$section}++;
                   11327:             }
                   11328:         }
1.233     raeburn  11329:     }
1.366     albertel 11330:     return %sectioncount;
1.233     raeburn  11331: }
                   11332: 
1.274     raeburn  11333: ###############################################
1.294     raeburn  11334: 
                   11335: =pod
1.405     albertel 11336: 
                   11337: =item * &get_course_users()
                   11338: 
1.275     raeburn  11339: Retrieves usernames:domains for users in the specified course
                   11340: with specific role(s), and access status. 
                   11341: 
                   11342: Incoming parameters:
1.277     albertel 11343: 1. course domain
                   11344: 2. course number
                   11345: 3. access status: users must have - either active, 
1.275     raeburn  11346: previous, future, or all.
1.277     albertel 11347: 4. reference to array of permissible roles
1.288     raeburn  11348: 5. reference to array of section restrictions (optional)
                   11349: 6. reference to results object (hash of hashes).
                   11350: 7. reference to optional userdata hash
1.609     raeburn  11351: 8. reference to optional statushash
1.630     raeburn  11352: 9. flag if privileged users (except those set to unhide in
                   11353:    course settings) should be excluded    
1.609     raeburn  11354: Keys of top level results hash are roles.
1.275     raeburn  11355: Keys of inner hashes are username:domain, with 
                   11356: values set to access type.
1.288     raeburn  11357: Optional userdata hash returns an array with arguments in the 
                   11358: same order as loncoursedata::get_classlist() for student data.
                   11359: 
1.609     raeburn  11360: Optional statushash returns
                   11361: 
1.288     raeburn  11362: Entries for end, start, section and status are blank because
                   11363: of the possibility of multiple values for non-student roles.
                   11364: 
1.275     raeburn  11365: =cut
1.405     albertel 11366: 
1.275     raeburn  11367: ###############################################
1.405     albertel 11368: 
1.275     raeburn  11369: sub get_course_users {
1.630     raeburn  11370:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11371:     my %idx = ();
1.419     raeburn  11372:     my %seclists;
1.288     raeburn  11373: 
                   11374:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11375:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11376:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11377:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11378:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11379:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11380:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11381:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11382: 
1.290     albertel 11383:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11384:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11385:         my $now = time;
1.277     albertel 11386:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11387:             my $match = 0;
1.412     raeburn  11388:             my $secmatch = 0;
1.419     raeburn  11389:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11390:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11391:             if ($section eq '') {
                   11392:                 $section = 'none';
                   11393:             }
1.291     albertel 11394:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11395:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11396:                     $secmatch = 1;
                   11397:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11398:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11399:                         $secmatch = 1;
                   11400:                     }
                   11401:                 } else {  
1.419     raeburn  11402: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11403: 		        $secmatch = 1;
                   11404:                     }
1.290     albertel 11405: 		}
1.412     raeburn  11406:                 if (!$secmatch) {
                   11407:                     next;
                   11408:                 }
1.419     raeburn  11409:             }
1.275     raeburn  11410:             if (defined($$types{'active'})) {
1.288     raeburn  11411:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11412:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11413:                     $match = 1;
1.275     raeburn  11414:                 }
                   11415:             }
                   11416:             if (defined($$types{'previous'})) {
1.609     raeburn  11417:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11418:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11419:                     $match = 1;
1.275     raeburn  11420:                 }
                   11421:             }
                   11422:             if (defined($$types{'future'})) {
1.609     raeburn  11423:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11424:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11425:                     $match = 1;
1.275     raeburn  11426:                 }
                   11427:             }
1.609     raeburn  11428:             if ($match) {
                   11429:                 push(@{$seclists{$student}},$section);
                   11430:                 if (ref($userdata) eq 'HASH') {
                   11431:                     $$userdata{$student} = $$classlist{$student};
                   11432:                 }
                   11433:                 if (ref($statushash) eq 'HASH') {
                   11434:                     $statushash->{$student}{'st'}{$section} = $status;
                   11435:                 }
1.288     raeburn  11436:             }
1.275     raeburn  11437:         }
                   11438:     }
1.412     raeburn  11439:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11440:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11441:         my $now = time;
1.609     raeburn  11442:         my %displaystatus = ( previous => 'Expired',
                   11443:                               active   => 'Active',
                   11444:                               future   => 'Future',
                   11445:                             );
1.1121    raeburn  11446:         my (%nothide,@possdoms);
1.630     raeburn  11447:         if ($hidepriv) {
                   11448:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11449:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11450:                 if ($user !~ /:/) {
                   11451:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11452:                 } else {
                   11453:                     $nothide{$user} = 1;
                   11454:                 }
                   11455:             }
1.1121    raeburn  11456:             my @possdoms = ($cdom);
                   11457:             if ($coursehash{'checkforpriv'}) {
                   11458:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11459:             }
1.630     raeburn  11460:         }
1.439     raeburn  11461:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11462:             my $match = 0;
1.412     raeburn  11463:             my $secmatch = 0;
1.439     raeburn  11464:             my $status;
1.412     raeburn  11465:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11466:             $user =~ s/:$//;
1.439     raeburn  11467:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11468:             if ($end == -1 || $start == -1) {
                   11469:                 next;
                   11470:             }
                   11471:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11472:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11473:                 my ($uname,$udom) = split(/:/,$user);
                   11474:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11475:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11476:                         $secmatch = 1;
                   11477:                     } elsif ($usec eq '') {
1.420     albertel 11478:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11479:                             $secmatch = 1;
                   11480:                         }
                   11481:                     } else {
                   11482:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11483:                             $secmatch = 1;
                   11484:                         }
                   11485:                     }
                   11486:                     if (!$secmatch) {
                   11487:                         next;
                   11488:                     }
1.288     raeburn  11489:                 }
1.419     raeburn  11490:                 if ($usec eq '') {
                   11491:                     $usec = 'none';
                   11492:                 }
1.275     raeburn  11493:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11494:                     if ($hidepriv) {
1.1121    raeburn  11495:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11496:                             (!$nothide{$uname.':'.$udom})) {
                   11497:                             next;
                   11498:                         }
                   11499:                     }
1.503     raeburn  11500:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11501:                         $status = 'previous';
                   11502:                     } elsif ($start > $now) {
                   11503:                         $status = 'future';
                   11504:                     } else {
                   11505:                         $status = 'active';
                   11506:                     }
1.277     albertel 11507:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11508:                         if ($status eq $type) {
1.420     albertel 11509:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11510:                                 push(@{$$users{$role}{$user}},$type);
                   11511:                             }
1.288     raeburn  11512:                             $match = 1;
                   11513:                         }
                   11514:                     }
1.419     raeburn  11515:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11516:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11517: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11518:                         }
1.420     albertel 11519:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11520:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11521:                         }
1.609     raeburn  11522:                         if (ref($statushash) eq 'HASH') {
                   11523:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11524:                         }
1.275     raeburn  11525:                     }
                   11526:                 }
                   11527:             }
                   11528:         }
1.290     albertel 11529:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11530:             if ((defined($cdom)) && (defined($cnum))) {
                   11531:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11532:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11533:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11534:                     next if ($owner eq '');
                   11535:                     my ($ownername,$ownerdom);
                   11536:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11537:                         $ownername = $1;
                   11538:                         $ownerdom = $2;
                   11539:                     } else {
                   11540:                         $ownername = $owner;
                   11541:                         $ownerdom = $cdom;
                   11542:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11543:                     }
                   11544:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11545:                     if (defined($userdata) && 
1.609     raeburn  11546: 			!exists($$userdata{$owner})) {
                   11547: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11548:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11549:                             push(@{$seclists{$owner}},'none');
                   11550:                         }
                   11551:                         if (ref($statushash) eq 'HASH') {
                   11552:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11553:                         }
1.290     albertel 11554: 		    }
1.279     raeburn  11555:                 }
                   11556:             }
                   11557:         }
1.419     raeburn  11558:         foreach my $user (keys(%seclists)) {
                   11559:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11560:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11561:         }
1.275     raeburn  11562:     }
                   11563:     return;
                   11564: }
                   11565: 
1.288     raeburn  11566: sub get_user_info {
                   11567:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11568:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11569: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11570:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11571:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11572:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11573:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11574:     return;
                   11575: }
1.275     raeburn  11576: 
1.472     raeburn  11577: ###############################################
                   11578: 
                   11579: =pod
                   11580: 
                   11581: =item * &get_user_quota()
                   11582: 
1.1134    raeburn  11583: Retrieves quota assigned for storage of user files.
                   11584: Default is to report quota for portfolio files.
1.472     raeburn  11585: 
                   11586: Incoming parameters:
                   11587: 1. user's username
                   11588: 2. user's domain
1.1134    raeburn  11589: 3. quota name - portfolio, author, or course
1.1136    raeburn  11590:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11591: 4. crstype - official, unofficial, textbook, placement or community, 
                   11592:    if quota name is course
1.472     raeburn  11593: 
                   11594: Returns:
1.1163    raeburn  11595: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11596: 2. (Optional) Type of setting: custom or default
                   11597:    (individually assigned or default for user's 
                   11598:    institutional status).
                   11599: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11600:    or student - types as defined in localenroll::inst_usertypes 
                   11601:    for user's domain, which determines default quota for user.
                   11602: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11603: 
                   11604: If a value has been stored in the user's environment, 
1.536     raeburn  11605: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11606: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11607: 
                   11608: =cut
                   11609: 
                   11610: ###############################################
                   11611: 
                   11612: 
                   11613: sub get_user_quota {
1.1136    raeburn  11614:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11615:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11616:     if (!defined($udom)) {
                   11617:         $udom = $env{'user.domain'};
                   11618:     }
                   11619:     if (!defined($uname)) {
                   11620:         $uname = $env{'user.name'};
                   11621:     }
                   11622:     if (($udom eq '' || $uname eq '') ||
                   11623:         ($udom eq 'public') && ($uname eq 'public')) {
                   11624:         $quota = 0;
1.536     raeburn  11625:         $quotatype = 'default';
                   11626:         $defquota = 0; 
1.472     raeburn  11627:     } else {
1.536     raeburn  11628:         my $inststatus;
1.1134    raeburn  11629:         if ($quotaname eq 'course') {
                   11630:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11631:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11632:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11633:             } else {
                   11634:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11635:                 $quota = $cenv{'internal.uploadquota'};
                   11636:             }
1.536     raeburn  11637:         } else {
1.1134    raeburn  11638:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11639:                 if ($quotaname eq 'author') {
                   11640:                     $quota = $env{'environment.authorquota'};
                   11641:                 } else {
                   11642:                     $quota = $env{'environment.portfolioquota'};
                   11643:                 }
                   11644:                 $inststatus = $env{'environment.inststatus'};
                   11645:             } else {
                   11646:                 my %userenv = 
                   11647:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11648:                                          'authorquota','inststatus'],$udom,$uname);
                   11649:                 my ($tmp) = keys(%userenv);
                   11650:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11651:                     if ($quotaname eq 'author') {
                   11652:                         $quota = $userenv{'authorquota'};
                   11653:                     } else {
                   11654:                         $quota = $userenv{'portfolioquota'};
                   11655:                     }
                   11656:                     $inststatus = $userenv{'inststatus'};
                   11657:                 } else {
                   11658:                     undef(%userenv);
                   11659:                 }
                   11660:             }
                   11661:         }
                   11662:         if ($quota eq '' || wantarray) {
                   11663:             if ($quotaname eq 'course') {
                   11664:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11665:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11666:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11667:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11668:                     $defquota = $domdefs{$crstype.'quota'};
                   11669:                 }
                   11670:                 if ($defquota eq '') {
                   11671:                     $defquota = 500;
                   11672:                 }
1.1134    raeburn  11673:             } else {
                   11674:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11675:             }
                   11676:             if ($quota eq '') {
                   11677:                 $quota = $defquota;
                   11678:                 $quotatype = 'default';
                   11679:             } else {
                   11680:                 $quotatype = 'custom';
                   11681:             }
1.472     raeburn  11682:         }
                   11683:     }
1.536     raeburn  11684:     if (wantarray) {
                   11685:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11686:     } else {
                   11687:         return $quota;
                   11688:     }
1.472     raeburn  11689: }
                   11690: 
                   11691: ###############################################
                   11692: 
                   11693: =pod
                   11694: 
                   11695: =item * &default_quota()
                   11696: 
1.536     raeburn  11697: Retrieves default quota assigned for storage of user portfolio files,
                   11698: given an (optional) user's institutional status.
1.472     raeburn  11699: 
                   11700: Incoming parameters:
1.1142    raeburn  11701: 
1.472     raeburn  11702: 1. domain
1.536     raeburn  11703: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11704:    status types (e.g., faculty, staff, student etc.)
                   11705:    which apply to the user for whom the default is being retrieved.
                   11706:    If the institutional status string in undefined, the domain
1.1134    raeburn  11707:    default quota will be returned.
                   11708: 3.  quota name - portfolio, author, or course
                   11709:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11710: 
                   11711: Returns:
1.1142    raeburn  11712: 
1.1163    raeburn  11713: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11714: 2. (Optional) institutional type which determined the value of the
                   11715:    default quota.
1.472     raeburn  11716: 
                   11717: If a value has been stored in the domain's configuration db,
                   11718: it will return that, otherwise it returns 20 (for backwards 
                   11719: compatibility with domains which have not set up a configuration
1.1163    raeburn  11720: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11721: 
1.536     raeburn  11722: If the user's status includes multiple types (e.g., staff and student),
                   11723: the largest default quota which applies to the user determines the
                   11724: default quota returned.
                   11725: 
1.472     raeburn  11726: =cut
                   11727: 
                   11728: ###############################################
                   11729: 
                   11730: 
                   11731: sub default_quota {
1.1134    raeburn  11732:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11733:     my ($defquota,$settingstatus);
                   11734:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11735:                                             ['quotas'],$udom);
1.1134    raeburn  11736:     my $key = 'defaultquota';
                   11737:     if ($quotaname eq 'author') {
                   11738:         $key = 'authorquota';
                   11739:     }
1.622     raeburn  11740:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11741:         if ($inststatus ne '') {
1.765     raeburn  11742:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11743:             foreach my $item (@statuses) {
1.1134    raeburn  11744:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11745:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11746:                         if ($defquota eq '') {
1.1134    raeburn  11747:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11748:                             $settingstatus = $item;
1.1134    raeburn  11749:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11750:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11751:                             $settingstatus = $item;
                   11752:                         }
                   11753:                     }
1.1134    raeburn  11754:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11755:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11756:                         if ($defquota eq '') {
                   11757:                             $defquota = $quotahash{'quotas'}{$item};
                   11758:                             $settingstatus = $item;
                   11759:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11760:                             $defquota = $quotahash{'quotas'}{$item};
                   11761:                             $settingstatus = $item;
                   11762:                         }
1.536     raeburn  11763:                     }
                   11764:                 }
                   11765:             }
                   11766:         }
                   11767:         if ($defquota eq '') {
1.1134    raeburn  11768:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11769:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11770:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11771:                 $defquota = $quotahash{'quotas'}{'default'};
                   11772:             }
1.536     raeburn  11773:             $settingstatus = 'default';
1.1139    raeburn  11774:             if ($defquota eq '') {
                   11775:                 if ($quotaname eq 'author') {
                   11776:                     $defquota = 500;
                   11777:                 }
                   11778:             }
1.536     raeburn  11779:         }
                   11780:     } else {
                   11781:         $settingstatus = 'default';
1.1134    raeburn  11782:         if ($quotaname eq 'author') {
                   11783:             $defquota = 500;
                   11784:         } else {
                   11785:             $defquota = 20;
                   11786:         }
1.536     raeburn  11787:     }
                   11788:     if (wantarray) {
                   11789:         return ($defquota,$settingstatus);
1.472     raeburn  11790:     } else {
1.536     raeburn  11791:         return $defquota;
1.472     raeburn  11792:     }
                   11793: }
                   11794: 
1.1135    raeburn  11795: ###############################################
                   11796: 
                   11797: =pod
                   11798: 
1.1136    raeburn  11799: =item * &excess_filesize_warning()
1.1135    raeburn  11800: 
                   11801: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11802: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11803: space to be exceeded.
1.1136    raeburn  11804: 
                   11805: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11806: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11807: 
1.1165    raeburn  11808: Inputs: 7 
1.1136    raeburn  11809: 1. username or coursenum
1.1135    raeburn  11810: 2. domain
1.1136    raeburn  11811: 3. context ('author' or 'course')
1.1135    raeburn  11812: 4. filename of file for which action is being requested
                   11813: 5. filesize (kB) of file
                   11814: 6. action being taken: copy or upload.
1.1237    raeburn  11815: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11816: 
                   11817: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11818:          otherwise return null.
                   11819: 
                   11820: =back
1.1135    raeburn  11821: 
                   11822: =cut
                   11823: 
1.1136    raeburn  11824: sub excess_filesize_warning {
1.1165    raeburn  11825:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11826:     my $current_disk_usage = 0;
1.1165    raeburn  11827:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11828:     if ($context eq 'author') {
                   11829:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11830:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11831:     } else {
                   11832:         foreach my $subdir ('docs','supplemental') {
                   11833:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11834:         }
                   11835:     }
1.1135    raeburn  11836:     $disk_quota = int($disk_quota * 1000);
                   11837:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11838:         return '<p class="LC_warning">'.
1.1135    raeburn  11839:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11840:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11841:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11842:                             $disk_quota,$current_disk_usage).
                   11843:                '</p>';
                   11844:     }
                   11845:     return;
                   11846: }
                   11847: 
                   11848: ###############################################
                   11849: 
                   11850: 
1.1136    raeburn  11851: 
                   11852: 
1.384     raeburn  11853: sub get_secgrprole_info {
                   11854:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11855:     my %sections_count = &get_sections($cdom,$cnum);
                   11856:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11857:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11858:     my @groups = sort(keys(%curr_groups));
                   11859:     my $allroles = [];
                   11860:     my $rolehash;
                   11861:     my $accesshash = {
                   11862:                      active => 'Currently has access',
                   11863:                      future => 'Will have future access',
                   11864:                      previous => 'Previously had access',
                   11865:                   };
                   11866:     if ($needroles) {
                   11867:         $rolehash = {'all' => 'all'};
1.385     albertel 11868:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11869: 	if (&Apache::lonnet::error(%user_roles)) {
                   11870: 	    undef(%user_roles);
                   11871: 	}
                   11872:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11873:             my ($role)=split(/\:/,$item,2);
                   11874:             if ($role eq 'cr') { next; }
                   11875:             if ($role =~ /^cr/) {
                   11876:                 $$rolehash{$role} = (split('/',$role))[3];
                   11877:             } else {
                   11878:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11879:             }
                   11880:         }
                   11881:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11882:             push(@{$allroles},$key);
                   11883:         }
                   11884:         push (@{$allroles},'st');
                   11885:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11886:     }
                   11887:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11888: }
                   11889: 
1.555     raeburn  11890: sub user_picker {
1.1279    raeburn  11891:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11892:     my $currdom = $dom;
1.1253    raeburn  11893:     my @alldoms = &Apache::lonnet::all_domains();
                   11894:     if (@alldoms == 1) {
                   11895:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11896:                                                ['directorysrch'],$alldoms[0]);
                   11897:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11898:         my $showdom = $domdesc;
                   11899:         if ($showdom eq '') {
                   11900:             $showdom = $dom;
                   11901:         }
                   11902:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11903:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11904:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11905:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11906:             }
                   11907:         }
                   11908:     }
1.555     raeburn  11909:     my %curr_selected = (
                   11910:                         srchin => 'dom',
1.580     raeburn  11911:                         srchby => 'lastname',
1.555     raeburn  11912:                       );
                   11913:     my $srchterm;
1.625     raeburn  11914:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11915:         if ($srch->{'srchby'} ne '') {
                   11916:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11917:         }
                   11918:         if ($srch->{'srchin'} ne '') {
                   11919:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11920:         }
                   11921:         if ($srch->{'srchtype'} ne '') {
                   11922:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11923:         }
                   11924:         if ($srch->{'srchdomain'} ne '') {
                   11925:             $currdom = $srch->{'srchdomain'};
                   11926:         }
                   11927:         $srchterm = $srch->{'srchterm'};
                   11928:     }
1.1222    damieng  11929:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11930:                     'usr'       => 'Search criteria',
1.563     raeburn  11931:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11932:                     'uname'     => 'username',
                   11933:                     'lastname'  => 'last name',
1.555     raeburn  11934:                     'lastfirst' => 'last name, first name',
1.558     albertel 11935:                     'crs'       => 'in this course',
1.576     raeburn  11936:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11937:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11938:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11939:                     'exact'     => 'is',
                   11940:                     'contains'  => 'contains',
1.569     raeburn  11941:                     'begins'    => 'begins with',
1.1222    damieng  11942:                                        );
                   11943:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11944:                     'youm'      => "You must include some text to search for.",
                   11945:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11946:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11947:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11948:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11949:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11950:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11951:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11952:                                        );
1.1222    damieng  11953:     &html_escape(\%html_lt);
                   11954:     &js_escape(\%js_lt);
1.1255    raeburn  11955:     my $domform;
1.1277    raeburn  11956:     my $allow_blank = 1;
1.1255    raeburn  11957:     if ($fixeddom) {
1.1277    raeburn  11958:         $allow_blank = 0;
                   11959:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11960:     } else {
1.1287    raeburn  11961:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11962:         my ($trusted,$untrusted);
1.1287    raeburn  11963:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11964:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11965:         } elsif ($context eq 'author') {
1.1288    raeburn  11966:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11967:         } elsif ($context eq 'domain') {
1.1288    raeburn  11968:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11969:         }
1.1288    raeburn  11970:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11971:     }
1.563     raeburn  11972:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11973: 
                   11974:     my @srchins = ('crs','dom','alc','instd');
                   11975: 
                   11976:     foreach my $option (@srchins) {
                   11977:         # FIXME 'alc' option unavailable until 
                   11978:         #       loncreateuser::print_user_query_page()
                   11979:         #       has been completed.
                   11980:         next if ($option eq 'alc');
1.880     raeburn  11981:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11982:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11983:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11984:         if ($curr_selected{'srchin'} eq $option) {
                   11985:             $srchinsel .= ' 
1.1222    damieng  11986:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11987:         } else {
                   11988:             $srchinsel .= '
1.1222    damieng  11989:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11990:         }
1.555     raeburn  11991:     }
1.563     raeburn  11992:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11993: 
                   11994:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11995:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11996:         if ($curr_selected{'srchby'} eq $option) {
                   11997:             $srchbysel .= '
1.1222    damieng  11998:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11999:         } else {
                   12000:             $srchbysel .= '
1.1222    damieng  12001:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  12002:          }
                   12003:     }
                   12004:     $srchbysel .= "\n  </select>\n";
                   12005: 
                   12006:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  12007:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  12008:         if ($curr_selected{'srchtype'} eq $option) {
                   12009:             $srchtypesel .= '
1.1222    damieng  12010:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  12011:         } else {
                   12012:             $srchtypesel .= '
1.1222    damieng  12013:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  12014:         }
                   12015:     }
                   12016:     $srchtypesel .= "\n  </select>\n";
                   12017: 
1.558     albertel 12018:     my ($newuserscript,$new_user_create);
1.994     raeburn  12019:     my $context_dom = $env{'request.role.domain'};
                   12020:     if ($context eq 'requestcrs') {
                   12021:         if ($env{'form.coursedom'} ne '') { 
                   12022:             $context_dom = $env{'form.coursedom'};
                   12023:         }
                   12024:     }
1.556     raeburn  12025:     if ($forcenewuser) {
1.576     raeburn  12026:         if (ref($srch) eq 'HASH') {
1.994     raeburn  12027:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  12028:                 if ($cancreate) {
                   12029:                     $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>';
                   12030:                 } else {
1.799     bisitz   12031:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  12032:                     my %usertypetext = (
                   12033:                         official   => 'institutional',
                   12034:                         unofficial => 'non-institutional',
                   12035:                     );
1.799     bisitz   12036:                     $new_user_create = '<p class="LC_warning">'
                   12037:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   12038:                                       .' '
                   12039:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   12040:                                           ,'<a href="'.$helplink.'">','</a>')
                   12041:                                       .'</p><br />';
1.627     raeburn  12042:                 }
1.576     raeburn  12043:             }
                   12044:         }
                   12045: 
1.556     raeburn  12046:         $newuserscript = <<"ENDSCRIPT";
                   12047: 
1.570     raeburn  12048: function setSearch(createnew,callingForm) {
1.556     raeburn  12049:     if (createnew == 1) {
1.570     raeburn  12050:         for (var i=0; i<callingForm.srchby.length; i++) {
                   12051:             if (callingForm.srchby.options[i].value == 'uname') {
                   12052:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  12053:             }
                   12054:         }
1.570     raeburn  12055:         for (var i=0; i<callingForm.srchin.length; i++) {
                   12056:             if ( callingForm.srchin.options[i].value == 'dom') {
                   12057: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  12058:             }
                   12059:         }
1.570     raeburn  12060:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   12061:             if (callingForm.srchtype.options[i].value == 'exact') {
                   12062:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  12063:             }
                   12064:         }
1.570     raeburn  12065:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  12066:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  12067:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  12068:             }
                   12069:         }
                   12070:     }
                   12071: }
                   12072: ENDSCRIPT
1.558     albertel 12073: 
1.556     raeburn  12074:     }
                   12075: 
1.555     raeburn  12076:     my $output = <<"END_BLOCK";
1.556     raeburn  12077: <script type="text/javascript">
1.824     bisitz   12078: // <![CDATA[
1.570     raeburn  12079: function validateEntry(callingForm) {
1.558     albertel 12080: 
1.556     raeburn  12081:     var checkok = 1;
1.558     albertel 12082:     var srchin;
1.570     raeburn  12083:     for (var i=0; i<callingForm.srchin.length; i++) {
                   12084: 	if ( callingForm.srchin[i].checked ) {
                   12085: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 12086: 	}
                   12087:     }
                   12088: 
1.570     raeburn  12089:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   12090:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   12091:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   12092:     var srchterm =  callingForm.srchterm.value;
                   12093:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  12094:     var msg = "";
                   12095: 
                   12096:     if (srchterm == "") {
                   12097:         checkok = 0;
1.1222    damieng  12098:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  12099:     }
                   12100: 
1.569     raeburn  12101:     if (srchtype== 'begins') {
                   12102:         if (srchterm.length < 2) {
                   12103:             checkok = 0;
1.1222    damieng  12104:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  12105:         }
                   12106:     }
                   12107: 
1.556     raeburn  12108:     if (srchtype== 'contains') {
                   12109:         if (srchterm.length < 3) {
                   12110:             checkok = 0;
1.1222    damieng  12111:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  12112:         }
                   12113:     }
                   12114:     if (srchin == 'instd') {
                   12115:         if (srchdomain == '') {
                   12116:             checkok = 0;
1.1222    damieng  12117:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  12118:         }
                   12119:     }
                   12120:     if (srchin == 'dom') {
                   12121:         if (srchdomain == '') {
                   12122:             checkok = 0;
1.1222    damieng  12123:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  12124:         }
                   12125:     }
                   12126:     if (srchby == 'lastfirst') {
                   12127:         if (srchterm.indexOf(",") == -1) {
                   12128:             checkok = 0;
1.1222    damieng  12129:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  12130:         }
                   12131:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   12132:             checkok = 0;
1.1222    damieng  12133:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  12134:         }
                   12135:     }
                   12136:     if (checkok == 0) {
1.1222    damieng  12137:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  12138:         return;
                   12139:     }
                   12140:     if (checkok == 1) {
1.570     raeburn  12141:         callingForm.submit();
1.556     raeburn  12142:     }
                   12143: }
                   12144: 
                   12145: $newuserscript
                   12146: 
1.824     bisitz   12147: // ]]>
1.556     raeburn  12148: </script>
1.558     albertel 12149: 
                   12150: $new_user_create
                   12151: 
1.555     raeburn  12152: END_BLOCK
1.558     albertel 12153: 
1.876     raeburn  12154:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  12155:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  12156:                $domform.
                   12157:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  12158:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  12159:                $srchbysel.
                   12160:                $srchtypesel. 
                   12161:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   12162:                $srchinsel.
                   12163:                &Apache::lonhtmlcommon::row_closure(1). 
                   12164:                &Apache::lonhtmlcommon::end_pick_box().
                   12165:                '<br />';
1.1253    raeburn  12166:     return ($output,1);
1.555     raeburn  12167: }
                   12168: 
1.612     raeburn  12169: sub user_rule_check {
1.615     raeburn  12170:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  12171:     my ($response,%inst_response);
1.612     raeburn  12172:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  12173:         if (keys(%{$usershash}) > 1) {
                   12174:             my (%by_username,%by_id,%userdoms);
                   12175:             my $checkid; 
                   12176:             if (ref($checks) eq 'HASH') {
                   12177:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   12178:                     $checkid = 1;
                   12179:                 }
                   12180:             }
                   12181:             foreach my $user (keys(%{$usershash})) {
                   12182:                 my ($uname,$udom) = split(/:/,$user);
                   12183:                 if ($checkid) {
                   12184:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12185:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12186:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12187:                             $userdoms{$udom} = 1;
1.1227    raeburn  12188:                             if (ref($inst_results) eq 'HASH') {
                   12189:                                 $inst_results->{$uname.':'.$udom} = {};
                   12190:                             }
1.1226    raeburn  12191:                         }
                   12192:                     }
                   12193:                 } else {
                   12194:                     $by_username{$udom}{$uname} = 1;
                   12195:                     $userdoms{$udom} = 1;
1.1227    raeburn  12196:                     if (ref($inst_results) eq 'HASH') {
                   12197:                         $inst_results->{$uname.':'.$udom} = {};
                   12198:                     }
1.1226    raeburn  12199:                 }
                   12200:             }
                   12201:             foreach my $udom (keys(%userdoms)) {
                   12202:                 if (!$got_rules->{$udom}) {
                   12203:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12204:                                                              ['usercreation'],$udom);
                   12205:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12206:                         foreach my $item ('username','id') {
                   12207:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12208:                                 $$curr_rules{$udom}{$item} =
                   12209:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12210:                             }
                   12211:                         }
                   12212:                     }
                   12213:                     $got_rules->{$udom} = 1;
                   12214:                 }
1.612     raeburn  12215:             }
1.1226    raeburn  12216:             if ($checkid) {
                   12217:                 foreach my $udom (keys(%by_id)) {
                   12218:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12219:                     if ($outcome eq 'ok') {
1.1227    raeburn  12220:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12221:                             my $uname = $by_id{$udom}{$id};
                   12222:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12223:                         }
1.1226    raeburn  12224:                         if (ref($results) eq 'HASH') {
                   12225:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12226:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12227:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12228:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12229:                                 }
1.1226    raeburn  12230:                             }
                   12231:                         }
                   12232:                     }
1.612     raeburn  12233:                 }
1.615     raeburn  12234:             } else {
1.1226    raeburn  12235:                 foreach my $udom (keys(%by_username)) {
                   12236:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12237:                     if ($outcome eq 'ok') {
1.1227    raeburn  12238:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12239:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12240:                         }
1.1226    raeburn  12241:                         if (ref($results) eq 'HASH') {
                   12242:                             foreach my $uname (keys(%{$results})) {
                   12243:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12244:                             }
                   12245:                         }
                   12246:                     }
                   12247:                 }
1.612     raeburn  12248:             }
1.1226    raeburn  12249:         } elsif (keys(%{$usershash}) == 1) {
                   12250:             my $user = (keys(%{$usershash}))[0];
                   12251:             my ($uname,$udom) = split(/:/,$user);
                   12252:             if (($udom ne '') && ($uname ne '')) {
                   12253:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12254:                     if (ref($checks) eq 'HASH') {
                   12255:                         if (defined($checks->{'username'})) {
                   12256:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12257:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12258:                         } elsif (defined($checks->{'id'})) {
                   12259:                             if ($usershash->{$user}->{'id'} ne '') {
                   12260:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12261:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12262:                                                                   $usershash->{$user}->{'id'});
                   12263:                             } else {
                   12264:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12265:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12266:                             }
1.585     raeburn  12267:                         }
1.1226    raeburn  12268:                     } else {
                   12269:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12270:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12271:                        return;
                   12272:                     }
                   12273:                     if (!$got_rules->{$udom}) {
                   12274:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12275:                                                                  ['usercreation'],$udom);
                   12276:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12277:                             foreach my $item ('username','id') {
                   12278:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12279:                                    $$curr_rules{$udom}{$item} = 
                   12280:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12281:                                 }
                   12282:                             }
                   12283:                         }
                   12284:                         $got_rules->{$udom} = 1;
1.585     raeburn  12285:                     }
                   12286:                 }
1.1226    raeburn  12287:             } else {
                   12288:                 return;
                   12289:             }
                   12290:         } else {
                   12291:             return;
                   12292:         }
                   12293:         foreach my $user (keys(%{$usershash})) {
                   12294:             my ($uname,$udom) = split(/:/,$user);
                   12295:             next if (($udom eq '') || ($uname eq ''));
                   12296:             my $id;
1.1227    raeburn  12297:             if (ref($inst_results) eq 'HASH') {
                   12298:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12299:                     $id = $inst_results->{$user}->{'id'};
                   12300:                 }
                   12301:             }
                   12302:             if ($id eq '') { 
                   12303:                 if (ref($usershash->{$user})) {
                   12304:                     $id = $usershash->{$user}->{'id'};
                   12305:                 }
1.585     raeburn  12306:             }
1.612     raeburn  12307:             foreach my $item (keys(%{$checks})) {
                   12308:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12309:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12310:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12311:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12312:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12313:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12314:                                 if ($rule_check{$rule}) {
                   12315:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12316:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12317:                                         if (ref($inst_results) eq 'HASH') {
                   12318:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12319:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12320:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12321:                                                 } elsif ($item eq 'id') {
                   12322:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12323:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12324:                                                     }
1.615     raeburn  12325:                                                 }
1.612     raeburn  12326:                                             }
                   12327:                                         }
1.615     raeburn  12328:                                     }
                   12329:                                     last;
1.585     raeburn  12330:                                 }
                   12331:                             }
                   12332:                         }
                   12333:                     }
                   12334:                 }
                   12335:             }
                   12336:         }
                   12337:     }
1.612     raeburn  12338:     return;
                   12339: }
                   12340: 
                   12341: sub user_rule_formats {
                   12342:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12343:     my %text = ( 
                   12344:                  'username' => 'Usernames',
                   12345:                  'id'       => 'IDs',
                   12346:                );
                   12347:     my $output;
                   12348:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12349:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12350:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12351:             $output = '<br />'.
                   12352:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12353:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12354:                       ' <ul>';
1.612     raeburn  12355:             foreach my $rule (@{$ruleorder}) {
                   12356:                 if (ref($curr_rules) eq 'ARRAY') {
                   12357:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12358:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12359:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12360:                                         $rules->{$rule}{'desc'}.'</li>';
                   12361:                         }
                   12362:                     }
                   12363:                 }
                   12364:             }
                   12365:             $output .= '</ul>';
                   12366:         }
                   12367:     }
                   12368:     return $output;
                   12369: }
                   12370: 
                   12371: sub instrule_disallow_msg {
1.615     raeburn  12372:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12373:     my $response;
                   12374:     my %text = (
                   12375:                   item   => 'username',
                   12376:                   items  => 'usernames',
                   12377:                   match  => 'matches',
                   12378:                   do     => 'does',
                   12379:                   action => 'a username',
                   12380:                   one    => 'one',
                   12381:                );
                   12382:     if ($count > 1) {
                   12383:         $text{'item'} = 'usernames';
                   12384:         $text{'match'} ='match';
                   12385:         $text{'do'} = 'do';
                   12386:         $text{'action'} = 'usernames',
                   12387:         $text{'one'} = 'ones';
                   12388:     }
                   12389:     if ($checkitem eq 'id') {
                   12390:         $text{'items'} = 'IDs';
                   12391:         $text{'item'} = 'ID';
                   12392:         $text{'action'} = 'an ID';
1.615     raeburn  12393:         if ($count > 1) {
                   12394:             $text{'item'} = 'IDs';
                   12395:             $text{'action'} = 'IDs';
                   12396:         }
1.612     raeburn  12397:     }
1.674     bisitz   12398:     $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  12399:     if ($mode eq 'upload') {
                   12400:         if ($checkitem eq 'username') {
                   12401:             $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'}.");
                   12402:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12403:             $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  12404:         }
1.669     raeburn  12405:     } elsif ($mode eq 'selfcreate') {
                   12406:         if ($checkitem eq 'id') {
                   12407:             $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.");
                   12408:         }
1.615     raeburn  12409:     } else {
                   12410:         if ($checkitem eq 'username') {
                   12411:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12412:         } elsif ($checkitem eq 'id') {
                   12413:             $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.");
                   12414:         }
1.612     raeburn  12415:     }
                   12416:     return $response;
1.585     raeburn  12417: }
                   12418: 
1.624     raeburn  12419: sub personal_data_fieldtitles {
                   12420:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12421:                         id => 'Student/Employee ID',
                   12422:                         permanentemail => 'E-mail address',
                   12423:                         lastname => 'Last Name',
                   12424:                         firstname => 'First Name',
                   12425:                         middlename => 'Middle Name',
                   12426:                         generation => 'Generation',
                   12427:                         gen => 'Generation',
1.765     raeburn  12428:                         inststatus => 'Affiliation',
1.624     raeburn  12429:                    );
                   12430:     return %fieldtitles;
                   12431: }
                   12432: 
1.642     raeburn  12433: sub sorted_inst_types {
                   12434:     my ($dom) = @_;
1.1185    raeburn  12435:     my ($usertypes,$order);
                   12436:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12437:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12438:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12439:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12440:     } else {
                   12441:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12442:     }
1.642     raeburn  12443:     my $othertitle = &mt('All users');
                   12444:     if ($env{'request.course.id'}) {
1.668     raeburn  12445:         $othertitle  = &mt('Any users');
1.642     raeburn  12446:     }
                   12447:     my @types;
                   12448:     if (ref($order) eq 'ARRAY') {
                   12449:         @types = @{$order};
                   12450:     }
                   12451:     if (@types == 0) {
                   12452:         if (ref($usertypes) eq 'HASH') {
                   12453:             @types = sort(keys(%{$usertypes}));
                   12454:         }
                   12455:     }
                   12456:     if (keys(%{$usertypes}) > 0) {
                   12457:         $othertitle = &mt('Other users');
                   12458:     }
                   12459:     return ($othertitle,$usertypes,\@types);
                   12460: }
                   12461: 
1.645     raeburn  12462: sub get_institutional_codes {
1.1361    raeburn  12463:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12464: # Get complete list of course sections to update
                   12465:     my @currsections = ();
                   12466:     my @currxlists = ();
1.1361    raeburn  12467:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12468:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12469:     my $crskey = $crs.':'.$coursecode;
                   12470:     @{$unclutteredsec{$crskey}} = ();
                   12471:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12472: 
                   12473:     if ($$settings{'internal.sectionnums'} ne '') {
                   12474:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12475:     }
                   12476: 
                   12477:     if ($$settings{'internal.crosslistings'} ne '') {
                   12478:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12479:     }
                   12480: 
                   12481:     if (@currxlists > 0) {
1.1361    raeburn  12482:         foreach my $xl (@currxlists) {
                   12483:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12484:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12485:                     push(@{$allcourses},$1);
1.645     raeburn  12486:                     $$LC_code{$1} = $2;
                   12487:                 }
                   12488:             }
                   12489:         }
                   12490:     }
1.1361    raeburn  12491: 
1.645     raeburn  12492:     if (@currsections > 0) {
1.1361    raeburn  12493:         foreach my $sec (@currsections) {
                   12494:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12495:                 my $instsec = $1;
1.645     raeburn  12496:                 my $lc_sec = $2;
1.1361    raeburn  12497:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12498:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12499:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12500:                 }
                   12501:             }
                   12502:         }
                   12503:     }
                   12504: 
                   12505:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12506:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12507:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12508:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12509:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12510:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12511:                     push(@{$allcourses},$sec);
1.1361    raeburn  12512:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12513:                 }
                   12514:             }
                   12515:         }
                   12516:     }
                   12517:     return;
                   12518: }
                   12519: 
1.971     raeburn  12520: sub get_standard_codeitems {
                   12521:     return ('Year','Semester','Department','Number','Section');
                   12522: }
                   12523: 
1.112     bowersj2 12524: =pod
                   12525: 
1.780     raeburn  12526: =head1 Slot Helpers
                   12527: 
                   12528: =over 4
                   12529: 
                   12530: =item * sorted_slots()
                   12531: 
1.1040    raeburn  12532: Sorts an array of slot names in order of an optional sort key,
                   12533: default sort is by slot start time (earliest first). 
1.780     raeburn  12534: 
                   12535: Inputs:
                   12536: 
                   12537: =over 4
                   12538: 
                   12539: slotsarr  - Reference to array of unsorted slot names.
                   12540: 
                   12541: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12542: 
1.1040    raeburn  12543: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12544: 
1.549     albertel 12545: =back
                   12546: 
1.780     raeburn  12547: Returns:
                   12548: 
                   12549: =over 4
                   12550: 
1.1040    raeburn  12551: sorted   - An array of slot names sorted by a specified sort key 
                   12552:            (default sort key is start time of the slot).
1.780     raeburn  12553: 
                   12554: =back
                   12555: 
                   12556: =cut
                   12557: 
                   12558: 
                   12559: sub sorted_slots {
1.1040    raeburn  12560:     my ($slotsarr,$slots,$sortkey) = @_;
                   12561:     if ($sortkey eq '') {
                   12562:         $sortkey = 'starttime';
                   12563:     }
1.780     raeburn  12564:     my @sorted;
                   12565:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12566:         @sorted =
                   12567:             sort {
                   12568:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12569:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12570:                      }
                   12571:                      if (ref($slots->{$a})) { return -1;}
                   12572:                      if (ref($slots->{$b})) { return 1;}
                   12573:                      return 0;
                   12574:                  } @{$slotsarr};
                   12575:     }
                   12576:     return @sorted;
                   12577: }
                   12578: 
1.1040    raeburn  12579: =pod
                   12580: 
                   12581: =item * get_future_slots()
                   12582: 
                   12583: Inputs:
                   12584: 
                   12585: =over 4
                   12586: 
                   12587: cnum - course number
                   12588: 
                   12589: cdom - course domain
                   12590: 
                   12591: now - current UNIX time
                   12592: 
                   12593: symb - optional symb
                   12594: 
                   12595: =back
                   12596: 
                   12597: Returns:
                   12598: 
                   12599: =over 4
                   12600: 
                   12601: sorted_reservable - ref to array of student_schedulable slots currently 
                   12602:                     reservable, ordered by end date of reservation period.
                   12603: 
                   12604: reservable_now - ref to hash of student_schedulable slots currently
                   12605:                  reservable.
                   12606: 
                   12607:     Keys in inner hash are:
                   12608:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12609:     (b) endreserve: end date of reservation period.
                   12610:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12611:         selected.
1.1040    raeburn  12612: 
                   12613: sorted_future - ref to array of student_schedulable slots reservable in
                   12614:                 the future, ordered by start date of reservation period.
                   12615: 
                   12616: future_reservable - ref to hash of student_schedulable slots reservable
                   12617:                     in the future.
                   12618: 
                   12619:     Keys in inner hash are:
                   12620:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12621:     (b) startreserve: start date of reservation period.
                   12622:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12623:         selected.
1.1040    raeburn  12624: 
                   12625: =back
                   12626: 
                   12627: =cut
                   12628: 
                   12629: sub get_future_slots {
                   12630:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12631:     my $map;
                   12632:     if ($symb) {
                   12633:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12634:     }
1.1040    raeburn  12635:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12636:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12637:     foreach my $slot (keys(%slots)) {
                   12638:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12639:         if ($symb) {
1.1229    raeburn  12640:             if ($slots{$slot}->{'symb'} ne '') {
                   12641:                 my $canuse;
                   12642:                 my %oksymbs;
                   12643:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12644:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12645:                 if ($oksymbs{$symb}) {
                   12646:                     $canuse = 1;
                   12647:                 } else {
                   12648:                     foreach my $item (@slotsymbs) {
                   12649:                         if ($item =~ /\.(page|sequence)$/) {
                   12650:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12651:                             if (($map ne '') && ($map eq $sloturl)) {
                   12652:                                 $canuse = 1;
                   12653:                                 last;
                   12654:                             }
                   12655:                         }
                   12656:                     }
                   12657:                 }
                   12658:                 next unless ($canuse);
                   12659:             }
1.1040    raeburn  12660:         }
                   12661:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12662:             ($slots{$slot}->{'endtime'} > $now)) {
                   12663:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12664:                 my $userallowed = 0;
                   12665:                 if ($slots{$slot}->{'allowedsections'}) {
                   12666:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12667:                     if (!defined($env{'request.role.sec'})
                   12668:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12669:                         $userallowed=1;
                   12670:                     } else {
                   12671:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12672:                             $userallowed=1;
                   12673:                         }
                   12674:                     }
                   12675:                     unless ($userallowed) {
                   12676:                         if (defined($env{'request.course.groups'})) {
                   12677:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12678:                             foreach my $group (@groups) {
                   12679:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12680:                                     $userallowed=1;
                   12681:                                     last;
                   12682:                                 }
                   12683:                             }
                   12684:                         }
                   12685:                     }
                   12686:                 }
                   12687:                 if ($slots{$slot}->{'allowedusers'}) {
                   12688:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12689:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12690:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12691:                         $userallowed = 1;
                   12692:                     }
                   12693:                 }
                   12694:                 next unless($userallowed);
                   12695:             }
                   12696:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12697:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12698:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12699:             my $uniqueperiod;
                   12700:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12701:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12702:             }
1.1040    raeburn  12703:             if (($startreserve < $now) &&
                   12704:                 (!$endreserve || $endreserve > $now)) {
                   12705:                 my $lastres = $endreserve;
                   12706:                 if (!$lastres) {
                   12707:                     $lastres = $slots{$slot}->{'starttime'};
                   12708:                 }
                   12709:                 $reservable_now{$slot} = {
                   12710:                                            symb       => $symb,
1.1250    raeburn  12711:                                            endreserve => $lastres,
                   12712:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12713:                                          };
                   12714:             } elsif (($startreserve > $now) &&
                   12715:                      (!$endreserve || $endreserve > $startreserve)) {
                   12716:                 $future_reservable{$slot} = {
                   12717:                                               symb         => $symb,
1.1250    raeburn  12718:                                               startreserve => $startreserve,
                   12719:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12720:                                             };
                   12721:             }
                   12722:         }
                   12723:     }
                   12724:     my @unsorted_reservable = keys(%reservable_now);
                   12725:     if (@unsorted_reservable > 0) {
                   12726:         @sorted_reservable = 
                   12727:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12728:     }
                   12729:     my @unsorted_future = keys(%future_reservable);
                   12730:     if (@unsorted_future > 0) {
                   12731:         @sorted_future =
                   12732:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12733:     }
                   12734:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12735: }
1.780     raeburn  12736: 
                   12737: =pod
                   12738: 
1.1057    foxr     12739: =back
                   12740: 
1.549     albertel 12741: =head1 HTTP Helpers
                   12742: 
                   12743: =over 4
                   12744: 
1.648     raeburn  12745: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12746: 
1.258     albertel 12747: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12748: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12749: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12750: 
                   12751: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12752: $possible_names is an ref to an array of form element names.  As an example:
                   12753: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12754: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12755: 
                   12756: =cut
1.1       albertel 12757: 
1.6       albertel 12758: sub get_unprocessed_cgi {
1.25      albertel 12759:   my ($query,$possible_names)= @_;
1.26      matthew  12760:   # $Apache::lonxml::debug=1;
1.356     albertel 12761:   foreach my $pair (split(/&/,$query)) {
                   12762:     my ($name, $value) = split(/=/,$pair);
1.369     www      12763:     $name = &unescape($name);
1.25      albertel 12764:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12765:       $value =~ tr/+/ /;
                   12766:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12767:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12768:     }
1.16      harris41 12769:   }
1.6       albertel 12770: }
                   12771: 
1.112     bowersj2 12772: =pod
                   12773: 
1.648     raeburn  12774: =item * &cacheheader() 
1.112     bowersj2 12775: 
                   12776: returns cache-controlling header code
                   12777: 
                   12778: =cut
                   12779: 
1.7       albertel 12780: sub cacheheader {
1.258     albertel 12781:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12782:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12783:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12784:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12785:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12786:     return $output;
1.7       albertel 12787: }
                   12788: 
1.112     bowersj2 12789: =pod
                   12790: 
1.648     raeburn  12791: =item * &no_cache($r) 
1.112     bowersj2 12792: 
                   12793: specifies header code to not have cache
                   12794: 
                   12795: =cut
                   12796: 
1.9       albertel 12797: sub no_cache {
1.216     albertel 12798:     my ($r) = @_;
                   12799:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12800: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12801:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12802:     $r->no_cache(1);
                   12803:     $r->header_out("Expires" => $date);
                   12804:     $r->header_out("Pragma" => "no-cache");
1.123     www      12805: }
                   12806: 
                   12807: sub content_type {
1.181     albertel 12808:     my ($r,$type,$charset) = @_;
1.299     foxr     12809:     if ($r) {
                   12810: 	#  Note that printout.pl calls this with undef for $r.
                   12811: 	&no_cache($r);
                   12812:     }
1.258     albertel 12813:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12814:     unless ($charset) {
                   12815: 	$charset=&Apache::lonlocal::current_encoding;
                   12816:     }
                   12817:     if ($charset) { $type.='; charset='.$charset; }
                   12818:     if ($r) {
                   12819: 	$r->content_type($type);
                   12820:     } else {
                   12821: 	print("Content-type: $type\n\n");
                   12822:     }
1.9       albertel 12823: }
1.25      albertel 12824: 
1.112     bowersj2 12825: =pod
                   12826: 
1.648     raeburn  12827: =item * &add_to_env($name,$value) 
1.112     bowersj2 12828: 
1.258     albertel 12829: adds $name to the %env hash with value
1.112     bowersj2 12830: $value, if $name already exists, the entry is converted to an array
                   12831: reference and $value is added to the array.
                   12832: 
                   12833: =cut
                   12834: 
1.25      albertel 12835: sub add_to_env {
                   12836:   my ($name,$value)=@_;
1.258     albertel 12837:   if (defined($env{$name})) {
                   12838:     if (ref($env{$name})) {
1.25      albertel 12839:       #already have multiple values
1.258     albertel 12840:       push(@{ $env{$name} },$value);
1.25      albertel 12841:     } else {
                   12842:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12843:       my $first=$env{$name};
                   12844:       undef($env{$name});
                   12845:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12846:     }
                   12847:   } else {
1.258     albertel 12848:     $env{$name}=$value;
1.25      albertel 12849:   }
1.31      albertel 12850: }
1.149     albertel 12851: 
                   12852: =pod
                   12853: 
1.648     raeburn  12854: =item * &get_env_multiple($name) 
1.149     albertel 12855: 
1.258     albertel 12856: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12857: values may be defined and end up as an array ref.
                   12858: 
                   12859: returns an array of values
                   12860: 
                   12861: =cut
                   12862: 
                   12863: sub get_env_multiple {
                   12864:     my ($name) = @_;
                   12865:     my @values;
1.258     albertel 12866:     if (defined($env{$name})) {
1.149     albertel 12867:         # exists is it an array
1.258     albertel 12868:         if (ref($env{$name})) {
                   12869:             @values=@{ $env{$name} };
1.149     albertel 12870:         } else {
1.258     albertel 12871:             $values[0]=$env{$name};
1.149     albertel 12872:         }
                   12873:     }
                   12874:     return(@values);
                   12875: }
                   12876: 
1.1249    damieng  12877: # Looks at given dependencies, and returns something depending on the context.
                   12878: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12879: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12880: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12881: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12882: # $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.
                   12883: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12884: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12885: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12886: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12887: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12888: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12889: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12890: # @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)
                   12891: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12892: sub ask_for_embedded_content {
1.1249    damieng  12893:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12894:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12895:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12896:         %currsubfile,%unused,$rem);
1.1071    raeburn  12897:     my $counter = 0;
                   12898:     my $numnew = 0;
1.987     raeburn  12899:     my $numremref = 0;
                   12900:     my $numinvalid = 0;
                   12901:     my $numpathchg = 0;
                   12902:     my $numexisting = 0;
1.1071    raeburn  12903:     my $numunused = 0;
                   12904:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12905:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12906:     my $heading = &mt('Upload embedded files');
                   12907:     my $buttontext = &mt('Upload');
                   12908: 
1.1249    damieng  12909:     # fills these variables based on the context:
                   12910:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12911:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12912:     if ($env{'request.course.id'}) {
1.1123    raeburn  12913:         if ($actionurl eq '/adm/dependencies') {
                   12914:             $navmap = Apache::lonnavmaps::navmap->new();
                   12915:         }
                   12916:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12917:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12918:     }
1.1123    raeburn  12919:     if (($actionurl eq '/adm/portfolio') || 
                   12920:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12921:         my $current_path='/';
                   12922:         if ($env{'form.currentpath'}) {
                   12923:             $current_path = $env{'form.currentpath'};
                   12924:         }
                   12925:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12926:             $udom = $cdom;
                   12927:             $uname = $cnum;
1.984     raeburn  12928:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12929:         } else {
                   12930:             $udom = $env{'user.domain'};
                   12931:             $uname = $env{'user.name'};
                   12932:             $url = '/userfiles/portfolio';
                   12933:         }
1.987     raeburn  12934:         $toplevel = $url.'/';
1.984     raeburn  12935:         $url .= $current_path;
                   12936:         $getpropath = 1;
1.987     raeburn  12937:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12938:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12939:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12940:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12941:         $toplevel = $url;
1.984     raeburn  12942:         if ($rest ne '') {
1.987     raeburn  12943:             $url .= $rest;
                   12944:         }
                   12945:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12946:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12947:             $url = $args->{'docs_url'};
                   12948:             $toplevel = $url;
1.1084    raeburn  12949:             if ($args->{'context'} eq 'paste') {
                   12950:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12951:                 ($path) = 
                   12952:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12953:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12954:                 $fileloc =~ s{^/}{};
                   12955:             }
1.1071    raeburn  12956:         }
1.1084    raeburn  12957:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12958:         if ($env{'request.course.id'} ne '') {
                   12959:             if (ref($args) eq 'HASH') {
                   12960:                 $url = $args->{'docs_url'};
                   12961:                 $title = $args->{'docs_title'};
1.1126    raeburn  12962:                 $toplevel = $url; 
                   12963:                 unless ($toplevel =~ m{^/}) {
                   12964:                     $toplevel = "/$url";
                   12965:                 }
1.1085    raeburn  12966:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12967:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12968:                     $path = $1;
                   12969:                 } else {
                   12970:                     ($path) =
                   12971:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12972:                 }
1.1195    raeburn  12973:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12974:                     $fileloc = $toplevel;
                   12975:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12976:                     my ($udom,$uname,$fname) =
                   12977:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12978:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12979:                 } else {
                   12980:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12981:                 }
1.1071    raeburn  12982:                 $fileloc =~ s{^/}{};
                   12983:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12984:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12985:             }
1.987     raeburn  12986:         }
1.1123    raeburn  12987:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12988:         $udom = $cdom;
                   12989:         $uname = $cnum;
                   12990:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12991:         $toplevel = $url;
                   12992:         $path = $url;
                   12993:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12994:         $fileloc =~ s{^/}{};
1.987     raeburn  12995:     }
1.1249    damieng  12996:     
                   12997:     # parses the dependency paths to get some info
                   12998:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12999:     # $newfiles: hash URL -> 1 for new files or external URLs
                   13000:     # (will be completed later)
                   13001:     # $mapping:
                   13002:     #   for external URLs: external URL -> external URL
                   13003:     #   for relative paths: clean path -> original path
                   13004:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   13005:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  13006:     foreach my $file (keys(%{$allfiles})) {
                   13007:         my $embed_file;
                   13008:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   13009:             $embed_file = $1;
                   13010:         } else {
                   13011:             $embed_file = $file;
                   13012:         }
1.1158    raeburn  13013:         my ($absolutepath,$cleaned_file);
                   13014:         if ($embed_file =~ m{^\w+://}) {
                   13015:             $cleaned_file = $embed_file;
1.1147    raeburn  13016:             $newfiles{$cleaned_file} = 1;
                   13017:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  13018:         } else {
1.1158    raeburn  13019:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  13020:             if ($embed_file =~ m{^/}) {
                   13021:                 $absolutepath = $embed_file;
                   13022:             }
1.1147    raeburn  13023:             if ($cleaned_file =~ m{/}) {
                   13024:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  13025:                 $path = &check_for_traversal($path,$url,$toplevel);
                   13026:                 my $item = $fname;
                   13027:                 if ($path ne '') {
                   13028:                     $item = $path.'/'.$fname;
                   13029:                     $subdependencies{$path}{$fname} = 1;
                   13030:                 } else {
                   13031:                     $dependencies{$item} = 1;
                   13032:                 }
                   13033:                 if ($absolutepath) {
                   13034:                     $mapping{$item} = $absolutepath;
                   13035:                 } else {
                   13036:                     $mapping{$item} = $embed_file;
                   13037:                 }
                   13038:             } else {
                   13039:                 $dependencies{$embed_file} = 1;
                   13040:                 if ($absolutepath) {
1.1147    raeburn  13041:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  13042:                 } else {
1.1147    raeburn  13043:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  13044:                 }
                   13045:             }
1.984     raeburn  13046:         }
                   13047:     }
1.1249    damieng  13048:     
                   13049:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   13050:     # and lists
                   13051:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   13052:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   13053:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   13054:     #                                    the path had to be cleaned up
                   13055:     # $existing: hash clean path -> 1 if the file exists
                   13056:     # $numexisting: number of keys in $existing
                   13057:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   13058:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   13059:     #                                      dependency subdirectories that are
                   13060:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  13061:     my $dirptr = 16384;
1.984     raeburn  13062:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  13063:         $currsubfile{$path} = {};
1.1123    raeburn  13064:         if (($actionurl eq '/adm/portfolio') || 
                   13065:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13066:             my ($sublistref,$listerror) =
                   13067:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   13068:             if (ref($sublistref) eq 'ARRAY') {
                   13069:                 foreach my $line (@{$sublistref}) {
                   13070:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  13071:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  13072:                 }
1.984     raeburn  13073:             }
1.987     raeburn  13074:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13075:             if (opendir(my $dir,$url.'/'.$path)) {
                   13076:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  13077:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   13078:             }
1.1084    raeburn  13079:         } elsif (($actionurl eq '/adm/dependencies') ||
                   13080:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13081:                   ($args->{'context'} eq 'paste')) ||
                   13082:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13083:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  13084:                 my $dir;
                   13085:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   13086:                     $dir = $fileloc;
                   13087:                 } else {
                   13088:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13089:                 }
1.1071    raeburn  13090:                 if ($dir ne '') {
                   13091:                     my ($sublistref,$listerror) =
                   13092:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   13093:                     if (ref($sublistref) eq 'ARRAY') {
                   13094:                         foreach my $line (@{$sublistref}) {
                   13095:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   13096:                                 undef,$mtime)=split(/\&/,$line,12);
                   13097:                             unless (($testdir&$dirptr) ||
                   13098:                                     ($file_name =~ /^\.\.?$/)) {
                   13099:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   13100:                             }
                   13101:                         }
                   13102:                     }
                   13103:                 }
1.984     raeburn  13104:             }
                   13105:         }
                   13106:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  13107:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  13108:                 my $item = $path.'/'.$file;
                   13109:                 unless ($mapping{$item} eq $item) {
                   13110:                     $pathchanges{$item} = 1;
                   13111:                 }
                   13112:                 $existing{$item} = 1;
                   13113:                 $numexisting ++;
                   13114:             } else {
                   13115:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  13116:             }
                   13117:         }
1.1071    raeburn  13118:         if ($actionurl eq '/adm/dependencies') {
                   13119:             foreach my $path (keys(%currsubfile)) {
                   13120:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   13121:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   13122:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  13123:                              next if (($rem ne '') &&
                   13124:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   13125:                                        (ref($navmap) &&
                   13126:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   13127:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13128:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  13129:                              $unused{$path.'/'.$file} = 1; 
                   13130:                          }
                   13131:                     }
                   13132:                 }
                   13133:             }
                   13134:         }
1.984     raeburn  13135:     }
1.1249    damieng  13136:     
                   13137:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   13138:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  13139:     my %currfile;
1.1123    raeburn  13140:     if (($actionurl eq '/adm/portfolio') ||
                   13141:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13142:         my ($dirlistref,$listerror) =
                   13143:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   13144:         if (ref($dirlistref) eq 'ARRAY') {
                   13145:             foreach my $line (@{$dirlistref}) {
                   13146:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   13147:                 $currfile{$file_name} = 1;
                   13148:             }
1.984     raeburn  13149:         }
1.987     raeburn  13150:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13151:         if (opendir(my $dir,$url)) {
1.987     raeburn  13152:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  13153:             map {$currfile{$_} = 1;} @dir_list;
                   13154:         }
1.1084    raeburn  13155:     } elsif (($actionurl eq '/adm/dependencies') ||
                   13156:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13157:               ($args->{'context'} eq 'paste')) ||
                   13158:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13159:         if ($env{'request.course.id'} ne '') {
                   13160:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13161:             if ($dir ne '') {
                   13162:                 my ($dirlistref,$listerror) =
                   13163:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   13164:                 if (ref($dirlistref) eq 'ARRAY') {
                   13165:                     foreach my $line (@{$dirlistref}) {
                   13166:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   13167:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   13168:                         unless (($testdir&$dirptr) ||
                   13169:                                 ($file_name =~ /^\.\.?$/)) {
                   13170:                             $currfile{$file_name} = [$size,$mtime];
                   13171:                         }
                   13172:                     }
                   13173:                 }
                   13174:             }
                   13175:         }
1.984     raeburn  13176:     }
1.1249    damieng  13177:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   13178:     # are not in subdirectories, using $currfile
1.984     raeburn  13179:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  13180:         if (exists($currfile{$file})) {
1.987     raeburn  13181:             unless ($mapping{$file} eq $file) {
                   13182:                 $pathchanges{$file} = 1;
                   13183:             }
                   13184:             $existing{$file} = 1;
                   13185:             $numexisting ++;
                   13186:         } else {
1.984     raeburn  13187:             $newfiles{$file} = 1;
                   13188:         }
                   13189:     }
1.1071    raeburn  13190:     foreach my $file (keys(%currfile)) {
                   13191:         unless (($file eq $filename) ||
                   13192:                 ($file eq $filename.'.bak') ||
                   13193:                 ($dependencies{$file})) {
1.1085    raeburn  13194:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13195:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13196:                     next if (($rem ne '') &&
                   13197:                              (($env{"httpref.$rem".$file} ne '') ||
                   13198:                               (ref($navmap) &&
                   13199:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13200:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13201:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13202:                 }
1.1085    raeburn  13203:             }
1.1071    raeburn  13204:             $unused{$file} = 1;
                   13205:         }
                   13206:     }
1.1249    damieng  13207:     
                   13208:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13209:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13210:         ($args->{'context'} eq 'paste')) {
                   13211:         $counter = scalar(keys(%existing));
                   13212:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13213:         return ($output,$counter,$numpathchg,\%existing);
                   13214:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13215:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13216:         $counter = scalar(keys(%existing));
                   13217:         $numpathchg = scalar(keys(%pathchanges));
                   13218:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13219:     }
1.1249    damieng  13220:     
                   13221:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13222:     
                   13223:     # $upload_output: missing dependencies (with upload form)
                   13224:     # $modify_output: uploaded dependencies (in use)
                   13225:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13226:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13227:         if ($actionurl eq '/adm/dependencies') {
                   13228:             next if ($embed_file =~ m{^\w+://});
                   13229:         }
1.660     raeburn  13230:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13231:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13232:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13233:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13234:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13235:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13236:         }
1.1123    raeburn  13237:         $upload_output .= '</td>';
1.1071    raeburn  13238:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13239:             $upload_output.='<td align="right">'.
                   13240:                             '<span class="LC_info LC_fontsize_medium">'.
                   13241:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13242:             $numremref++;
1.660     raeburn  13243:         } elsif ($args->{'error_on_invalid_names'}
                   13244:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13245:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13246:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13247:             $numinvalid++;
1.660     raeburn  13248:         } else {
1.1123    raeburn  13249:             $upload_output .= '<td>'.
                   13250:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13251:                                                      $embed_file,\%mapping,
1.1071    raeburn  13252:                                                      $allfiles,$codebase,'upload');
                   13253:             $counter ++;
                   13254:             $numnew ++;
1.987     raeburn  13255:         }
                   13256:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13257:     }
                   13258:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13259:         if ($actionurl eq '/adm/dependencies') {
                   13260:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13261:             $modify_output .= &start_data_table_row().
                   13262:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13263:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13264:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13265:                               '<td>'.$size.'</td>'.
                   13266:                               '<td>'.$mtime.'</td>'.
                   13267:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13268:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13269:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13270:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13271:                               &embedded_file_element('upload_embedded',$counter,
                   13272:                                                      $embed_file,\%mapping,
                   13273:                                                      $allfiles,$codebase,'modify').
                   13274:                               '</div></td>'.
                   13275:                               &end_data_table_row()."\n";
                   13276:             $counter ++;
                   13277:         } else {
                   13278:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13279:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13280:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13281:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13282:                               &Apache::loncommon::end_data_table_row()."\n";
                   13283:         }
                   13284:     }
                   13285:     my $delidx = $counter;
                   13286:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13287:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13288:         $delete_output .= &start_data_table_row().
                   13289:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13290:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13291:                           '<td>'.$size.'</td>'.
                   13292:                           '<td>'.$mtime.'</td>'.
                   13293:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13294:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13295:                           &embedded_file_element('upload_embedded',$delidx,
                   13296:                                                  $oldfile,\%mapping,$allfiles,
                   13297:                                                  $codebase,'delete').'</td>'.
                   13298:                           &end_data_table_row()."\n"; 
                   13299:         $numunused ++;
                   13300:         $delidx ++;
1.987     raeburn  13301:     }
                   13302:     if ($upload_output) {
                   13303:         $upload_output = &start_data_table().
                   13304:                          $upload_output.
                   13305:                          &end_data_table()."\n";
                   13306:     }
1.1071    raeburn  13307:     if ($modify_output) {
                   13308:         $modify_output = &start_data_table().
                   13309:                          &start_data_table_header_row().
                   13310:                          '<th>'.&mt('File').'</th>'.
                   13311:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13312:                          '<th>'.&mt('Modified').'</th>'.
                   13313:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13314:                          &end_data_table_header_row().
                   13315:                          $modify_output.
                   13316:                          &end_data_table()."\n";
                   13317:     }
                   13318:     if ($delete_output) {
                   13319:         $delete_output = &start_data_table().
                   13320:                          &start_data_table_header_row().
                   13321:                          '<th>'.&mt('File').'</th>'.
                   13322:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13323:                          '<th>'.&mt('Modified').'</th>'.
                   13324:                          '<th>'.&mt('Delete?').'</th>'.
                   13325:                          &end_data_table_header_row().
                   13326:                          $delete_output.
                   13327:                          &end_data_table()."\n";
                   13328:     }
1.987     raeburn  13329:     my $applies = 0;
                   13330:     if ($numremref) {
                   13331:         $applies ++;
                   13332:     }
                   13333:     if ($numinvalid) {
                   13334:         $applies ++;
                   13335:     }
                   13336:     if ($numexisting) {
                   13337:         $applies ++;
                   13338:     }
1.1071    raeburn  13339:     if ($counter || $numunused) {
1.987     raeburn  13340:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13341:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13342:                   $state.'<h3>'.$heading.'</h3>'; 
                   13343:         if ($actionurl eq '/adm/dependencies') {
                   13344:             if ($numnew) {
                   13345:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13346:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13347:                            $upload_output.'<br />'."\n";
                   13348:             }
                   13349:             if ($numexisting) {
                   13350:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13351:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13352:                            $modify_output.'<br />'."\n";
                   13353:                            $buttontext = &mt('Save changes');
                   13354:             }
                   13355:             if ($numunused) {
                   13356:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13357:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13358:                            $delete_output.'<br />'."\n";
                   13359:                            $buttontext = &mt('Save changes');
                   13360:             }
                   13361:         } else {
                   13362:             $output .= $upload_output.'<br />'."\n";
                   13363:         }
                   13364:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13365:                    $counter.'" />'."\n";
                   13366:         if ($actionurl eq '/adm/dependencies') { 
                   13367:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13368:                        $numnew.'" />'."\n";
                   13369:         } elsif ($actionurl eq '') {
1.987     raeburn  13370:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13371:         }
                   13372:     } elsif ($applies) {
                   13373:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13374:         if ($applies > 1) {
                   13375:             $output .=  
1.1123    raeburn  13376:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13377:             if ($numremref) {
                   13378:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13379:             }
                   13380:             if ($numinvalid) {
                   13381:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13382:             }
                   13383:             if ($numexisting) {
                   13384:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13385:             }
                   13386:             $output .= '</ul><br />';
                   13387:         } elsif ($numremref) {
                   13388:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13389:         } elsif ($numinvalid) {
                   13390:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13391:         } elsif ($numexisting) {
                   13392:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13393:         }
                   13394:         $output .= $upload_output.'<br />';
                   13395:     }
                   13396:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13397:     $chgcount = $counter;
1.987     raeburn  13398:     if (keys(%pathchanges) > 0) {
                   13399:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13400:             if ($counter) {
1.987     raeburn  13401:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13402:                                                   $embed_file,\%mapping,
1.1071    raeburn  13403:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13404:             } else {
                   13405:                 $pathchange_output .= 
                   13406:                     &start_data_table_row().
                   13407:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13408:                     $chgcount.'" checked="checked" /></td>'.
                   13409:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13410:                     '<td>'.$embed_file.
                   13411:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13412:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13413:                     '</td>'.&end_data_table_row();
1.660     raeburn  13414:             }
1.987     raeburn  13415:             $numpathchg ++;
                   13416:             $chgcount ++;
1.660     raeburn  13417:         }
                   13418:     }
1.1127    raeburn  13419:     if (($counter) || ($numunused)) {
1.987     raeburn  13420:         if ($numpathchg) {
                   13421:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13422:                        $numpathchg.'" />'."\n";
                   13423:         }
                   13424:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13425:             ($actionurl eq '/adm/imsimport')) {
                   13426:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13427:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13428:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13429:         } elsif ($actionurl eq '/adm/dependencies') {
                   13430:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13431:         }
1.1123    raeburn  13432:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13433:     } elsif ($numpathchg) {
                   13434:         my %pathchange = ();
                   13435:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13436:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13437:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13438:         }
1.987     raeburn  13439:     }
1.1071    raeburn  13440:     return ($output,$counter,$numpathchg);
1.987     raeburn  13441: }
                   13442: 
1.1147    raeburn  13443: =pod
                   13444: 
                   13445: =item * clean_path($name)
                   13446: 
                   13447: Performs clean-up of directories, subdirectories and filename in an
                   13448: embedded object, referenced in an HTML file which is being uploaded
                   13449: to a course or portfolio, where 
                   13450: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13451: checked.
                   13452: 
                   13453: Clean-up is similar to replacements in lonnet::clean_filename()
                   13454: except each / between sub-directory and next level is preserved.
                   13455: 
                   13456: =cut
                   13457: 
                   13458: sub clean_path {
                   13459:     my ($embed_file) = @_;
                   13460:     $embed_file =~s{^/+}{};
                   13461:     my @contents;
                   13462:     if ($embed_file =~ m{/}) {
                   13463:         @contents = split(/\//,$embed_file);
                   13464:     } else {
                   13465:         @contents = ($embed_file);
                   13466:     }
                   13467:     my $lastidx = scalar(@contents)-1;
                   13468:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13469:         $contents[$i]=~s{\\}{/}g;
                   13470:         $contents[$i]=~s/\s+/\_/g;
                   13471:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13472:         if ($i == $lastidx) {
                   13473:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13474:         }
                   13475:     }
                   13476:     if ($lastidx > 0) {
                   13477:         return join('/',@contents);
                   13478:     } else {
                   13479:         return $contents[0];
                   13480:     }
                   13481: }
                   13482: 
1.987     raeburn  13483: sub embedded_file_element {
1.1071    raeburn  13484:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13485:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13486:                    (ref($codebase) eq 'HASH'));
                   13487:     my $output;
1.1071    raeburn  13488:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13489:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13490:     }
                   13491:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13492:                &escape($embed_file).'" />';
                   13493:     unless (($context eq 'upload_embedded') && 
                   13494:             ($mapping->{$embed_file} eq $embed_file)) {
                   13495:         $output .='
                   13496:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13497:     }
                   13498:     my $attrib;
                   13499:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13500:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13501:     }
                   13502:     $output .=
                   13503:         "\n\t\t".
                   13504:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13505:         $attrib.'" />';
                   13506:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13507:         $output .=
                   13508:             "\n\t\t".
                   13509:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13510:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13511:     }
1.987     raeburn  13512:     return $output;
1.660     raeburn  13513: }
                   13514: 
1.1071    raeburn  13515: sub get_dependency_details {
                   13516:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13517:     my ($size,$mtime,$showsize,$showmtime);
                   13518:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13519:         if ($embed_file =~ m{/}) {
                   13520:             my ($path,$fname) = split(/\//,$embed_file);
                   13521:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13522:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13523:             }
                   13524:         } else {
                   13525:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13526:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13527:             }
                   13528:         }
                   13529:         $showsize = $size/1024.0;
                   13530:         $showsize = sprintf("%.1f",$showsize);
                   13531:         if ($mtime > 0) {
                   13532:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13533:         }
                   13534:     }
                   13535:     return ($showsize,$showmtime);
                   13536: }
                   13537: 
                   13538: sub ask_embedded_js {
                   13539:     return <<"END";
                   13540: <script type="text/javascript"">
                   13541: // <![CDATA[
                   13542: function toggleBrowse(counter) {
                   13543:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13544:     var fileid = document.getElementById('embedded_item_'+counter);
                   13545:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13546:     if (chkboxid.checked == true) {
                   13547:         uploaddivid.style.display='block';
                   13548:     } else {
                   13549:         uploaddivid.style.display='none';
                   13550:         fileid.value = '';
                   13551:     }
                   13552: }
                   13553: // ]]>
                   13554: </script>
                   13555: 
                   13556: END
                   13557: }
                   13558: 
1.661     raeburn  13559: sub upload_embedded {
                   13560:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13561:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13562:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13563:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13564:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13565:         my $orig_uploaded_filename =
                   13566:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13567:         foreach my $type ('orig','ref','attrib','codebase') {
                   13568:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13569:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13570:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13571:             }
                   13572:         }
1.661     raeburn  13573:         my ($path,$fname) =
                   13574:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13575:         # no path, whole string is fname
                   13576:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13577:         $fname = &Apache::lonnet::clean_filename($fname);
                   13578:         # See if there is anything left
                   13579:         next if ($fname eq '');
                   13580: 
                   13581:         # Check if file already exists as a file or directory.
                   13582:         my ($state,$msg);
                   13583:         if ($context eq 'portfolio') {
                   13584:             my $port_path = $dirpath;
                   13585:             if ($group ne '') {
                   13586:                 $port_path = "groups/$group/$port_path";
                   13587:             }
1.987     raeburn  13588:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13589:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13590:                                               $dir_root,$port_path,$disk_quota,
                   13591:                                               $current_disk_usage,$uname,$udom);
                   13592:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13593:                 || $state eq 'file_locked') {
1.661     raeburn  13594:                 $output .= $msg;
                   13595:                 next;
                   13596:             }
                   13597:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13598:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13599:             if ($state eq 'exists') {
                   13600:                 $output .= $msg;
                   13601:                 next;
                   13602:             }
                   13603:         }
                   13604:         # Check if extension is valid
                   13605:         if (($fname =~ /\.(\w+)$/) &&
                   13606:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13607:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13608:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13609:             next;
                   13610:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13611:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13612:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13613:             next;
                   13614:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13615:             $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  13616:             next;
                   13617:         }
                   13618:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13619:         my $subdir = $path;
                   13620:         $subdir =~ s{/+$}{};
1.661     raeburn  13621:         if ($context eq 'portfolio') {
1.984     raeburn  13622:             my $result;
                   13623:             if ($state eq 'existingfile') {
                   13624:                 $result=
                   13625:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13626:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13627:             } else {
1.984     raeburn  13628:                 $result=
                   13629:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13630:                                                     $dirpath.
1.1123    raeburn  13631:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13632:                 if ($result !~ m|^/uploaded/|) {
                   13633:                     $output .= '<span class="LC_error">'
                   13634:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13635:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13636:                                .'</span><br />';
                   13637:                     next;
                   13638:                 } else {
1.987     raeburn  13639:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13640:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13641:                 }
1.661     raeburn  13642:             }
1.1123    raeburn  13643:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13644:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13645:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13646:             my $result =
1.1126    raeburn  13647:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13648:             if ($result !~ m|^/uploaded/|) {
                   13649:                 $output .= '<span class="LC_error">'
                   13650:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13651:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13652:                            .'</span><br />';
                   13653:                     next;
                   13654:             } else {
                   13655:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13656:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13657:                 if ($context eq 'syllabus') {
                   13658:                     &Apache::lonnet::make_public_indefinitely($result);
                   13659:                 }
1.987     raeburn  13660:             }
1.661     raeburn  13661:         } else {
                   13662: # Save the file
                   13663:             my $target = $env{'form.embedded_item_'.$i};
                   13664:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13665:             my $dest = $fullpath.$fname;
                   13666:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13667:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13668:             my $count;
                   13669:             my $filepath = $dir_root;
1.1027    raeburn  13670:             foreach my $subdir (@parts) {
                   13671:                 $filepath .= "/$subdir";
                   13672:                 if (!-e $filepath) {
1.661     raeburn  13673:                     mkdir($filepath,0770);
                   13674:                 }
                   13675:             }
                   13676:             my $fh;
                   13677:             if (!open($fh,'>'.$dest)) {
                   13678:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13679:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13680:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13681:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13682:                            '</span><br />';
                   13683:             } else {
                   13684:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13685:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13686:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13687:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13688:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13689:                               '</span><br />';
                   13690:                 } else {
1.987     raeburn  13691:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13692:                                $url.'</span>').'<br />';
                   13693:                     unless ($context eq 'testbank') {
                   13694:                         $footer .= &mt('View embedded file: [_1]',
                   13695:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13696:                     }
                   13697:                 }
                   13698:                 close($fh);
                   13699:             }
                   13700:         }
                   13701:         if ($env{'form.embedded_ref_'.$i}) {
                   13702:             $pathchange{$i} = 1;
                   13703:         }
                   13704:     }
                   13705:     if ($output) {
                   13706:         $output = '<p>'.$output.'</p>';
                   13707:     }
                   13708:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13709:     $returnflag = 'ok';
1.1071    raeburn  13710:     my $numpathchgs = scalar(keys(%pathchange));
                   13711:     if ($numpathchgs > 0) {
1.987     raeburn  13712:         if ($context eq 'portfolio') {
                   13713:             $output .= '<p>'.&mt('or').'</p>';
                   13714:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13715:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13716:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13717:             $returnflag = 'modify_orightml';
                   13718:         }
                   13719:     }
1.1071    raeburn  13720:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13721: }
                   13722: 
                   13723: sub modify_html_form {
                   13724:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13725:     my $end = 0;
                   13726:     my $modifyform;
                   13727:     if ($context eq 'upload_embedded') {
                   13728:         return unless (ref($pathchange) eq 'HASH');
                   13729:         if ($env{'form.number_embedded_items'}) {
                   13730:             $end += $env{'form.number_embedded_items'};
                   13731:         }
                   13732:         if ($env{'form.number_pathchange_items'}) {
                   13733:             $end += $env{'form.number_pathchange_items'};
                   13734:         }
                   13735:         if ($end) {
                   13736:             for (my $i=0; $i<$end; $i++) {
                   13737:                 if ($i < $env{'form.number_embedded_items'}) {
                   13738:                     next unless($pathchange->{$i});
                   13739:                 }
                   13740:                 $modifyform .=
                   13741:                     &start_data_table_row().
                   13742:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13743:                     'checked="checked" /></td>'.
                   13744:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13745:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13746:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13747:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13748:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13749:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13750:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13751:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13752:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13753:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13754:                     &end_data_table_row();
1.1071    raeburn  13755:             }
1.987     raeburn  13756:         }
                   13757:     } else {
                   13758:         $modifyform = $pathchgtable;
                   13759:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13760:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13761:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13762:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13763:         }
                   13764:     }
                   13765:     if ($modifyform) {
1.1071    raeburn  13766:         if ($actionurl eq '/adm/dependencies') {
                   13767:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13768:         }
1.987     raeburn  13769:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13770:                '<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".
                   13771:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13772:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13773:                '</ol></p>'."\n".'<p>'.
                   13774:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13775:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13776:                &start_data_table()."\n".
                   13777:                &start_data_table_header_row().
                   13778:                '<th>'.&mt('Change?').'</th>'.
                   13779:                '<th>'.&mt('Current reference').'</th>'.
                   13780:                '<th>'.&mt('Required reference').'</th>'.
                   13781:                &end_data_table_header_row()."\n".
                   13782:                $modifyform.
                   13783:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13784:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13785:                '</form>'."\n";
                   13786:     }
                   13787:     return;
                   13788: }
                   13789: 
                   13790: sub modify_html_refs {
1.1123    raeburn  13791:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13792:     my $container;
                   13793:     if ($context eq 'portfolio') {
                   13794:         $container = $env{'form.container'};
                   13795:     } elsif ($context eq 'coursedoc') {
                   13796:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13797:     } elsif ($context eq 'manage_dependencies') {
                   13798:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13799:         $container = "/$container";
1.1123    raeburn  13800:     } elsif ($context eq 'syllabus') {
                   13801:         $container = $url;
1.987     raeburn  13802:     } else {
1.1027    raeburn  13803:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13804:     }
                   13805:     my (%allfiles,%codebase,$output,$content);
                   13806:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13807:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13808:         if (wantarray) {
                   13809:             return ('',0,0); 
                   13810:         } else {
                   13811:             return;
                   13812:         }
                   13813:     }
                   13814:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13815:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13816:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13817:             if (wantarray) {
                   13818:                 return ('',0,0);
                   13819:             } else {
                   13820:                 return;
                   13821:             }
                   13822:         } 
1.987     raeburn  13823:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13824:         if ($content eq '-1') {
                   13825:             if (wantarray) {
                   13826:                 return ('',0,0);
                   13827:             } else {
                   13828:                 return;
                   13829:             }
                   13830:         }
1.987     raeburn  13831:     } else {
1.1071    raeburn  13832:         unless ($container =~ /^\Q$dir_root\E/) {
                   13833:             if (wantarray) {
                   13834:                 return ('',0,0);
                   13835:             } else {
                   13836:                 return;
                   13837:             }
                   13838:         } 
1.1317    raeburn  13839:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13840:             $content = join('', <$fh>);
                   13841:             close($fh);
                   13842:         } else {
1.1071    raeburn  13843:             if (wantarray) {
                   13844:                 return ('',0,0);
                   13845:             } else {
                   13846:                 return;
                   13847:             }
1.987     raeburn  13848:         }
                   13849:     }
                   13850:     my ($count,$codebasecount) = (0,0);
                   13851:     my $mm = new File::MMagic;
                   13852:     my $mime_type = $mm->checktype_contents($content);
                   13853:     if ($mime_type eq 'text/html') {
                   13854:         my $parse_result = 
                   13855:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13856:                                                     \%codebase,\$content);
                   13857:         if ($parse_result eq 'ok') {
                   13858:             foreach my $i (@changes) {
                   13859:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13860:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13861:                 if ($allfiles{$ref}) {
                   13862:                     my $newname =  $orig;
                   13863:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13864:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13865:                     if ($attrib_regexp =~ /:/) {
                   13866:                         $attrib_regexp =~ s/\:/|/g;
                   13867:                     }
                   13868:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13869:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13870:                         $count += $numchg;
1.1123    raeburn  13871:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13872:                         delete($allfiles{$ref});
1.987     raeburn  13873:                     }
                   13874:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13875:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13876:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13877:                         $codebasecount ++;
                   13878:                     }
                   13879:                 }
                   13880:             }
1.1123    raeburn  13881:             my $skiprewrites;
1.987     raeburn  13882:             if ($count || $codebasecount) {
                   13883:                 my $saveresult;
1.1071    raeburn  13884:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13885:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13886:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13887:                     if ($url eq $container) {
                   13888:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13889:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13890:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13891:                                             $fname.'</span>').'</p>';
1.987     raeburn  13892:                     } else {
                   13893:                          $output = '<p class="LC_error">'.
                   13894:                                    &mt('Error: update failed for: [_1].',
                   13895:                                    '<span class="LC_filename">'.
                   13896:                                    $container.'</span>').'</p>';
                   13897:                     }
1.1123    raeburn  13898:                     if ($context eq 'syllabus') {
                   13899:                         unless ($saveresult eq 'ok') {
                   13900:                             $skiprewrites = 1;
                   13901:                         }
                   13902:                     }
1.987     raeburn  13903:                 } else {
1.1317    raeburn  13904:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13905:                         print $fh $content;
                   13906:                         close($fh);
                   13907:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13908:                                   $count,'<span class="LC_filename">'.
                   13909:                                   $container.'</span>').'</p>';
1.661     raeburn  13910:                     } else {
1.987     raeburn  13911:                          $output = '<p class="LC_error">'.
                   13912:                                    &mt('Error: could not update [_1].',
                   13913:                                    '<span class="LC_filename">'.
                   13914:                                    $container.'</span>').'</p>';
1.661     raeburn  13915:                     }
                   13916:                 }
                   13917:             }
1.1123    raeburn  13918:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13919:                 my ($actionurl,$state);
                   13920:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13921:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13922:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13923:                                               \%codebase,
                   13924:                                               {'context' => 'rewrites',
                   13925:                                                'ignore_remote_references' => 1,});
                   13926:                 if (ref($mapping) eq 'HASH') {
                   13927:                     my $rewrites = 0;
                   13928:                     foreach my $key (keys(%{$mapping})) {
                   13929:                         next if ($key =~ m{^https?://});
                   13930:                         my $ref = $mapping->{$key};
                   13931:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13932:                         my $attrib;
                   13933:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13934:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13935:                         }
                   13936:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13937:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13938:                             $rewrites += $numchg;
                   13939:                         }
                   13940:                     }
                   13941:                     if ($rewrites) {
                   13942:                         my $saveresult; 
                   13943:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13944:                         if ($url eq $container) {
                   13945:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13946:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13947:                                             $count,'<span class="LC_filename">'.
                   13948:                                             $fname.'</span>').'</p>';
                   13949:                         } else {
                   13950:                             $output .= '<p class="LC_error">'.
                   13951:                                        &mt('Error: could not update links in [_1].',
                   13952:                                        '<span class="LC_filename">'.
                   13953:                                        $container.'</span>').'</p>';
                   13954: 
                   13955:                         }
                   13956:                     }
                   13957:                 }
                   13958:             }
1.987     raeburn  13959:         } else {
                   13960:             &logthis('Failed to parse '.$container.
                   13961:                      ' to modify references: '.$parse_result);
1.661     raeburn  13962:         }
                   13963:     }
1.1071    raeburn  13964:     if (wantarray) {
                   13965:         return ($output,$count,$codebasecount);
                   13966:     } else {
                   13967:         return $output;
                   13968:     }
1.661     raeburn  13969: }
                   13970: 
                   13971: sub check_for_existing {
                   13972:     my ($path,$fname,$element) = @_;
                   13973:     my ($state,$msg);
                   13974:     if (-d $path.'/'.$fname) {
                   13975:         $state = 'exists';
                   13976:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13977:     } elsif (-e $path.'/'.$fname) {
                   13978:         $state = 'exists';
                   13979:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13980:     }
                   13981:     if ($state eq 'exists') {
                   13982:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13983:     }
                   13984:     return ($state,$msg);
                   13985: }
                   13986: 
                   13987: sub check_for_upload {
                   13988:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13989:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13990:     my $filesize = length($env{'form.'.$element});
                   13991:     if (!$filesize) {
                   13992:         my $msg = '<span class="LC_error">'.
                   13993:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13994:                       '<span class="LC_filename">'.$fname.'</span>',
                   13995:                       $filesize).'<br />'.
1.1007    raeburn  13996:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13997:                   '</span>';
                   13998:         return ('zero_bytes',$msg);
                   13999:     }
                   14000:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  14001:     my $getpropath = 1;
1.1021    raeburn  14002:     my ($dirlistref,$listerror) =
                   14003:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  14004:     my $found_file = 0;
                   14005:     my $locked_file = 0;
1.991     raeburn  14006:     my @lockers;
                   14007:     my $navmap;
                   14008:     if ($env{'request.course.id'}) {
                   14009:         $navmap = Apache::lonnavmaps::navmap->new();
                   14010:     }
1.1021    raeburn  14011:     if (ref($dirlistref) eq 'ARRAY') {
                   14012:         foreach my $line (@{$dirlistref}) {
                   14013:             my ($file_name,$rest)=split(/\&/,$line,2);
                   14014:             if ($file_name eq $fname){
                   14015:                 $file_name = $path.$file_name;
                   14016:                 if ($group ne '') {
                   14017:                     $file_name = $group.$file_name;
                   14018:                 }
                   14019:                 $found_file = 1;
                   14020:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   14021:                     foreach my $lock (@lockers) {
                   14022:                         if (ref($lock) eq 'ARRAY') {
                   14023:                             my ($symb,$crsid) = @{$lock};
                   14024:                             if ($crsid eq $env{'request.course.id'}) {
                   14025:                                 if (ref($navmap)) {
                   14026:                                     my $res = $navmap->getBySymb($symb);
                   14027:                                     foreach my $part (@{$res->parts()}) { 
                   14028:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   14029:                                         unless (($slot_status == $res->RESERVED) ||
                   14030:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   14031:                                             $locked_file = 1;
                   14032:                                         }
1.991     raeburn  14033:                                     }
1.1021    raeburn  14034:                                 } else {
                   14035:                                     $locked_file = 1;
1.991     raeburn  14036:                                 }
                   14037:                             } else {
                   14038:                                 $locked_file = 1;
                   14039:                             }
                   14040:                         }
1.1021    raeburn  14041:                    }
                   14042:                 } else {
                   14043:                     my @info = split(/\&/,$rest);
                   14044:                     my $currsize = $info[6]/1000;
                   14045:                     if ($currsize < $filesize) {
                   14046:                         my $extra = $filesize - $currsize;
                   14047:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   14048:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  14049:                                       &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   14050:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   14051:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   14052:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  14053:                             return ('will_exceed_quota',$msg);
                   14054:                         }
1.984     raeburn  14055:                     }
                   14056:                 }
1.661     raeburn  14057:             }
                   14058:         }
                   14059:     }
                   14060:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   14061:         my $msg = '<p class="LC_warning">'.
                   14062:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  14063:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  14064:         return ('will_exceed_quota',$msg);
                   14065:     } elsif ($found_file) {
                   14066:         if ($locked_file) {
1.1179    bisitz   14067:             my $msg = '<p class="LC_warning">';
1.661     raeburn  14068:             $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   14069:             $msg .= '</p>';
1.661     raeburn  14070:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   14071:             return ('file_locked',$msg);
                   14072:         } else {
1.1179    bisitz   14073:             my $msg = '<p class="LC_error">';
1.984     raeburn  14074:             $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   14075:             $msg .= '</p>';
1.984     raeburn  14076:             return ('existingfile',$msg);
1.661     raeburn  14077:         }
                   14078:     }
                   14079: }
                   14080: 
1.987     raeburn  14081: sub check_for_traversal {
                   14082:     my ($path,$url,$toplevel) = @_;
                   14083:     my @parts=split(/\//,$path);
                   14084:     my $cleanpath;
                   14085:     my $fullpath = $url;
                   14086:     for (my $i=0;$i<@parts;$i++) {
                   14087:         next if ($parts[$i] eq '.');
                   14088:         if ($parts[$i] eq '..') {
                   14089:             $fullpath =~ s{([^/]+/)$}{};
                   14090:         } else {
                   14091:             $fullpath .= $parts[$i].'/';
                   14092:         }
                   14093:     }
                   14094:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   14095:         $cleanpath = $1;
                   14096:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   14097:         my $curr_toprel = $1;
                   14098:         my @parts = split(/\//,$curr_toprel);
                   14099:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   14100:         my @urlparts = split(/\//,$url_toprel);
                   14101:         my $doubledots;
                   14102:         my $startdiff = -1;
                   14103:         for (my $i=0; $i<@urlparts; $i++) {
                   14104:             if ($startdiff == -1) {
                   14105:                 unless ($urlparts[$i] eq $parts[$i]) {
                   14106:                     $startdiff = $i;
                   14107:                     $doubledots .= '../';
                   14108:                 }
                   14109:             } else {
                   14110:                 $doubledots .= '../';
                   14111:             }
                   14112:         }
                   14113:         if ($startdiff > -1) {
                   14114:             $cleanpath = $doubledots;
                   14115:             for (my $i=$startdiff; $i<@parts; $i++) {
                   14116:                 $cleanpath .= $parts[$i].'/';
                   14117:             }
                   14118:         }
                   14119:     }
                   14120:     $cleanpath =~ s{(/)$}{};
                   14121:     return $cleanpath;
                   14122: }
1.31      albertel 14123: 
1.1053    raeburn  14124: sub is_archive_file {
                   14125:     my ($mimetype) = @_;
                   14126:     if (($mimetype eq 'application/octet-stream') ||
                   14127:         ($mimetype eq 'application/x-stuffit') ||
                   14128:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   14129:         return 1;
                   14130:     }
                   14131:     return;
                   14132: }
                   14133: 
                   14134: sub decompress_form {
1.1065    raeburn  14135:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  14136:     my %lt = &Apache::lonlocal::texthash (
                   14137:         this => 'This file is an archive file.',
1.1067    raeburn  14138:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  14139:         itsc => 'Its contents are as follows:',
1.1053    raeburn  14140:         youm => 'You may wish to extract its contents.',
                   14141:         extr => 'Extract contents',
1.1067    raeburn  14142:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   14143:         proa => 'Process automatically?',
1.1053    raeburn  14144:         yes  => 'Yes',
                   14145:         no   => 'No',
1.1067    raeburn  14146:         fold => 'Title for folder containing movie',
                   14147:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  14148:     );
1.1065    raeburn  14149:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  14150:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  14151:     my $info = &list_archive_contents($fileloc,\@paths);
                   14152:     if (@paths) {
                   14153:         foreach my $path (@paths) {
                   14154:             $path =~ s{^/}{};
1.1067    raeburn  14155:             if ($path =~ m{^([^/]+)/$}) {
                   14156:                 $topdir = $1;
                   14157:             }
1.1065    raeburn  14158:             if ($path =~ m{^([^/]+)/}) {
                   14159:                 $toplevel{$1} = $path;
                   14160:             } else {
                   14161:                 $toplevel{$path} = $path;
                   14162:             }
                   14163:         }
                   14164:     }
1.1067    raeburn  14165:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  14166:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  14167:                         "$topdir/media/",
                   14168:                         "$topdir/media/$topdir.mp4",
                   14169:                         "$topdir/media/FirstFrame.png",
                   14170:                         "$topdir/media/player.swf",
                   14171:                         "$topdir/media/swfobject.js",
                   14172:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  14173:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  14174:                          "$topdir/$topdir.mp4",
                   14175:                          "$topdir/$topdir\_config.xml",
                   14176:                          "$topdir/$topdir\_controller.swf",
                   14177:                          "$topdir/$topdir\_embed.css",
                   14178:                          "$topdir/$topdir\_First_Frame.png",
                   14179:                          "$topdir/$topdir\_player.html",
                   14180:                          "$topdir/$topdir\_Thumbnails.png",
                   14181:                          "$topdir/playerProductInstall.swf",
                   14182:                          "$topdir/scripts/",
                   14183:                          "$topdir/scripts/config_xml.js",
                   14184:                          "$topdir/scripts/handlebars.js",
                   14185:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14186:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14187:                          "$topdir/scripts/modernizr.js",
                   14188:                          "$topdir/scripts/player-min.js",
                   14189:                          "$topdir/scripts/swfobject.js",
                   14190:                          "$topdir/skins/",
                   14191:                          "$topdir/skins/configuration_express.xml",
                   14192:                          "$topdir/skins/express_show/",
                   14193:                          "$topdir/skins/express_show/player-min.css",
                   14194:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14195:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14196:                          "$topdir/$topdir.mp4",
                   14197:                          "$topdir/$topdir\_config.xml",
                   14198:                          "$topdir/$topdir\_controller.swf",
                   14199:                          "$topdir/$topdir\_embed.css",
                   14200:                          "$topdir/$topdir\_First_Frame.png",
                   14201:                          "$topdir/$topdir\_player.html",
                   14202:                          "$topdir/$topdir\_Thumbnails.png",
                   14203:                          "$topdir/playerProductInstall.swf",
                   14204:                          "$topdir/scripts/",
                   14205:                          "$topdir/scripts/config_xml.js",
                   14206:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14207:                          "$topdir/skins/",
                   14208:                          "$topdir/skins/configuration_express.xml",
                   14209:                          "$topdir/skins/express_show/",
                   14210:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14211:                          "$topdir/skins/express_show/spritesheet.png",
                   14212:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14213:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14214:         if (@diffs == 0) {
1.1164    raeburn  14215:             $is_camtasia = 6;
                   14216:         } else {
1.1197    raeburn  14217:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14218:             if (@diffs == 0) {
                   14219:                 $is_camtasia = 8;
1.1197    raeburn  14220:             } else {
                   14221:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14222:                 if (@diffs == 0) {
                   14223:                     $is_camtasia = 8;
                   14224:                 }
1.1164    raeburn  14225:             }
1.1067    raeburn  14226:         }
                   14227:     }
                   14228:     my $output;
                   14229:     if ($is_camtasia) {
                   14230:         $output = <<"ENDCAM";
                   14231: <script type="text/javascript" language="Javascript">
                   14232: // <![CDATA[
                   14233: 
                   14234: function camtasiaToggle() {
                   14235:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14236:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14237:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14238:                 document.getElementById('camtasia_titles').style.display='block';
                   14239:             } else {
                   14240:                 document.getElementById('camtasia_titles').style.display='none';
                   14241:             }
                   14242:         }
                   14243:     }
                   14244:     return;
                   14245: }
                   14246: 
                   14247: // ]]>
                   14248: </script>
                   14249: <p>$lt{'camt'}</p>
                   14250: ENDCAM
1.1065    raeburn  14251:     } else {
1.1067    raeburn  14252:         $output = '<p>'.$lt{'this'};
                   14253:         if ($info eq '') {
                   14254:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14255:         } else {
                   14256:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14257:                        '<div><pre>'.$info.'</pre></div>';
                   14258:         }
1.1065    raeburn  14259:     }
1.1067    raeburn  14260:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14261:     my $duplicates;
                   14262:     my $num = 0;
                   14263:     if (ref($dirlist) eq 'ARRAY') {
                   14264:         foreach my $item (@{$dirlist}) {
                   14265:             if (ref($item) eq 'ARRAY') {
                   14266:                 if (exists($toplevel{$item->[0]})) {
                   14267:                     $duplicates .= 
                   14268:                         &start_data_table_row().
                   14269:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14270:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14271:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14272:                         'value="1" />'.&mt('Yes').'</label>'.
                   14273:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14274:                         '<td>'.$item->[0].'</td>';
                   14275:                     if ($item->[2]) {
                   14276:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14277:                     } else {
                   14278:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14279:                     }
                   14280:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14281:                                    '<td>'.
                   14282:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14283:                                    '</td>'.
                   14284:                                    &end_data_table_row();
                   14285:                     $num ++;
                   14286:                 }
                   14287:             }
                   14288:         }
                   14289:     }
                   14290:     my $itemcount;
                   14291:     if (@paths > 0) {
                   14292:         $itemcount = scalar(@paths);
                   14293:     } else {
                   14294:         $itemcount = 1;
                   14295:     }
1.1067    raeburn  14296:     if ($is_camtasia) {
                   14297:         $output .= $lt{'auto'}.'<br />'.
                   14298:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14299:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14300:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14301:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14302:                    $lt{'no'}.'</label></span><br />'.
                   14303:                    '<div id="camtasia_titles" style="display:block">'.
                   14304:                    &Apache::lonhtmlcommon::start_pick_box().
                   14305:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14306:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14307:                    &Apache::lonhtmlcommon::row_closure().
                   14308:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14309:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14310:                    &Apache::lonhtmlcommon::row_closure(1).
                   14311:                    &Apache::lonhtmlcommon::end_pick_box().
                   14312:                    '</div>';
                   14313:     }
1.1065    raeburn  14314:     $output .= 
                   14315:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14316:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14317:         "\n";
1.1065    raeburn  14318:     if ($duplicates ne '') {
                   14319:         $output .= '<p><span class="LC_warning">'.
                   14320:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14321:                    &start_data_table().
                   14322:                    &start_data_table_header_row().
                   14323:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14324:                    '<th>'.&mt('Name').'</th>'.
                   14325:                    '<th>'.&mt('Type').'</th>'.
                   14326:                    '<th>'.&mt('Size').'</th>'.
                   14327:                    '<th>'.&mt('Last modified').'</th>'.
                   14328:                    &end_data_table_header_row().
                   14329:                    $duplicates.
                   14330:                    &end_data_table().
                   14331:                    '</p>';
                   14332:     }
1.1067    raeburn  14333:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14334:     if (ref($hiddenelements) eq 'HASH') {
                   14335:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14336:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14337:         }
                   14338:     }
                   14339:     $output .= <<"END";
1.1067    raeburn  14340: <br />
1.1053    raeburn  14341: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14342: </form>
                   14343: $noextract
                   14344: END
                   14345:     return $output;
                   14346: }
                   14347: 
1.1065    raeburn  14348: sub decompression_utility {
                   14349:     my ($program) = @_;
                   14350:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14351:     my $location;
                   14352:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14353:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14354:                          '/usr/sbin/') {
                   14355:             if (-x $dir.$program) {
                   14356:                 $location = $dir.$program;
                   14357:                 last;
                   14358:             }
                   14359:         }
                   14360:     }
                   14361:     return $location;
                   14362: }
                   14363: 
                   14364: sub list_archive_contents {
                   14365:     my ($file,$pathsref) = @_;
                   14366:     my (@cmd,$output);
                   14367:     my $needsregexp;
                   14368:     if ($file =~ /\.zip$/) {
                   14369:         @cmd = (&decompression_utility('unzip'),"-l");
                   14370:         $needsregexp = 1;
                   14371:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14372:              ($file =~ /\.tgz$/)) {
                   14373:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14374:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14375:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14376:     } elsif ($file =~ m|\.tar$|) {
                   14377:         @cmd = (&decompression_utility('tar'),"-tf");
                   14378:     }
                   14379:     if (@cmd) {
                   14380:         undef($!);
                   14381:         undef($@);
                   14382:         if (open(my $fh,"-|", @cmd, $file)) {
                   14383:             while (my $line = <$fh>) {
                   14384:                 $output .= $line;
                   14385:                 chomp($line);
                   14386:                 my $item;
                   14387:                 if ($needsregexp) {
                   14388:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14389:                 } else {
                   14390:                     $item = $line;
                   14391:                 }
                   14392:                 if ($item ne '') {
                   14393:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14394:                         push(@{$pathsref},$item);
                   14395:                     } 
                   14396:                 }
                   14397:             }
                   14398:             close($fh);
                   14399:         }
                   14400:     }
                   14401:     return $output;
                   14402: }
                   14403: 
1.1053    raeburn  14404: sub decompress_uploaded_file {
                   14405:     my ($file,$dir) = @_;
                   14406:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14407:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14408:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14409:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14410:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14411:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14412:     my $decompressed = $env{'cgi.decompressed'};
                   14413:     &Apache::lonnet::delenv('cgi.file');
                   14414:     &Apache::lonnet::delenv('cgi.dir');
                   14415:     &Apache::lonnet::delenv('cgi.decompressed');
                   14416:     return ($decompressed,$result);
                   14417: }
                   14418: 
1.1055    raeburn  14419: sub process_decompression {
                   14420:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14421:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14422:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14423:                &mt('Unexpected file path.').'</p>'."\n";
                   14424:     }
                   14425:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14426:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14427:                &mt('Unexpected course context.').'</p>'."\n";
                   14428:     }
1.1293    raeburn  14429:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14430:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14431:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14432:     }
1.1055    raeburn  14433:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14434:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14435:         $error = &mt('Filename not a supported archive file type.').
                   14436:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14437:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14438:     } else {
                   14439:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14440:         if ($docuhome eq 'no_host') {
                   14441:             $error = &mt('Could not determine home server for course.');
                   14442:         } else {
                   14443:             my @ids=&Apache::lonnet::current_machine_ids();
                   14444:             my $currdir = "$dir_root/$destination";
                   14445:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14446:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14447:                        "$dir_root/$destination";
                   14448:             } else {
                   14449:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14450:                        "$dir_root/$docudom/$docuname/$destination";
                   14451:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14452:                     $error = &mt('Archive file not found.');
                   14453:                 }
                   14454:             }
1.1065    raeburn  14455:             my (@to_overwrite,@to_skip);
                   14456:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14457:                 my $total = $env{'form.archive_overwrite_total'};
                   14458:                 for (my $i=0; $i<$total; $i++) {
                   14459:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14460:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14461:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14462:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14463:                     }
                   14464:                 }
                   14465:             }
                   14466:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14467:             my $numoverwrite = scalar(@to_overwrite);
                   14468:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14469:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14470:             } elsif ($dir eq '') {
1.1055    raeburn  14471:                 $error = &mt('Directory containing archive file unavailable.');
                   14472:             } elsif (!$error) {
1.1065    raeburn  14473:                 my ($decompressed,$display);
1.1292    raeburn  14474:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14475:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14476:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14477:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14478:                         ($decompressed,$display) = 
                   14479:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14480:                         foreach my $item (@to_skip) {
                   14481:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14482:                                 if (-f "$dir/$tempdir/$item") { 
                   14483:                                     unlink("$dir/$tempdir/$item");
                   14484:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14485:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14486:                                 }
                   14487:                             }
                   14488:                         }
                   14489:                         foreach my $item (@to_overwrite) {
                   14490:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14491:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14492:                                     if (-f "$dir/$item") {
                   14493:                                         unlink("$dir/$item");
                   14494:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14495:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14496:                                     }
                   14497:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14498:                                 }
1.1065    raeburn  14499:                             }
                   14500:                         }
1.1292    raeburn  14501:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14502:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14503:                         }
1.1065    raeburn  14504:                     }
                   14505:                 } else {
                   14506:                     ($decompressed,$display) = 
                   14507:                         &decompress_uploaded_file($file,$dir);
                   14508:                 }
1.1055    raeburn  14509:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14510:                     $output = '<p class="LC_info">'.
                   14511:                               &mt('Files extracted successfully from archive.').
                   14512:                               '</p>'."\n";
1.1055    raeburn  14513:                     my ($warning,$result,@contents);
                   14514:                     my ($newdirlistref,$newlisterror) =
                   14515:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14516:                                                  $docuname,1);
                   14517:                     my (%is_dir,%changes,@newitems);
                   14518:                     my $dirptr = 16384;
1.1065    raeburn  14519:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14520:                         foreach my $dir_line (@{$newdirlistref}) {
                   14521:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14522:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14523:                                 push(@newitems,$item);
                   14524:                                 if ($dirptr&$testdir) {
                   14525:                                     $is_dir{$item} = 1;
                   14526:                                 }
                   14527:                                 $changes{$item} = 1;
                   14528:                             }
                   14529:                         }
                   14530:                     }
                   14531:                     if (keys(%changes) > 0) {
                   14532:                         foreach my $item (sort(@newitems)) {
                   14533:                             if ($changes{$item}) {
                   14534:                                 push(@contents,$item);
                   14535:                             }
                   14536:                         }
                   14537:                     }
                   14538:                     if (@contents > 0) {
1.1067    raeburn  14539:                         my $wantform;
                   14540:                         unless ($env{'form.autoextract_camtasia'}) {
                   14541:                             $wantform = 1;
                   14542:                         }
1.1056    raeburn  14543:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14544:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14545:                                                                 $currdir,\%is_dir,
                   14546:                                                                 \%children,\%parent,
1.1056    raeburn  14547:                                                                 \@contents,\%dirorder,
                   14548:                                                                 \%titles,$wantform);
1.1055    raeburn  14549:                         if ($datatable ne '') {
                   14550:                             $output .= &archive_options_form('decompressed',$datatable,
                   14551:                                                              $count,$hiddenelem);
1.1065    raeburn  14552:                             my $startcount = 6;
1.1055    raeburn  14553:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14554:                                                            \%titles,\%children);
1.1055    raeburn  14555:                         }
1.1067    raeburn  14556:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14557:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14558:                             my %displayed;
                   14559:                             my $total = 1;
                   14560:                             $env{'form.archive_directory'} = [];
                   14561:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14562:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14563:                                 $path =~ s{/$}{};
                   14564:                                 my $item;
                   14565:                                 if ($path ne '') {
                   14566:                                     $item = "$path/$titles{$i}";
                   14567:                                 } else {
                   14568:                                     $item = $titles{$i};
                   14569:                                 }
                   14570:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14571:                                 if ($item eq $contents[0]) {
                   14572:                                     push(@{$env{'form.archive_directory'}},$i);
                   14573:                                     $env{'form.archive_'.$i} = 'display';
                   14574:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14575:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14576:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14577:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14578:                                     $env{'form.archive_'.$i} = 'display';
                   14579:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14580:                                     $displayed{'web'} = $i;
                   14581:                                 } else {
1.1164    raeburn  14582:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14583:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14584:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14585:                                         push(@{$env{'form.archive_directory'}},$i);
                   14586:                                     }
                   14587:                                     $env{'form.archive_'.$i} = 'dependency';
                   14588:                                 }
                   14589:                                 $total ++;
                   14590:                             }
                   14591:                             for (my $i=1; $i<$total; $i++) {
                   14592:                                 next if ($i == $displayed{'web'});
                   14593:                                 next if ($i == $displayed{'folder'});
                   14594:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14595:                             }
                   14596:                             $env{'form.phase'} = 'decompress_cleanup';
                   14597:                             $env{'form.archivedelete'} = 1;
                   14598:                             $env{'form.archive_count'} = $total-1;
                   14599:                             $output .=
                   14600:                                 &process_extracted_files('coursedocs',$docudom,
                   14601:                                                          $docuname,$destination,
                   14602:                                                          $dir_root,$hiddenelem);
                   14603:                         }
1.1055    raeburn  14604:                     } else {
                   14605:                         $warning = &mt('No new items extracted from archive file.');
                   14606:                     }
                   14607:                 } else {
                   14608:                     $output = $display;
                   14609:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14610:                 }
                   14611:             }
                   14612:         }
                   14613:     }
                   14614:     if ($error) {
                   14615:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14616:                    $error.'</p>'."\n";
                   14617:     }
                   14618:     if ($warning) {
                   14619:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14620:     }
                   14621:     return $output;
                   14622: }
                   14623: 
                   14624: sub get_extracted {
1.1056    raeburn  14625:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14626:         $titles,$wantform) = @_;
1.1055    raeburn  14627:     my $count = 0;
                   14628:     my $depth = 0;
                   14629:     my $datatable;
1.1056    raeburn  14630:     my @hierarchy;
1.1055    raeburn  14631:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14632:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14633:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14634:     foreach my $item (@{$contents}) {
                   14635:         $count ++;
1.1056    raeburn  14636:         @{$dirorder->{$count}} = @hierarchy;
                   14637:         $titles->{$count} = $item;
1.1055    raeburn  14638:         &archive_hierarchy($depth,$count,$parent,$children);
                   14639:         if ($wantform) {
                   14640:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14641:                                        $currdir,$depth,$count);
                   14642:         }
                   14643:         if ($is_dir->{$item}) {
                   14644:             $depth ++;
1.1056    raeburn  14645:             push(@hierarchy,$count);
                   14646:             $parent->{$depth} = $count;
1.1055    raeburn  14647:             $datatable .=
                   14648:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14649:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14650:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14651:             $depth --;
1.1056    raeburn  14652:             pop(@hierarchy);
1.1055    raeburn  14653:         }
                   14654:     }
                   14655:     return ($count,$datatable);
                   14656: }
                   14657: 
                   14658: sub recurse_extracted_archive {
1.1056    raeburn  14659:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14660:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14661:     my $result='';
1.1056    raeburn  14662:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14663:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14664:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14665:         return $result;
                   14666:     }
                   14667:     my $dirptr = 16384;
                   14668:     my ($newdirlistref,$newlisterror) =
                   14669:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14670:     if (ref($newdirlistref) eq 'ARRAY') {
                   14671:         foreach my $dir_line (@{$newdirlistref}) {
                   14672:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14673:             unless ($item =~ /^\.+$/) {
                   14674:                 $$count ++;
1.1056    raeburn  14675:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14676:                 $titles->{$$count} = $item;
1.1055    raeburn  14677:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14678: 
1.1055    raeburn  14679:                 my $is_dir;
                   14680:                 if ($dirptr&$testdir) {
                   14681:                     $is_dir = 1;
                   14682:                 }
                   14683:                 if ($wantform) {
                   14684:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14685:                 }
                   14686:                 if ($is_dir) {
                   14687:                     $$depth ++;
1.1056    raeburn  14688:                     push(@{$hierarchy},$$count);
                   14689:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14690:                     $result .=
                   14691:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14692:                                                    $docuname,$depth,$count,
1.1056    raeburn  14693:                                                    $hierarchy,$dirorder,$children,
                   14694:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14695:                     $$depth --;
1.1056    raeburn  14696:                     pop(@{$hierarchy});
1.1055    raeburn  14697:                 }
                   14698:             }
                   14699:         }
                   14700:     }
                   14701:     return $result;
                   14702: }
                   14703: 
                   14704: sub archive_hierarchy {
                   14705:     my ($depth,$count,$parent,$children) =@_;
                   14706:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14707:         if (exists($parent->{$depth})) {
                   14708:              $children->{$parent->{$depth}} .= $count.':';
                   14709:         }
                   14710:     }
                   14711:     return;
                   14712: }
                   14713: 
                   14714: sub archive_row {
                   14715:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14716:     my ($name) = ($item =~ m{([^/]+)$});
                   14717:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14718:                                        'display'    => 'Add as file',
1.1055    raeburn  14719:                                        'dependency' => 'Include as dependency',
                   14720:                                        'discard'    => 'Discard',
                   14721:                                       );
                   14722:     if ($is_dir) {
1.1059    raeburn  14723:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14724:     }
1.1056    raeburn  14725:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14726:     my $offset = 0;
1.1055    raeburn  14727:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14728:         $offset ++;
1.1065    raeburn  14729:         if ($action ne 'display') {
                   14730:             $offset ++;
                   14731:         }  
1.1055    raeburn  14732:         $output .= '<td><span class="LC_nobreak">'.
                   14733:                    '<label><input type="radio" name="archive_'.$count.
                   14734:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14735:         my $text = $choices{$action};
                   14736:         if ($is_dir) {
                   14737:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14738:             if ($action eq 'display') {
1.1059    raeburn  14739:                 $text = &mt('Add as folder');
1.1055    raeburn  14740:             }
1.1056    raeburn  14741:         } else {
                   14742:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14743: 
                   14744:         }
                   14745:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14746:         if ($action eq 'dependency') {
                   14747:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14748:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14749:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14750:                        '<option value=""></option>'."\n".
                   14751:                        '</select>'."\n".
                   14752:                        '</div>';
1.1059    raeburn  14753:         } elsif ($action eq 'display') {
                   14754:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14755:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14756:                        '</div>';
1.1055    raeburn  14757:         }
1.1056    raeburn  14758:         $output .= '</td>';
1.1055    raeburn  14759:     }
                   14760:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14761:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14762:     for (my $i=0; $i<$depth; $i++) {
                   14763:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14764:     }
                   14765:     if ($is_dir) {
                   14766:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14767:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14768:     } else {
                   14769:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14770:     }
                   14771:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14772:                &end_data_table_row();
                   14773:     return $output;
                   14774: }
                   14775: 
                   14776: sub archive_options_form {
1.1065    raeburn  14777:     my ($form,$display,$count,$hiddenelem) = @_;
                   14778:     my %lt = &Apache::lonlocal::texthash(
                   14779:                perm => 'Permanently remove archive file?',
                   14780:                hows => 'How should each extracted item be incorporated in the course?',
                   14781:                cont => 'Content actions for all',
                   14782:                addf => 'Add as folder/file',
                   14783:                incd => 'Include as dependency for a displayed file',
                   14784:                disc => 'Discard',
                   14785:                no   => 'No',
                   14786:                yes  => 'Yes',
                   14787:                save => 'Save',
                   14788:     );
                   14789:     my $output = <<"END";
                   14790: <form name="$form" method="post" action="">
                   14791: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14792: <label>
                   14793:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14794: </label>
                   14795: &nbsp;
                   14796: <label>
                   14797:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14798: </span>
                   14799: </p>
                   14800: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14801: <br />$lt{'hows'}
                   14802: <div class="LC_columnSection">
                   14803:   <fieldset>
                   14804:     <legend>$lt{'cont'}</legend>
                   14805:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14806:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14807:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14808:   </fieldset>
                   14809: </div>
                   14810: END
                   14811:     return $output.
1.1055    raeburn  14812:            &start_data_table()."\n".
1.1065    raeburn  14813:            $display."\n".
1.1055    raeburn  14814:            &end_data_table()."\n".
                   14815:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14816:            $hiddenelem.
1.1065    raeburn  14817:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14818:            '</form>';
                   14819: }
                   14820: 
                   14821: sub archive_javascript {
1.1056    raeburn  14822:     my ($startcount,$numitems,$titles,$children) = @_;
                   14823:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14824:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14825:     my $scripttag = <<START;
                   14826: <script type="text/javascript">
                   14827: // <![CDATA[
                   14828: 
                   14829: function checkAll(form,prefix) {
                   14830:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14831:     for (var i=0; i < form.elements.length; i++) {
                   14832:         var id = form.elements[i].id;
                   14833:         if ((id != '') && (id != undefined)) {
                   14834:             if (idstr.test(id)) {
                   14835:                 if (form.elements[i].type == 'radio') {
                   14836:                     form.elements[i].checked = true;
1.1056    raeburn  14837:                     var nostart = i-$startcount;
1.1059    raeburn  14838:                     var offset = nostart%7;
                   14839:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14840:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14841:                 }
                   14842:             }
                   14843:         }
                   14844:     }
                   14845: }
                   14846: 
                   14847: function propagateCheck(form,count) {
                   14848:     if (count > 0) {
1.1059    raeburn  14849:         var startelement = $startcount + ((count-1) * 7);
                   14850:         for (var j=1; j<6; j++) {
                   14851:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14852:                 var item = startelement + j; 
                   14853:                 if (form.elements[item].type == 'radio') {
                   14854:                     if (form.elements[item].checked) {
                   14855:                         containerCheck(form,count,j);
                   14856:                         break;
                   14857:                     }
1.1055    raeburn  14858:                 }
                   14859:             }
                   14860:         }
                   14861:     }
                   14862: }
                   14863: 
                   14864: numitems = $numitems
1.1056    raeburn  14865: var titles = new Array(numitems);
                   14866: var parents = new Array(numitems);
1.1055    raeburn  14867: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14868:     parents[i] = new Array;
1.1055    raeburn  14869: }
1.1059    raeburn  14870: var maintitle = '$maintitle';
1.1055    raeburn  14871: 
                   14872: START
                   14873: 
1.1056    raeburn  14874:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14875:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14876:         for (my $i=0; $i<@contents; $i ++) {
                   14877:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14878:         }
                   14879:     }
                   14880: 
1.1056    raeburn  14881:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14882:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14883:     }
                   14884: 
1.1055    raeburn  14885:     $scripttag .= <<END;
                   14886: 
                   14887: function containerCheck(form,count,offset) {
                   14888:     if (count > 0) {
1.1056    raeburn  14889:         dependencyCheck(form,count,offset);
1.1059    raeburn  14890:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14891:         form.elements[item].checked = true;
                   14892:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14893:             if (parents[count].length > 0) {
                   14894:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14895:                     containerCheck(form,parents[count][j],offset);
                   14896:                 }
                   14897:             }
                   14898:         }
                   14899:     }
                   14900: }
                   14901: 
                   14902: function dependencyCheck(form,count,offset) {
                   14903:     if (count > 0) {
1.1059    raeburn  14904:         var chosen = (offset+$startcount)+7*(count-1);
                   14905:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14906:         var currtype = form.elements[depitem].type;
                   14907:         if (form.elements[chosen].value == 'dependency') {
                   14908:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14909:             form.elements[depitem].options.length = 0;
                   14910:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14911:             for (var i=1; i<=numitems; i++) {
                   14912:                 if (i == count) {
                   14913:                     continue;
                   14914:                 }
1.1059    raeburn  14915:                 var startelement = $startcount + (i-1) * 7;
                   14916:                 for (var j=1; j<6; j++) {
                   14917:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14918:                         var item = startelement + j;
                   14919:                         if (form.elements[item].type == 'radio') {
                   14920:                             if (form.elements[item].checked) {
                   14921:                                 if (form.elements[item].value == 'display') {
                   14922:                                     var n = form.elements[depitem].options.length;
                   14923:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14924:                                 }
                   14925:                             }
                   14926:                         }
                   14927:                     }
                   14928:                 }
                   14929:             }
                   14930:         } else {
                   14931:             document.getElementById('arc_depon_'+count).style.display='none';
                   14932:             form.elements[depitem].options.length = 0;
                   14933:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14934:         }
1.1059    raeburn  14935:         titleCheck(form,count,offset);
1.1056    raeburn  14936:     }
                   14937: }
                   14938: 
                   14939: function propagateSelect(form,count,offset) {
                   14940:     if (count > 0) {
1.1065    raeburn  14941:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14942:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14943:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14944:             if (parents[count].length > 0) {
                   14945:                 for (var j=0; j<parents[count].length; j++) {
                   14946:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14947:                 }
                   14948:             }
                   14949:         }
                   14950:     }
                   14951: }
1.1056    raeburn  14952: 
                   14953: function containerSelect(form,count,offset,picked) {
                   14954:     if (count > 0) {
1.1065    raeburn  14955:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14956:         if (form.elements[item].type == 'radio') {
                   14957:             if (form.elements[item].value == 'dependency') {
                   14958:                 if (form.elements[item+1].type == 'select-one') {
                   14959:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14960:                         if (form.elements[item+1].options[i].value == picked) {
                   14961:                             form.elements[item+1].selectedIndex = i;
                   14962:                             break;
                   14963:                         }
                   14964:                     }
                   14965:                 }
                   14966:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14967:                     if (parents[count].length > 0) {
                   14968:                         for (var j=0; j<parents[count].length; j++) {
                   14969:                             containerSelect(form,parents[count][j],offset,picked);
                   14970:                         }
                   14971:                     }
                   14972:                 }
                   14973:             }
                   14974:         }
                   14975:     }
                   14976: }
                   14977: 
1.1059    raeburn  14978: function titleCheck(form,count,offset) {
                   14979:     if (count > 0) {
                   14980:         var chosen = (offset+$startcount)+7*(count-1);
                   14981:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14982:         var currtype = form.elements[depitem].type;
                   14983:         if (form.elements[chosen].value == 'display') {
                   14984:             document.getElementById('arc_title_'+count).style.display='block';
                   14985:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14986:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14987:             }
                   14988:         } else {
                   14989:             document.getElementById('arc_title_'+count).style.display='none';
                   14990:             if (currtype == 'text') { 
                   14991:                 document.getElementById('archive_title_'+count).value='';
                   14992:             }
                   14993:         }
                   14994:     }
                   14995:     return;
                   14996: }
                   14997: 
1.1055    raeburn  14998: // ]]>
                   14999: </script>
                   15000: END
                   15001:     return $scripttag;
                   15002: }
                   15003: 
                   15004: sub process_extracted_files {
1.1067    raeburn  15005:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  15006:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  15007:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  15008:     my @ids=&Apache::lonnet::current_machine_ids();
                   15009:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  15010:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  15011:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   15012:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   15013:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   15014:         $pathtocheck = "$dir_root/$destination";
                   15015:         $dir = $dir_root;
                   15016:         $ishome = 1;
                   15017:     } else {
                   15018:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   15019:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  15020:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  15021:     }
                   15022:     my $currdir = "$dir_root/$destination";
                   15023:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   15024:     if ($env{'form.folderpath'}) {
                   15025:         my @items = split('&',$env{'form.folderpath'});
                   15026:         $folders{'0'} = $items[-2];
1.1099    raeburn  15027:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   15028:             $containers{'0'}='page';
                   15029:         } else {  
                   15030:             $containers{'0'}='sequence';
                   15031:         }
1.1055    raeburn  15032:     }
                   15033:     my @archdirs = &get_env_multiple('form.archive_directory');
                   15034:     if ($numitems) {
                   15035:         for (my $i=1; $i<=$numitems; $i++) {
                   15036:             my $path = $env{'form.archive_content_'.$i};
                   15037:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   15038:                 my $item = $1;
                   15039:                 $toplevelitems{$item} = $i;
                   15040:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   15041:                     $is_dir{$item} = 1;
                   15042:                 }
                   15043:             }
                   15044:         }
                   15045:     }
1.1067    raeburn  15046:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  15047:     if (keys(%toplevelitems) > 0) {
                   15048:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  15049:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   15050:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  15051:     }
1.1066    raeburn  15052:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  15053:     if ($numitems) {
                   15054:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  15055:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  15056:             my $path = $env{'form.archive_content_'.$i};
                   15057:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15058:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   15059:                     if ($prefix ne '' && $path ne '') {
                   15060:                         if (-e $prefix.$path) {
1.1066    raeburn  15061:                             if ((@archdirs > 0) && 
                   15062:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   15063:                                 $todeletedir{$prefix.$path} = 1;
                   15064:                             } else {
                   15065:                                 $todelete{$prefix.$path} = 1;
                   15066:                             }
1.1055    raeburn  15067:                         }
                   15068:                     }
                   15069:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  15070:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  15071:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  15072:                     $docstitle = $env{'form.archive_title_'.$i};
                   15073:                     if ($docstitle eq '') {
                   15074:                         $docstitle = $title;
                   15075:                     }
1.1055    raeburn  15076:                     $outer = 0;
1.1056    raeburn  15077:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15078:                         if (@{$dirorder{$i}} > 0) {
                   15079:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  15080:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   15081:                                     $outer = $item;
                   15082:                                     last;
                   15083:                                 }
                   15084:                             }
                   15085:                         }
                   15086:                     }
                   15087:                     my ($errtext,$fatal) = 
                   15088:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   15089:                                                '/'.$folders{$outer}.'.'.
                   15090:                                                $containers{$outer});
                   15091:                     next if ($fatal);
                   15092:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   15093:                         if ($context eq 'coursedocs') {
1.1056    raeburn  15094:                             $mapinner{$i} = time;
1.1055    raeburn  15095:                             $folders{$i} = 'default_'.$mapinner{$i};
                   15096:                             $containers{$i} = 'sequence';
                   15097:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15098:                                       $folders{$i}.'.'.$containers{$i};
                   15099:                             my $newidx = &LONCAPA::map::getresidx();
                   15100:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  15101:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  15102:                             push(@LONCAPA::map::order,$newidx);
                   15103:                             my ($outtext,$errtext) =
                   15104:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15105:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  15106:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  15107:                             $newseqid{$i} = $newidx;
1.1067    raeburn  15108:                             unless ($errtext) {
1.1294    raeburn  15109:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   15110:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   15111:                                             '</li>'."\n";
1.1067    raeburn  15112:                             }
1.1055    raeburn  15113:                         }
                   15114:                     } else {
                   15115:                         if ($context eq 'coursedocs') {
                   15116:                             my $newidx=&LONCAPA::map::getresidx();
                   15117:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15118:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   15119:                                       $title;
1.1392    raeburn  15120:                             if (($outer !~ /\D/) &&
                   15121:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   15122:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  15123:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   15124:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   15125:                                 }
                   15126:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15127:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   15128:                                 }
                   15129:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15130:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   15131:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   15132:                                         unless ($ishome) {
                   15133:                                             my $fetch = "$newdest{$i}/$title";
                   15134:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   15135:                                             $prompttofetch{$fetch} = 1;
                   15136:                                         }
1.1292    raeburn  15137:                                     }
1.1067    raeburn  15138:                                 }
1.1294    raeburn  15139:                                 $LONCAPA::map::resources[$newidx]=
                   15140:                                     $docstitle.':'.$url.':false:normal:res';
                   15141:                                 push(@LONCAPA::map::order, $newidx);
                   15142:                                 my ($outtext,$errtext)=
                   15143:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15144:                                                             $docuname.'/'.$folders{$outer}.
                   15145:                                                             '.'.$containers{$outer},1,1);
                   15146:                                 unless ($errtext) {
                   15147:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   15148:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   15149:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   15150:                                                    '</li>'."\n";
                   15151:                                     }
1.1067    raeburn  15152:                                 }
1.1294    raeburn  15153:                             } else {
                   15154:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15155:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  15156:                             }
1.1055    raeburn  15157:                         }
                   15158:                     }
1.1086    raeburn  15159:                 }
                   15160:             } else {
1.1294    raeburn  15161:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15162:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  15163:             }
                   15164:         }
                   15165:         for (my $i=1; $i<=$numitems; $i++) {
                   15166:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   15167:             my $path = $env{'form.archive_content_'.$i};
                   15168:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15169:                 my ($title) = ($path =~ m{/([^/]+)$});
                   15170:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   15171:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   15172:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15173:                         my ($itemidx,$fullpath,$relpath);
                   15174:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   15175:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  15176:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  15177:                                 if ($dirorder{$i}->[$j] eq $container) {
                   15178:                                     $itemidx = $j;
1.1056    raeburn  15179:                                 }
                   15180:                             }
1.1086    raeburn  15181:                         }
                   15182:                         if ($itemidx eq '') {
                   15183:                             $itemidx =  0;
                   15184:                         } 
                   15185:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15186:                             if ($mapinner{$referrer{$i}}) {
                   15187:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15188:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15189:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15190:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15191:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15192:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15193:                                             if (!-e $fullpath) {
                   15194:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15195:                                             }
                   15196:                                         }
1.1086    raeburn  15197:                                     } else {
                   15198:                                         last;
1.1056    raeburn  15199:                                     }
1.1086    raeburn  15200:                                 }
                   15201:                             }
                   15202:                         } elsif ($newdest{$referrer{$i}}) {
                   15203:                             $fullpath = $newdest{$referrer{$i}};
                   15204:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15205:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15206:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15207:                                     last;
                   15208:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15209:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15210:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15211:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15212:                                         if (!-e $fullpath) {
                   15213:                                             mkdir($fullpath,0755);
1.1056    raeburn  15214:                                         }
                   15215:                                     }
1.1086    raeburn  15216:                                 } else {
                   15217:                                     last;
1.1056    raeburn  15218:                                 }
1.1055    raeburn  15219:                             }
                   15220:                         }
1.1086    raeburn  15221:                         if ($fullpath ne '') {
                   15222:                             if (-e "$prefix$path") {
1.1292    raeburn  15223:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15224:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15225:                                 }
1.1086    raeburn  15226:                             }
                   15227:                             if (-e "$fullpath/$title") {
                   15228:                                 my $showpath;
                   15229:                                 if ($relpath ne '') {
                   15230:                                     $showpath = "$relpath/$title";
                   15231:                                 } else {
                   15232:                                     $showpath = "/$title";
                   15233:                                 } 
1.1294    raeburn  15234:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15235:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15236:                                            '</li>'."\n";
1.1292    raeburn  15237:                                 unless ($ishome) {
                   15238:                                     my $fetch = "$fullpath/$title";
                   15239:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15240:                                     $prompttofetch{$fetch} = 1;
                   15241:                                 }
1.1086    raeburn  15242:                             }
                   15243:                         }
1.1055    raeburn  15244:                     }
1.1086    raeburn  15245:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15246:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15247:                                     &HTML::Entities::encode($path,'<>&"'),
                   15248:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15249:                                 '<br />';
1.1055    raeburn  15250:                 }
                   15251:             } else {
1.1294    raeburn  15252:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15253:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15254:             }
                   15255:         }
                   15256:         if (keys(%todelete)) {
                   15257:             foreach my $key (keys(%todelete)) {
                   15258:                 unlink($key);
1.1066    raeburn  15259:             }
                   15260:         }
                   15261:         if (keys(%todeletedir)) {
                   15262:             foreach my $key (keys(%todeletedir)) {
                   15263:                 rmdir($key);
                   15264:             }
                   15265:         }
                   15266:         foreach my $dir (sort(keys(%is_dir))) {
                   15267:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15268:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15269:             }
                   15270:         }
1.1067    raeburn  15271:         if ($result ne '') {
                   15272:             $output .= '<ul>'."\n".
                   15273:                        $result."\n".
                   15274:                        '</ul>';
                   15275:         }
                   15276:         unless ($ishome) {
                   15277:             my $replicationfail;
                   15278:             foreach my $item (keys(%prompttofetch)) {
                   15279:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15280:                 unless ($fetchresult eq 'ok') {
                   15281:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15282:                 }
                   15283:             }
                   15284:             if ($replicationfail) {
                   15285:                 $output .= '<p class="LC_error">'.
                   15286:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15287:                            $replicationfail.
                   15288:                            '</ul></p>';
                   15289:             }
                   15290:         }
1.1055    raeburn  15291:     } else {
                   15292:         $warning = &mt('No items found in archive.');
                   15293:     }
                   15294:     if ($error) {
                   15295:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15296:                    $error.'</p>'."\n";
                   15297:     }
                   15298:     if ($warning) {
                   15299:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15300:     }
                   15301:     return $output;
                   15302: }
                   15303: 
1.1066    raeburn  15304: sub cleanup_empty_dirs {
                   15305:     my ($path) = @_;
                   15306:     if (($path ne '') && (-d $path)) {
                   15307:         if (opendir(my $dirh,$path)) {
                   15308:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15309:             my $numitems = 0;
                   15310:             foreach my $item (@dircontents) {
                   15311:                 if (-d "$path/$item") {
1.1111    raeburn  15312:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15313:                     if (-e "$path/$item") {
                   15314:                         $numitems ++;
                   15315:                     }
                   15316:                 } else {
                   15317:                     $numitems ++;
                   15318:                 }
                   15319:             }
                   15320:             if ($numitems == 0) {
                   15321:                 rmdir($path);
                   15322:             }
                   15323:             closedir($dirh);
                   15324:         }
                   15325:     }
                   15326:     return;
                   15327: }
                   15328: 
1.41      ng       15329: =pod
1.45      matthew  15330: 
1.1162    raeburn  15331: =item * &get_folder_hierarchy()
1.1068    raeburn  15332: 
                   15333: Provides hierarchy of names of folders/sub-folders containing the current
                   15334: item,
                   15335: 
                   15336: Inputs: 3
                   15337:      - $navmap - navmaps object
                   15338: 
                   15339:      - $map - url for map (either the trigger itself, or map containing
                   15340:                            the resource, which is the trigger).
                   15341: 
                   15342:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15343: 
                   15344: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15345: 
                   15346: =cut
                   15347: 
                   15348: sub get_folder_hierarchy {
                   15349:     my ($navmap,$map,$showitem) = @_;
                   15350:     my @pathitems;
                   15351:     if (ref($navmap)) {
                   15352:         my $mapres = $navmap->getResourceByUrl($map);
                   15353:         if (ref($mapres)) {
                   15354:             my $pcslist = $mapres->map_hierarchy();
                   15355:             if ($pcslist ne '') {
                   15356:                 my @pcs = split(/,/,$pcslist);
                   15357:                 foreach my $pc (@pcs) {
                   15358:                     if ($pc == 1) {
1.1129    raeburn  15359:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15360:                     } else {
                   15361:                         my $res = $navmap->getByMapPc($pc);
                   15362:                         if (ref($res)) {
                   15363:                             my $title = $res->compTitle();
                   15364:                             $title =~ s/\W+/_/g;
                   15365:                             if ($title ne '') {
                   15366:                                 push(@pathitems,$title);
                   15367:                             }
                   15368:                         }
                   15369:                     }
                   15370:                 }
                   15371:             }
1.1071    raeburn  15372:             if ($showitem) {
                   15373:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15374:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15375:                 } else {
                   15376:                     my $maptitle = $mapres->compTitle();
                   15377:                     $maptitle =~ s/\W+/_/g;
                   15378:                     if ($maptitle ne '') {
                   15379:                         push(@pathitems,$maptitle);
                   15380:                     }
1.1068    raeburn  15381:                 }
                   15382:             }
                   15383:         }
                   15384:     }
                   15385:     return @pathitems;
                   15386: }
                   15387: 
                   15388: =pod
                   15389: 
1.1015    raeburn  15390: =item * &get_turnedin_filepath()
                   15391: 
                   15392: Determines path in a user's portfolio file for storage of files uploaded
                   15393: to a specific essayresponse or dropbox item.
                   15394: 
                   15395: Inputs: 3 required + 1 optional.
                   15396: $symb is symb for resource, $uname and $udom are for current user (required).
                   15397: $caller is optional (can be "submission", if routine is called when storing
                   15398: an upoaded file when "Submit Answer" button was pressed).
                   15399: 
                   15400: Returns array containing $path and $multiresp. 
                   15401: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15402: than one file upload item.  Callers of routine should append partid as a 
                   15403: subdirectory to $path in cases where $multiresp is 1.
                   15404: 
                   15405: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15406: 
                   15407: =cut
                   15408: 
                   15409: sub get_turnedin_filepath {
                   15410:     my ($symb,$uname,$udom,$caller) = @_;
                   15411:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15412:     my $turnindir;
                   15413:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15414:     $turnindir = $userhash{'turnindir'};
                   15415:     my ($path,$multiresp);
                   15416:     if ($turnindir eq '') {
                   15417:         if ($caller eq 'submission') {
                   15418:             $turnindir = &mt('turned in');
                   15419:             $turnindir =~ s/\W+/_/g;
                   15420:             my %newhash = (
                   15421:                             'turnindir' => $turnindir,
                   15422:                           );
                   15423:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15424:         }
                   15425:     }
                   15426:     if ($turnindir ne '') {
                   15427:         $path = '/'.$turnindir.'/';
                   15428:         my ($multipart,$turnin,@pathitems);
                   15429:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15430:         if (defined($navmap)) {
                   15431:             my $mapres = $navmap->getResourceByUrl($map);
                   15432:             if (ref($mapres)) {
                   15433:                 my $pcslist = $mapres->map_hierarchy();
                   15434:                 if ($pcslist ne '') {
                   15435:                     foreach my $pc (split(/,/,$pcslist)) {
                   15436:                         my $res = $navmap->getByMapPc($pc);
                   15437:                         if (ref($res)) {
                   15438:                             my $title = $res->compTitle();
                   15439:                             $title =~ s/\W+/_/g;
                   15440:                             if ($title ne '') {
1.1149    raeburn  15441:                                 if (($pc > 1) && (length($title) > 12)) {
                   15442:                                     $title = substr($title,0,12);
                   15443:                                 }
1.1015    raeburn  15444:                                 push(@pathitems,$title);
                   15445:                             }
                   15446:                         }
                   15447:                     }
                   15448:                 }
                   15449:                 my $maptitle = $mapres->compTitle();
                   15450:                 $maptitle =~ s/\W+/_/g;
                   15451:                 if ($maptitle ne '') {
1.1149    raeburn  15452:                     if (length($maptitle) > 12) {
                   15453:                         $maptitle = substr($maptitle,0,12);
                   15454:                     }
1.1015    raeburn  15455:                     push(@pathitems,$maptitle);
                   15456:                 }
                   15457:                 unless ($env{'request.state'} eq 'construct') {
                   15458:                     my $res = $navmap->getBySymb($symb);
                   15459:                     if (ref($res)) {
                   15460:                         my $partlist = $res->parts();
                   15461:                         my $totaluploads = 0;
                   15462:                         if (ref($partlist) eq 'ARRAY') {
                   15463:                             foreach my $part (@{$partlist}) {
                   15464:                                 my @types = $res->responseType($part);
                   15465:                                 my @ids = $res->responseIds($part);
                   15466:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15467:                                     if ($types[$i] eq 'essay') {
                   15468:                                         my $partid = $part.'_'.$ids[$i];
                   15469:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15470:                                             $totaluploads ++;
                   15471:                                         }
                   15472:                                     }
                   15473:                                 }
                   15474:                             }
                   15475:                             if ($totaluploads > 1) {
                   15476:                                 $multiresp = 1;
                   15477:                             }
                   15478:                         }
                   15479:                     }
                   15480:                 }
                   15481:             } else {
                   15482:                 return;
                   15483:             }
                   15484:         } else {
                   15485:             return;
                   15486:         }
                   15487:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15488:         $restitle =~ s/\W+/_/g;
                   15489:         if ($restitle eq '') {
                   15490:             $restitle = ($resurl =~ m{/[^/]+$});
                   15491:             if ($restitle eq '') {
                   15492:                 $restitle = time;
                   15493:             }
                   15494:         }
1.1149    raeburn  15495:         if (length($restitle) > 12) {
                   15496:             $restitle = substr($restitle,0,12);
                   15497:         }
1.1015    raeburn  15498:         push(@pathitems,$restitle);
                   15499:         $path .= join('/',@pathitems);
                   15500:     }
                   15501:     return ($path,$multiresp);
                   15502: }
                   15503: 
                   15504: =pod
                   15505: 
1.464     albertel 15506: =back
1.41      ng       15507: 
1.112     bowersj2 15508: =head1 CSV Upload/Handling functions
1.38      albertel 15509: 
1.41      ng       15510: =over 4
                   15511: 
1.648     raeburn  15512: =item * &upfile_store($r)
1.41      ng       15513: 
                   15514: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15515: needs $env{'form.upfile'}
1.41      ng       15516: returns $datatoken to be put into hidden field
                   15517: 
                   15518: =cut
1.31      albertel 15519: 
                   15520: sub upfile_store {
                   15521:     my $r=shift;
1.258     albertel 15522:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15523:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15524:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15525:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15526: 
1.1299    raeburn  15527:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15528:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15529:                                      time.'_'.$$);
                   15530:     return if ($datatoken eq '');
                   15531: 
1.31      albertel 15532:     {
1.158     raeburn  15533:         my $datafile = $r->dir_config('lonDaemons').
                   15534:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15535:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15536:             print $fh $env{'form.upfile'};
1.158     raeburn  15537:             close($fh);
                   15538:         }
1.31      albertel 15539:     }
                   15540:     return $datatoken;
                   15541: }
                   15542: 
1.56      matthew  15543: =pod
                   15544: 
1.1290    raeburn  15545: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15546: 
                   15547: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15548: $datatoken is the name to assign to the temporary file.
1.258     albertel 15549: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15550: 
                   15551: =cut
1.31      albertel 15552: 
                   15553: sub load_tmp_file {
1.1290    raeburn  15554:     my ($r,$datatoken) = @_;
                   15555:     return if ($datatoken eq '');
1.31      albertel 15556:     my @studentdata=();
                   15557:     {
1.158     raeburn  15558:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15559:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15560:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15561:             @studentdata=<$fh>;
                   15562:             close($fh);
                   15563:         }
1.31      albertel 15564:     }
1.258     albertel 15565:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15566: }
                   15567: 
1.1290    raeburn  15568: sub valid_datatoken {
                   15569:     my ($datatoken) = @_;
1.1325    raeburn  15570:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15571:         return $datatoken;
                   15572:     }
                   15573:     return;
                   15574: }
                   15575: 
1.56      matthew  15576: =pod
                   15577: 
1.648     raeburn  15578: =item * &upfile_record_sep()
1.41      ng       15579: 
                   15580: Separate uploaded file into records
                   15581: returns array of records,
1.258     albertel 15582: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15583: 
                   15584: =cut
1.31      albertel 15585: 
                   15586: sub upfile_record_sep {
1.258     albertel 15587:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15588:     } else {
1.248     albertel 15589: 	my @records;
1.258     albertel 15590: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15591: 	    if ($line=~/^\s*$/) { next; }
                   15592: 	    push(@records,$line);
                   15593: 	}
                   15594: 	return @records;
1.31      albertel 15595:     }
                   15596: }
                   15597: 
1.56      matthew  15598: =pod
                   15599: 
1.648     raeburn  15600: =item * &record_sep($record)
1.41      ng       15601: 
1.258     albertel 15602: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15603: 
                   15604: =cut
                   15605: 
1.263     www      15606: sub takeleft {
                   15607:     my $index=shift;
                   15608:     return substr('0000'.$index,-4,4);
                   15609: }
                   15610: 
1.31      albertel 15611: sub record_sep {
                   15612:     my $record=shift;
                   15613:     my %components=();
1.258     albertel 15614:     if ($env{'form.upfiletype'} eq 'xml') {
                   15615:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15616:         my $i=0;
1.356     albertel 15617:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15618:             $field=~s/^(\"|\')//;
                   15619:             $field=~s/(\"|\')$//;
1.263     www      15620:             $components{&takeleft($i)}=$field;
1.31      albertel 15621:             $i++;
                   15622:         }
1.258     albertel 15623:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15624:         my $i=0;
1.356     albertel 15625:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15626:             $field=~s/^(\"|\')//;
                   15627:             $field=~s/(\"|\')$//;
1.263     www      15628:             $components{&takeleft($i)}=$field;
1.31      albertel 15629:             $i++;
                   15630:         }
                   15631:     } else {
1.561     www      15632:         my $separator=',';
1.480     banghart 15633:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15634:             $separator=';';
1.480     banghart 15635:         }
1.31      albertel 15636:         my $i=0;
1.561     www      15637: # the character we are looking for to indicate the end of a quote or a record 
                   15638:         my $looking_for=$separator;
                   15639: # do not add the characters to the fields
                   15640:         my $ignore=0;
                   15641: # we just encountered a separator (or the beginning of the record)
                   15642:         my $just_found_separator=1;
                   15643: # store the field we are working on here
                   15644:         my $field='';
                   15645: # work our way through all characters in record
                   15646:         foreach my $character ($record=~/(.)/g) {
                   15647:             if ($character eq $looking_for) {
                   15648:                if ($character ne $separator) {
                   15649: # Found the end of a quote, again looking for separator
                   15650:                   $looking_for=$separator;
                   15651:                   $ignore=1;
                   15652:                } else {
                   15653: # Found a separator, store away what we got
                   15654:                   $components{&takeleft($i)}=$field;
                   15655: 	          $i++;
                   15656:                   $just_found_separator=1;
                   15657:                   $ignore=0;
                   15658:                   $field='';
                   15659:                }
                   15660:                next;
                   15661:             }
                   15662: # single or double quotation marks after a separator indicate beginning of a quote
                   15663: # we are now looking for the end of the quote and need to ignore separators
                   15664:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15665:                $looking_for=$character;
                   15666:                next;
                   15667:             }
                   15668: # ignore would be true after we reached the end of a quote
                   15669:             if ($ignore) { next; }
                   15670:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15671:             $field.=$character;
                   15672:             $just_found_separator=0; 
1.31      albertel 15673:         }
1.561     www      15674: # catch the very last entry, since we never encountered the separator
                   15675:         $components{&takeleft($i)}=$field;
1.31      albertel 15676:     }
                   15677:     return %components;
                   15678: }
                   15679: 
1.144     matthew  15680: ######################################################
                   15681: ######################################################
                   15682: 
1.56      matthew  15683: =pod
                   15684: 
1.648     raeburn  15685: =item * &upfile_select_html()
1.41      ng       15686: 
1.144     matthew  15687: Return HTML code to select a file from the users machine and specify 
                   15688: the file type.
1.41      ng       15689: 
                   15690: =cut
                   15691: 
1.144     matthew  15692: ######################################################
                   15693: ######################################################
1.31      albertel 15694: sub upfile_select_html {
1.144     matthew  15695:     my %Types = (
                   15696:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15697:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15698:                  space => &mt('Space separated'),
                   15699:                  tab   => &mt('Tabulator separated'),
                   15700: #                 xml   => &mt('HTML/XML'),
                   15701:                  );
1.1473  ! raeburn  15702:     my $Str = '<input type="file" name="upfile" id="upfile" size="50" />'.
        !          15703:         '<br /><label>'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15704:     foreach my $type (sort(keys(%Types))) {
                   15705:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15706:     }
1.1473  ! raeburn  15707:     $Str .= "</select></label>\n";
1.144     matthew  15708:     return $Str;
1.31      albertel 15709: }
                   15710: 
1.301     albertel 15711: sub get_samples {
                   15712:     my ($records,$toget) = @_;
                   15713:     my @samples=({});
                   15714:     my $got=0;
                   15715:     foreach my $rec (@$records) {
                   15716: 	my %temp = &record_sep($rec);
                   15717: 	if (! grep(/\S/, values(%temp))) { next; }
                   15718: 	if (%temp) {
                   15719: 	    $samples[$got]=\%temp;
                   15720: 	    $got++;
                   15721: 	    if ($got == $toget) { last; }
                   15722: 	}
                   15723:     }
                   15724:     return \@samples;
                   15725: }
                   15726: 
1.144     matthew  15727: ######################################################
                   15728: ######################################################
                   15729: 
1.56      matthew  15730: =pod
                   15731: 
1.648     raeburn  15732: =item * &csv_print_samples($r,$records)
1.41      ng       15733: 
                   15734: Prints a table of sample values from each column uploaded $r is an
                   15735: Apache Request ref, $records is an arrayref from
                   15736: &Apache::loncommon::upfile_record_sep
                   15737: 
                   15738: =cut
                   15739: 
1.144     matthew  15740: ######################################################
                   15741: ######################################################
1.31      albertel 15742: sub csv_print_samples {
                   15743:     my ($r,$records) = @_;
1.662     bisitz   15744:     my $samples = &get_samples($records,5);
1.301     albertel 15745: 
1.594     raeburn  15746:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15747:               &start_data_table_header_row());
1.356     albertel 15748:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15749:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15750:     $r->print(&end_data_table_header_row());
1.301     albertel 15751:     foreach my $hash (@$samples) {
1.594     raeburn  15752: 	$r->print(&start_data_table_row());
1.356     albertel 15753: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15754: 	    $r->print('<td>');
1.356     albertel 15755: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15756: 	    $r->print('</td>');
                   15757: 	}
1.594     raeburn  15758: 	$r->print(&end_data_table_row());
1.31      albertel 15759:     }
1.594     raeburn  15760:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15761: }
                   15762: 
1.144     matthew  15763: ######################################################
                   15764: ######################################################
                   15765: 
1.56      matthew  15766: =pod
                   15767: 
1.648     raeburn  15768: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15769: 
                   15770: Prints a table to create associations between values and table columns.
1.144     matthew  15771: 
1.41      ng       15772: $r is an Apache Request ref,
                   15773: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15774: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15775: 
                   15776: =cut
                   15777: 
1.144     matthew  15778: ######################################################
                   15779: ######################################################
1.31      albertel 15780: sub csv_print_select_table {
                   15781:     my ($r,$records,$d) = @_;
1.301     albertel 15782:     my $i=0;
                   15783:     my $samples = &get_samples($records,1);
1.144     matthew  15784:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15785: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15786:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15787:               '<th>'.&mt('Column').'</th>'.
                   15788:               &end_data_table_header_row()."\n");
1.356     albertel 15789:     foreach my $array_ref (@$d) {
                   15790: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.1473  ! raeburn  15791: 	$r->print(&start_data_table_row().'<td><label for="f'.$i.'">'.$display.'</label></td>');
1.31      albertel 15792: 
1.1473  ! raeburn  15793: 	$r->print('<td><select name="f'.$i.'" id="f'.$i.'"'.
1.32      matthew  15794: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15795: 	$r->print('<option value="none"></option>');
1.356     albertel 15796: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15797: 	    $r->print('<option value="'.$sample.'"'.
                   15798:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15799:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15800: 	}
1.594     raeburn  15801: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15802: 	$i++;
                   15803:     }
1.594     raeburn  15804:     $r->print(&end_data_table());
1.31      albertel 15805:     $i--;
                   15806:     return $i;
                   15807: }
1.56      matthew  15808: 
1.144     matthew  15809: ######################################################
                   15810: ######################################################
                   15811: 
1.56      matthew  15812: =pod
1.31      albertel 15813: 
1.648     raeburn  15814: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15815: 
                   15816: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15817: 
                   15818: $r is an Apache Request ref,
                   15819: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15820: $d is an array of 2 element arrays (internal name, displayed name)
                   15821: 
                   15822: =cut
                   15823: 
1.144     matthew  15824: ######################################################
                   15825: ######################################################
1.31      albertel 15826: sub csv_samples_select_table {
                   15827:     my ($r,$records,$d) = @_;
                   15828:     my $i=0;
1.144     matthew  15829:     #
1.662     bisitz   15830:     my $max_samples = 5;
                   15831:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15832:     $r->print(&start_data_table().
                   15833:               &start_data_table_header_row().'<th>'.
                   15834:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15835:               &end_data_table_header_row());
1.301     albertel 15836: 
                   15837:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.1473  ! raeburn  15838:         my $num = $i+1;
        !          15839:         my $labeltext = &HTML::Entities::encode(&mt('Field for data in column [_1]',$num));
1.594     raeburn  15840: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.1473  ! raeburn  15841: 		  ' onchange="javascript:flip(this.form,'.$i.');" aria-label="'.$labeltext.'">');
1.301     albertel 15842: 	foreach my $option (@$d) {
                   15843: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15844: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15845:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15846:                       $display.'</option>');
1.31      albertel 15847: 	}
                   15848: 	$r->print('</select></td><td>');
1.662     bisitz   15849: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15850: 	    if (defined($samples->[$line]{$key})) { 
                   15851: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15852: 	    }
                   15853: 	}
1.594     raeburn  15854: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15855: 	$i++;
                   15856:     }
1.594     raeburn  15857:     $r->print(&end_data_table());
1.31      albertel 15858:     $i--;
                   15859:     return($i);
1.115     matthew  15860: }
                   15861: 
1.144     matthew  15862: ######################################################
                   15863: ######################################################
                   15864: 
1.115     matthew  15865: =pod
                   15866: 
1.648     raeburn  15867: =item * &clean_excel_name($name)
1.115     matthew  15868: 
                   15869: Returns a replacement for $name which does not contain any illegal characters.
                   15870: 
                   15871: =cut
                   15872: 
1.144     matthew  15873: ######################################################
                   15874: ######################################################
1.115     matthew  15875: sub clean_excel_name {
                   15876:     my ($name) = @_;
                   15877:     $name =~ s/[:\*\?\/\\]//g;
                   15878:     if (length($name) > 31) {
                   15879:         $name = substr($name,0,31);
                   15880:     }
                   15881:     return $name;
1.25      albertel 15882: }
1.84      albertel 15883: 
1.85      albertel 15884: =pod
                   15885: 
1.648     raeburn  15886: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15887: 
                   15888: Returns either 1 or undef
                   15889: 
                   15890: 1 if the part is to be hidden, undef if it is to be shown
                   15891: 
                   15892: Arguments are:
                   15893: 
                   15894: $id the id of the part to be checked
                   15895: $symb, optional the symb of the resource to check
                   15896: $udom, optional the domain of the user to check for
                   15897: $uname, optional the username of the user to check for
                   15898: 
                   15899: =cut
1.84      albertel 15900: 
                   15901: sub check_if_partid_hidden {
                   15902:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15903:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15904: 					 $symb,$udom,$uname);
1.141     albertel 15905:     my $truth=1;
                   15906:     #if the string starts with !, then the list is the list to show not hide
                   15907:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15908:     my @hiddenlist=split(/,/,$hiddenparts);
                   15909:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15910: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15911:     }
1.141     albertel 15912:     return !$truth;
1.84      albertel 15913: }
1.127     matthew  15914: 
1.138     matthew  15915: 
                   15916: ############################################################
                   15917: ############################################################
                   15918: 
                   15919: =pod
                   15920: 
1.157     matthew  15921: =back 
                   15922: 
1.138     matthew  15923: =head1 cgi-bin script and graphing routines
                   15924: 
1.157     matthew  15925: =over 4
                   15926: 
1.648     raeburn  15927: =item * &get_cgi_id()
1.138     matthew  15928: 
                   15929: Inputs: none
                   15930: 
                   15931: Returns an id which can be used to pass environment variables
                   15932: to various cgi-bin scripts.  These environment variables will
                   15933: be removed from the users environment after a given time by
                   15934: the routine &Apache::lonnet::transfer_profile_to_env.
                   15935: 
                   15936: =cut
                   15937: 
                   15938: ############################################################
                   15939: ############################################################
1.152     albertel 15940: my $uniq=0;
1.136     matthew  15941: sub get_cgi_id {
1.154     albertel 15942:     $uniq=($uniq+1)%100000;
1.280     albertel 15943:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15944: }
                   15945: 
1.127     matthew  15946: ############################################################
                   15947: ############################################################
                   15948: 
                   15949: =pod
                   15950: 
1.648     raeburn  15951: =item * &DrawBarGraph()
1.127     matthew  15952: 
1.138     matthew  15953: Facilitates the plotting of data in a (stacked) bar graph.
                   15954: Puts plot definition data into the users environment in order for 
                   15955: graph.png to plot it.  Returns an <img> tag for the plot.
                   15956: The bars on the plot are labeled '1','2',...,'n'.
                   15957: 
                   15958: Inputs:
                   15959: 
                   15960: =over 4
                   15961: 
                   15962: =item $Title: string, the title of the plot
                   15963: 
                   15964: =item $xlabel: string, text describing the X-axis of the plot
                   15965: 
                   15966: =item $ylabel: string, text describing the Y-axis of the plot
                   15967: 
                   15968: =item $Max: scalar, the maximum Y value to use in the plot
                   15969: If $Max is < any data point, the graph will not be rendered.
                   15970: 
1.140     matthew  15971: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15972: they are plotted.  If undefined, default values will be used.
                   15973: 
1.178     matthew  15974: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15975: 
1.138     matthew  15976: =item @Values: An array of array references.  Each array reference holds data
                   15977: to be plotted in a stacked bar chart.
                   15978: 
1.239     matthew  15979: =item If the final element of @Values is a hash reference the key/value
                   15980: pairs will be added to the graph definition.
                   15981: 
1.138     matthew  15982: =back
                   15983: 
                   15984: Returns:
                   15985: 
                   15986: An <img> tag which references graph.png and the appropriate identifying
                   15987: information for the plot.
                   15988: 
1.127     matthew  15989: =cut
                   15990: 
                   15991: ############################################################
                   15992: ############################################################
1.134     matthew  15993: sub DrawBarGraph {
1.178     matthew  15994:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15995:     #
                   15996:     if (! defined($colors)) {
                   15997:         $colors = ['#33ff00', 
                   15998:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15999:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   16000:                   ]; 
                   16001:     }
1.228     matthew  16002:     my $extra_settings = {};
                   16003:     if (ref($Values[-1]) eq 'HASH') {
                   16004:         $extra_settings = pop(@Values);
                   16005:     }
1.127     matthew  16006:     #
1.136     matthew  16007:     my $identifier = &get_cgi_id();
                   16008:     my $id = 'cgi.'.$identifier;        
1.129     matthew  16009:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  16010:         return '';
                   16011:     }
1.225     matthew  16012:     #
                   16013:     my @Labels;
                   16014:     if (defined($labels)) {
                   16015:         @Labels = @$labels;
                   16016:     } else {
                   16017:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  16018:             push(@Labels,$i+1);
1.225     matthew  16019:         }
                   16020:     }
                   16021:     #
1.129     matthew  16022:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  16023:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  16024:     my %ValuesHash;
                   16025:     my $NumSets=1;
                   16026:     foreach my $array (@Values) {
                   16027:         next if (! ref($array));
1.136     matthew  16028:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  16029:             join(',',@$array);
1.129     matthew  16030:     }
1.127     matthew  16031:     #
1.136     matthew  16032:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  16033:     if ($NumBars < 3) {
                   16034:         $width = 120+$NumBars*32;
1.220     matthew  16035:         $xskip = 1;
1.225     matthew  16036:         $bar_width = 30;
                   16037:     } elsif ($NumBars < 5) {
                   16038:         $width = 120+$NumBars*20;
                   16039:         $xskip = 1;
                   16040:         $bar_width = 20;
1.220     matthew  16041:     } elsif ($NumBars < 10) {
1.136     matthew  16042:         $width = 120+$NumBars*15;
                   16043:         $xskip = 1;
                   16044:         $bar_width = 15;
                   16045:     } elsif ($NumBars <= 25) {
                   16046:         $width = 120+$NumBars*11;
                   16047:         $xskip = 5;
                   16048:         $bar_width = 8;
                   16049:     } elsif ($NumBars <= 50) {
                   16050:         $width = 120+$NumBars*8;
                   16051:         $xskip = 5;
                   16052:         $bar_width = 4;
                   16053:     } else {
                   16054:         $width = 120+$NumBars*8;
                   16055:         $xskip = 5;
                   16056:         $bar_width = 4;
                   16057:     }
                   16058:     #
1.137     matthew  16059:     $Max = 1 if ($Max < 1);
                   16060:     if ( int($Max) < $Max ) {
                   16061:         $Max++;
                   16062:         $Max = int($Max);
                   16063:     }
1.127     matthew  16064:     $Title  = '' if (! defined($Title));
                   16065:     $xlabel = '' if (! defined($xlabel));
                   16066:     $ylabel = '' if (! defined($ylabel));
1.369     www      16067:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   16068:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   16069:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  16070:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  16071:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   16072:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   16073:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   16074:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16075:     $ValuesHash{$id.'.height'}   = $height;
                   16076:     $ValuesHash{$id.'.width'}    = $width;
                   16077:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   16078:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   16079:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  16080:     #
1.228     matthew  16081:     # Deal with other parameters
                   16082:     while (my ($key,$value) = each(%$extra_settings)) {
                   16083:         $ValuesHash{$id.'.'.$key} = $value;
                   16084:     }
                   16085:     #
1.646     raeburn  16086:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  16087:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16088: }
                   16089: 
                   16090: ############################################################
                   16091: ############################################################
                   16092: 
                   16093: =pod
                   16094: 
1.648     raeburn  16095: =item * &DrawXYGraph()
1.137     matthew  16096: 
1.138     matthew  16097: Facilitates the plotting of data in an XY graph.
                   16098: Puts plot definition data into the users environment in order for 
                   16099: graph.png to plot it.  Returns an <img> tag for the plot.
                   16100: 
                   16101: Inputs:
                   16102: 
                   16103: =over 4
                   16104: 
                   16105: =item $Title: string, the title of the plot
                   16106: 
                   16107: =item $xlabel: string, text describing the X-axis of the plot
                   16108: 
                   16109: =item $ylabel: string, text describing the Y-axis of the plot
                   16110: 
                   16111: =item $Max: scalar, the maximum Y value to use in the plot
                   16112: If $Max is < any data point, the graph will not be rendered.
                   16113: 
                   16114: =item $colors: Array ref containing the hex color codes for the data to be 
                   16115: plotted in.  If undefined, default values will be used.
                   16116: 
                   16117: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16118: 
                   16119: =item $Ydata: Array ref containing Array refs.  
1.185     www      16120: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  16121: 
                   16122: =item %Values: hash indicating or overriding any default values which are 
                   16123: passed to graph.png.  
                   16124: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16125: 
                   16126: =back
                   16127: 
                   16128: Returns:
                   16129: 
                   16130: An <img> tag which references graph.png and the appropriate identifying
                   16131: information for the plot.
                   16132: 
1.137     matthew  16133: =cut
                   16134: 
                   16135: ############################################################
                   16136: ############################################################
                   16137: sub DrawXYGraph {
                   16138:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   16139:     #
                   16140:     # Create the identifier for the graph
                   16141:     my $identifier = &get_cgi_id();
                   16142:     my $id = 'cgi.'.$identifier;
                   16143:     #
                   16144:     $Title  = '' if (! defined($Title));
                   16145:     $xlabel = '' if (! defined($xlabel));
                   16146:     $ylabel = '' if (! defined($ylabel));
                   16147:     my %ValuesHash = 
                   16148:         (
1.369     www      16149:          $id.'.title'  => &escape($Title),
                   16150:          $id.'.xlabel' => &escape($xlabel),
                   16151:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  16152:          $id.'.y_max_value'=> $Max,
                   16153:          $id.'.labels'     => join(',',@$Xlabels),
                   16154:          $id.'.PlotType'   => 'XY',
                   16155:          );
                   16156:     #
                   16157:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16158:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16159:     }
                   16160:     #
                   16161:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   16162:         return '';
                   16163:     }
                   16164:     my $NumSets=1;
1.138     matthew  16165:     foreach my $array (@{$Ydata}){
1.137     matthew  16166:         next if (! ref($array));
                   16167:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   16168:     }
1.138     matthew  16169:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  16170:     #
                   16171:     # Deal with other parameters
                   16172:     while (my ($key,$value) = each(%Values)) {
                   16173:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  16174:     }
                   16175:     #
1.646     raeburn  16176:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  16177:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16178: }
                   16179: 
                   16180: ############################################################
                   16181: ############################################################
                   16182: 
                   16183: =pod
                   16184: 
1.648     raeburn  16185: =item * &DrawXYYGraph()
1.138     matthew  16186: 
                   16187: Facilitates the plotting of data in an XY graph with two Y axes.
                   16188: Puts plot definition data into the users environment in order for 
                   16189: graph.png to plot it.  Returns an <img> tag for the plot.
                   16190: 
                   16191: Inputs:
                   16192: 
                   16193: =over 4
                   16194: 
                   16195: =item $Title: string, the title of the plot
                   16196: 
                   16197: =item $xlabel: string, text describing the X-axis of the plot
                   16198: 
                   16199: =item $ylabel: string, text describing the Y-axis of the plot
                   16200: 
                   16201: =item $colors: Array ref containing the hex color codes for the data to be 
                   16202: plotted in.  If undefined, default values will be used.
                   16203: 
                   16204: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16205: 
                   16206: =item $Ydata1: The first data set
                   16207: 
                   16208: =item $Min1: The minimum value of the left Y-axis
                   16209: 
                   16210: =item $Max1: The maximum value of the left Y-axis
                   16211: 
                   16212: =item $Ydata2: The second data set
                   16213: 
                   16214: =item $Min2: The minimum value of the right Y-axis
                   16215: 
                   16216: =item $Max2: The maximum value of the left Y-axis
                   16217: 
                   16218: =item %Values: hash indicating or overriding any default values which are 
                   16219: passed to graph.png.  
                   16220: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16221: 
                   16222: =back
                   16223: 
                   16224: Returns:
                   16225: 
                   16226: An <img> tag which references graph.png and the appropriate identifying
                   16227: information for the plot.
1.136     matthew  16228: 
                   16229: =cut
                   16230: 
                   16231: ############################################################
                   16232: ############################################################
1.137     matthew  16233: sub DrawXYYGraph {
                   16234:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16235:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16236:     #
                   16237:     # Create the identifier for the graph
                   16238:     my $identifier = &get_cgi_id();
                   16239:     my $id = 'cgi.'.$identifier;
                   16240:     #
                   16241:     $Title  = '' if (! defined($Title));
                   16242:     $xlabel = '' if (! defined($xlabel));
                   16243:     $ylabel = '' if (! defined($ylabel));
                   16244:     my %ValuesHash = 
                   16245:         (
1.369     www      16246:          $id.'.title'  => &escape($Title),
                   16247:          $id.'.xlabel' => &escape($xlabel),
                   16248:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16249:          $id.'.labels' => join(',',@$Xlabels),
                   16250:          $id.'.PlotType' => 'XY',
                   16251:          $id.'.NumSets' => 2,
1.137     matthew  16252:          $id.'.two_axes' => 1,
                   16253:          $id.'.y1_max_value' => $Max1,
                   16254:          $id.'.y1_min_value' => $Min1,
                   16255:          $id.'.y2_max_value' => $Max2,
                   16256:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16257:          );
                   16258:     #
1.137     matthew  16259:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16260:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16261:     }
                   16262:     #
                   16263:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16264:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16265:         return '';
                   16266:     }
                   16267:     my $NumSets=1;
1.137     matthew  16268:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16269:         next if (! ref($array));
                   16270:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16271:     }
                   16272:     #
                   16273:     # Deal with other parameters
                   16274:     while (my ($key,$value) = each(%Values)) {
                   16275:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16276:     }
                   16277:     #
1.646     raeburn  16278:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16279:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16280: }
                   16281: 
                   16282: ############################################################
                   16283: ############################################################
                   16284: 
                   16285: =pod
                   16286: 
1.157     matthew  16287: =back 
                   16288: 
1.139     matthew  16289: =head1 Statistics helper routines?  
                   16290: 
                   16291: Bad place for them but what the hell.
                   16292: 
1.157     matthew  16293: =over 4
                   16294: 
1.648     raeburn  16295: =item * &chartlink()
1.139     matthew  16296: 
                   16297: Returns a link to the chart for a specific student.  
                   16298: 
                   16299: Inputs:
                   16300: 
                   16301: =over 4
                   16302: 
                   16303: =item $linktext: The text of the link
                   16304: 
                   16305: =item $sname: The students username
                   16306: 
                   16307: =item $sdomain: The students domain
                   16308: 
                   16309: =back
                   16310: 
1.157     matthew  16311: =back
                   16312: 
1.139     matthew  16313: =cut
                   16314: 
                   16315: ############################################################
                   16316: ############################################################
                   16317: sub chartlink {
                   16318:     my ($linktext, $sname, $sdomain) = @_;
                   16319:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16320:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16321:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16322:        '">'.$linktext.'</a>';
1.153     matthew  16323: }
                   16324: 
                   16325: #######################################################
                   16326: #######################################################
                   16327: 
                   16328: =pod
                   16329: 
                   16330: =head1 Course Environment Routines
1.157     matthew  16331: 
                   16332: =over 4
1.153     matthew  16333: 
1.648     raeburn  16334: =item * &restore_course_settings()
1.153     matthew  16335: 
1.648     raeburn  16336: =item * &store_course_settings()
1.153     matthew  16337: 
                   16338: Restores/Store indicated form parameters from the course environment.
                   16339: Will not overwrite existing values of the form parameters.
                   16340: 
                   16341: Inputs: 
                   16342: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16343: 
                   16344: a hash ref describing the data to be stored.  For example:
                   16345:    
                   16346: %Save_Parameters = ('Status' => 'scalar',
                   16347:     'chartoutputmode' => 'scalar',
                   16348:     'chartoutputdata' => 'scalar',
                   16349:     'Section' => 'array',
1.373     raeburn  16350:     'Group' => 'array',
1.153     matthew  16351:     'StudentData' => 'array',
                   16352:     'Maps' => 'array');
                   16353: 
                   16354: Returns: both routines return nothing
                   16355: 
1.631     raeburn  16356: =back
                   16357: 
1.153     matthew  16358: =cut
                   16359: 
                   16360: #######################################################
                   16361: #######################################################
                   16362: sub store_course_settings {
1.496     albertel 16363:     return &store_settings($env{'request.course.id'},@_);
                   16364: }
                   16365: 
                   16366: sub store_settings {
1.153     matthew  16367:     # save to the environment
                   16368:     # appenv the same items, just to be safe
1.300     albertel 16369:     my $udom  = $env{'user.domain'};
                   16370:     my $uname = $env{'user.name'};
1.496     albertel 16371:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16372:     my %SaveHash;
                   16373:     my %AppHash;
                   16374:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16375:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16376:         my $envname = 'environment.'.$basename;
1.258     albertel 16377:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16378:             # Save this value away
                   16379:             if ($type eq 'scalar' &&
1.258     albertel 16380:                 (! exists($env{$envname}) || 
                   16381:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16382:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16383:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16384:             } elsif ($type eq 'array') {
                   16385:                 my $stored_form;
1.258     albertel 16386:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16387:                     $stored_form = join(',',
                   16388:                                         map {
1.369     www      16389:                                             &escape($_);
1.258     albertel 16390:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16391:                 } else {
                   16392:                     $stored_form = 
1.369     www      16393:                         &escape($env{'form.'.$setting});
1.153     matthew  16394:                 }
                   16395:                 # Determine if the array contents are the same.
1.258     albertel 16396:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16397:                     $SaveHash{$basename} = $stored_form;
                   16398:                     $AppHash{$envname}   = $stored_form;
                   16399:                 }
                   16400:             }
                   16401:         }
                   16402:     }
                   16403:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16404:                                           $udom,$uname);
1.153     matthew  16405:     if ($put_result !~ /^(ok|delayed)/) {
                   16406:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16407:                                  'got error:'.$put_result);
                   16408:     }
                   16409:     # Make sure these settings stick around in this session, too
1.646     raeburn  16410:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16411:     return;
                   16412: }
                   16413: 
                   16414: sub restore_course_settings {
1.499     albertel 16415:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16416: }
                   16417: 
                   16418: sub restore_settings {
                   16419:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16420:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16421:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16422:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16423:             '.'.$setting;
1.258     albertel 16424:         if (exists($env{$envname})) {
1.153     matthew  16425:             if ($type eq 'scalar') {
1.258     albertel 16426:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16427:             } elsif ($type eq 'array') {
1.258     albertel 16428:                 $env{'form.'.$setting} = [ 
1.153     matthew  16429:                                            map { 
1.369     www      16430:                                                &unescape($_); 
1.258     albertel 16431:                                            } split(',',$env{$envname})
1.153     matthew  16432:                                            ];
                   16433:             }
                   16434:         }
                   16435:     }
1.127     matthew  16436: }
                   16437: 
1.618     raeburn  16438: #######################################################
                   16439: #######################################################
                   16440: 
                   16441: =pod
                   16442: 
                   16443: =head1 Domain E-mail Routines  
                   16444: 
                   16445: =over 4
                   16446: 
1.648     raeburn  16447: =item * &build_recipient_list()
1.618     raeburn  16448: 
1.1144    raeburn  16449: Build recipient lists for following types of e-mail:
1.766     raeburn  16450: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16451: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16452: module change checking, student/employee ID conflict checks, as
                   16453: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16454: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16455: 
                   16456: Inputs:
1.619     raeburn  16457: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16458: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16459: requestsmail, updatesmail, or idconflictsmail).
                   16460: 
1.619     raeburn  16461: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16462: 
1.619     raeburn  16463: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16464: i.e., predates configuration by DC via domainprefs.pm
                   16465: 
                   16466: $requname username of requester (if mailing type is helpdeskmail)
                   16467: 
                   16468: $requdom domain of requester (if mailing type is helpdeskmail)
                   16469: 
                   16470: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16471: 
1.618     raeburn  16472: 
1.655     raeburn  16473: Returns: comma separated list of addresses to which to send e-mail.
                   16474: 
                   16475: =back
1.618     raeburn  16476: 
                   16477: =cut
                   16478: 
                   16479: ############################################################
                   16480: ############################################################
                   16481: sub build_recipient_list {
1.1297    raeburn  16482:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16483:     my @recipients;
1.1270    raeburn  16484:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16485:     my %domconfig =
1.1270    raeburn  16486:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16487:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16488:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16489:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16490:                 my @contacts = ('adminemail','supportemail');
                   16491:                 foreach my $item (@contacts) {
                   16492:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16493:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16494:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16495:                             push(@recipients,$addr);
                   16496:                         }
1.619     raeburn  16497:                     }
1.1270    raeburn  16498:                 }
                   16499:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16500:                 if ($mailing eq 'helpdeskmail') {
                   16501:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16502:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16503:                         my @ok_bccs;
                   16504:                         foreach my $bcc (@bccs) {
                   16505:                             $bcc =~ s/^\s+//g;
                   16506:                             $bcc =~ s/\s+$//g;
                   16507:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16508:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16509:                                     push(@ok_bccs,$bcc);
                   16510:                                 }
                   16511:                             }
                   16512:                         }
                   16513:                         if (@ok_bccs > 0) {
                   16514:                             $allbcc = join(', ',@ok_bccs);
                   16515:                         }
                   16516:                     }
                   16517:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16518:                 }
                   16519:             }
1.766     raeburn  16520:         } elsif ($origmail ne '') {
1.1270    raeburn  16521:             $lastresort = $origmail;
1.618     raeburn  16522:         }
1.1297    raeburn  16523:         if ($mailing eq 'helpdeskmail') {
                   16524:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16525:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16526:                 my ($inststatus,$inststatus_checked);
                   16527:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16528:                     ($env{'user.domain'} ne 'public')) {
                   16529:                     $inststatus_checked = 1;
                   16530:                     $inststatus = $env{'environment.inststatus'};
                   16531:                 }
                   16532:                 unless ($inststatus_checked) {
                   16533:                     if (($requname ne '') && ($requdom ne '')) {
                   16534:                         if (($requname =~ /^$match_username$/) &&
                   16535:                             ($requdom =~ /^$match_domain$/) &&
                   16536:                             (&Apache::lonnet::domain($requdom))) {
                   16537:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16538:                                                                       $requdom);
                   16539:                             unless ($requhome eq 'no_host') {
                   16540:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16541:                                 $inststatus = $userenv{'inststatus'};
                   16542:                                 $inststatus_checked = 1;
                   16543:                             }
                   16544:                         }
                   16545:                     }
                   16546:                 }
                   16547:                 unless ($inststatus_checked) {
                   16548:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16549:                         my %srch = (srchby     => 'email',
                   16550:                                     srchdomain => $defdom,
                   16551:                                     srchterm   => $reqemail,
                   16552:                                     srchtype   => 'exact');
                   16553:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16554:                         foreach my $uname (keys(%srch_results)) {
                   16555:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16556:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16557:                                 $inststatus_checked = 1;
                   16558:                                 last;
                   16559:                             }
                   16560:                         }
                   16561:                         unless ($inststatus_checked) {
                   16562:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16563:                             if ($dirsrchres eq 'ok') {
                   16564:                                 foreach my $uname (keys(%srch_results)) {
                   16565:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16566:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16567:                                         $inststatus_checked = 1;
                   16568:                                         last;
                   16569:                                     }
                   16570:                                 }
                   16571:                             }
                   16572:                         }
                   16573:                     }
                   16574:                 }
                   16575:                 if ($inststatus ne '') {
                   16576:                     foreach my $status (split(/\:/,$inststatus)) {
                   16577:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16578:                             my @contacts = ('adminemail','supportemail');
                   16579:                             foreach my $item (@contacts) {
                   16580:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16581:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16582:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16583:                                         push(@recipients,$addr);
                   16584:                                     }
                   16585:                                 }
                   16586:                             }
                   16587:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16588:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16589:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16590:                                 my @ok_bccs;
                   16591:                                 foreach my $bcc (@bccs) {
                   16592:                                     $bcc =~ s/^\s+//g;
                   16593:                                     $bcc =~ s/\s+$//g;
                   16594:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16595:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16596:                                             push(@ok_bccs,$bcc);
                   16597:                                         }
                   16598:                                     }
                   16599:                                 }
                   16600:                                 if (@ok_bccs > 0) {
                   16601:                                     $allbcc = join(', ',@ok_bccs);
                   16602:                                 }
                   16603:                             }
                   16604:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16605:                             last;
                   16606:                         }
                   16607:                     }
                   16608:                 }
                   16609:             }
                   16610:         }
1.619     raeburn  16611:     } elsif ($origmail ne '') {
1.1270    raeburn  16612:         $lastresort = $origmail;
                   16613:     }
1.1297    raeburn  16614:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16615:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16616:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16617:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16618:             my %what = (
                   16619:                           perlvar => 1,
                   16620:                        );
                   16621:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16622:             if ($primary) {
                   16623:                 my $gotaddr;
                   16624:                 my ($result,$returnhash) =
                   16625:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16626:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16627:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16628:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16629:                         $gotaddr = 1;
                   16630:                     }
                   16631:                 }
                   16632:                 unless ($gotaddr) {
                   16633:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16634:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16635:                     unless ($uintdom eq $intdom) {
                   16636:                         my %domconfig =
                   16637:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16638:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16639:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16640:                                 my @contacts = ('adminemail','supportemail');
                   16641:                                 foreach my $item (@contacts) {
                   16642:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16643:                                         my $addr = $domconfig{'contacts'}{$item};
                   16644:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16645:                                             push(@recipients,$addr);
                   16646:                                         }
                   16647:                                     }
                   16648:                                 }
                   16649:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16650:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16651:                                 }
                   16652:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16653:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16654:                                     my @ok_bccs;
                   16655:                                     foreach my $bcc (@bccs) {
                   16656:                                         $bcc =~ s/^\s+//g;
                   16657:                                         $bcc =~ s/\s+$//g;
                   16658:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16659:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16660:                                                 push(@ok_bccs,$bcc);
                   16661:                                             }
                   16662:                                         }
                   16663:                                     }
                   16664:                                     if (@ok_bccs > 0) {
                   16665:                                         $allbcc = join(', ',@ok_bccs);
                   16666:                                     }
                   16667:                                 }
                   16668:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16669:                             }
                   16670:                         }
                   16671:                     }
                   16672:                 }
                   16673:             }
                   16674:         }
1.618     raeburn  16675:     }
1.688     raeburn  16676:     if (defined($defmail)) {
                   16677:         if ($defmail ne '') {
                   16678:             push(@recipients,$defmail);
                   16679:         }
1.618     raeburn  16680:     }
                   16681:     if ($otheremails) {
1.619     raeburn  16682:         my @others;
                   16683:         if ($otheremails =~ /,/) {
                   16684:             @others = split(/,/,$otheremails);
1.618     raeburn  16685:         } else {
1.619     raeburn  16686:             push(@others,$otheremails);
                   16687:         }
                   16688:         foreach my $addr (@others) {
                   16689:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16690:                 push(@recipients,$addr);
                   16691:             }
1.618     raeburn  16692:         }
                   16693:     }
1.1298    raeburn  16694:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16695:         if ((!@recipients) && ($lastresort ne '')) {
                   16696:             push(@recipients,$lastresort);
                   16697:         }
                   16698:     } elsif ($lastresort ne '') {
                   16699:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16700:             push(@recipients,$lastresort);
                   16701:         }
                   16702:     }
1.1271    raeburn  16703:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16704:     if (wantarray) {
                   16705:         return ($recipientlist,$allbcc,$addtext);
                   16706:     } else {
                   16707:         return $recipientlist;
                   16708:     }
1.618     raeburn  16709: }
                   16710: 
1.127     matthew  16711: ############################################################
                   16712: ############################################################
1.154     albertel 16713: 
1.655     raeburn  16714: =pod
                   16715: 
1.1224    musolffc 16716: =over 4
                   16717: 
1.1223    musolffc 16718: =item * &mime_email()
                   16719: 
                   16720: Sends an email with a possible attachment
                   16721: 
                   16722: Inputs:
                   16723: 
                   16724: =over 4
                   16725: 
                   16726: from -              Sender's email address
                   16727: 
1.1343    raeburn  16728: replyto -           Reply-To email address
                   16729: 
1.1223    musolffc 16730: to -                Email address of recipient
                   16731: 
                   16732: subject -           Subject of email
                   16733: 
                   16734: body -              Body of email
                   16735: 
                   16736: cc_string -         Carbon copy email address
                   16737: 
                   16738: bcc -               Blind carbon copy email address
                   16739: 
                   16740: attachment_path -   Path of file to be attached
                   16741: 
                   16742: file_name -         Name of file to be attached
                   16743: 
                   16744: attachment_text -   The body of an attachment of type "TEXT"
                   16745: 
                   16746: =back
                   16747: 
                   16748: =back
                   16749: 
                   16750: =cut
                   16751: 
                   16752: ############################################################
                   16753: ############################################################
                   16754: 
                   16755: sub mime_email {
1.1343    raeburn  16756:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16757:         $file_name,$attachment_text) = @_;
                   16758:  
1.1223    musolffc 16759:     my $msg = MIME::Lite->new(
                   16760:              From    => $from,
                   16761:              To      => $to,
                   16762:              Subject => $subject,
                   16763:              Type    =>'TEXT',
                   16764:              Data    => $body,
                   16765:              );
1.1343    raeburn  16766:     if ($replyto ne '') {
                   16767:         $msg->add("Reply-To" => $replyto);
                   16768:     }
1.1223    musolffc 16769:     if ($cc_string ne '') {
                   16770:         $msg->add("Cc" => $cc_string);
                   16771:     }
                   16772:     if ($bcc ne '') {
                   16773:         $msg->add("Bcc" => $bcc);
                   16774:     }
                   16775:     $msg->attr("content-type"         => "text/plain");
                   16776:     $msg->attr("content-type.charset" => "UTF-8");
                   16777:     # Attach file if given
                   16778:     if ($attachment_path) {
                   16779:         unless ($file_name) {
                   16780:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16781:         }
                   16782:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16783:         $msg->attach(Type     => $type,
                   16784:                      Path     => $attachment_path,
                   16785:                      Filename => $file_name
                   16786:                      );
                   16787:     # Otherwise attach text if given
                   16788:     } elsif ($attachment_text) {
                   16789:         $msg->attach(Type => 'TEXT',
                   16790:                      Data => $attachment_text);
                   16791:     }
                   16792:     # Send it
                   16793:     $msg->send('sendmail');
                   16794: }
                   16795: 
                   16796: ############################################################
                   16797: ############################################################
                   16798: 
                   16799: =pod
                   16800: 
1.655     raeburn  16801: =head1 Course Catalog Routines
                   16802: 
                   16803: =over 4
                   16804: 
                   16805: =item * &gather_categories()
                   16806: 
                   16807: Converts category definitions - keys of categories hash stored in  
                   16808: coursecategories in configuration.db on the primary library server in a 
                   16809: domain - to an array.  Also generates javascript and idx hash used to 
                   16810: generate Domain Coordinator interface for editing Course Categories.
                   16811: 
                   16812: Inputs:
1.663     raeburn  16813: 
1.655     raeburn  16814: categories (reference to hash of category definitions).
1.663     raeburn  16815: 
1.655     raeburn  16816: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16817:       categories and subcategories).
1.663     raeburn  16818: 
1.655     raeburn  16819: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16820:       editing Course Categories).
1.663     raeburn  16821: 
1.655     raeburn  16822: jsarray (reference to array of categories used to create Javascript arrays for
                   16823:          Domain Coordinator interface for editing Course Categories).
                   16824: 
                   16825: Returns: nothing
                   16826: 
                   16827: Side effects: populates cats, idx and jsarray. 
                   16828: 
                   16829: =cut
                   16830: 
                   16831: sub gather_categories {
                   16832:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16833:     my %counters;
                   16834:     my $num = 0;
                   16835:     foreach my $item (keys(%{$categories})) {
                   16836:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16837:         if ($container eq '' && $depth == 0) {
                   16838:             $cats->[$depth][$categories->{$item}] = $cat;
                   16839:         } else {
                   16840:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16841:         }
                   16842:         my ($escitem,$tail) = split(/:/,$item,2);
                   16843:         if ($counters{$tail} eq '') {
                   16844:             $counters{$tail} = $num;
                   16845:             $num ++;
                   16846:         }
                   16847:         if (ref($idx) eq 'HASH') {
                   16848:             $idx->{$item} = $counters{$tail};
                   16849:         }
                   16850:         if (ref($jsarray) eq 'ARRAY') {
                   16851:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16852:         }
                   16853:     }
                   16854:     return;
                   16855: }
                   16856: 
                   16857: =pod
                   16858: 
                   16859: =item * &extract_categories()
                   16860: 
                   16861: Used to generate breadcrumb trails for course categories.
                   16862: 
                   16863: Inputs:
1.663     raeburn  16864: 
1.655     raeburn  16865: categories (reference to hash of category definitions).
1.663     raeburn  16866: 
1.655     raeburn  16867: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16868:       categories and subcategories).
1.663     raeburn  16869: 
1.655     raeburn  16870: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16871: 
1.655     raeburn  16872: allitems (reference to hash - key is category key 
                   16873:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16874: 
1.655     raeburn  16875: idx (reference to hash of counters used in Domain Coordinator interface for
                   16876:       editing Course Categories).
1.663     raeburn  16877: 
1.655     raeburn  16878: jsarray (reference to array of categories used to create Javascript arrays for
                   16879:          Domain Coordinator interface for editing Course Categories).
                   16880: 
1.665     raeburn  16881: subcats (reference to hash of arrays containing all subcategories within each 
                   16882:          category, -recursive)
                   16883: 
1.1321    raeburn  16884: maxd (reference to hash used to hold max depth for all top-level categories).
                   16885: 
1.655     raeburn  16886: Returns: nothing
                   16887: 
                   16888: Side effects: populates trails and allitems hash references.
                   16889: 
                   16890: =cut
                   16891: 
                   16892: sub extract_categories {
1.1321    raeburn  16893:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16894:     if (ref($categories) eq 'HASH') {
                   16895:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16896:         if (ref($cats->[0]) eq 'ARRAY') {
                   16897:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16898:                 my $name = $cats->[0][$i];
                   16899:                 my $item = &escape($name).'::0';
                   16900:                 my $trailstr;
                   16901:                 if ($name eq 'instcode') {
                   16902:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16903:                 } elsif ($name eq 'communities') {
                   16904:                     $trailstr = &mt('Communities');
1.1239    raeburn  16905:                 } elsif ($name eq 'placement') {
                   16906:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16907:                 } else {
                   16908:                     $trailstr = $name;
                   16909:                 }
                   16910:                 if ($allitems->{$item} eq '') {
                   16911:                     push(@{$trails},$trailstr);
                   16912:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16913:                 }
                   16914:                 my @parents = ($name);
                   16915:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16916:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16917:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16918:                         if (ref($subcats) eq 'HASH') {
                   16919:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16920:                         }
1.1321    raeburn  16921:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16922:                     }
                   16923:                 } else {
                   16924:                     if (ref($subcats) eq 'HASH') {
                   16925:                         $subcats->{$item} = [];
1.655     raeburn  16926:                     }
1.1321    raeburn  16927:                     if (ref($maxd) eq 'HASH') {
                   16928:                         $maxd->{$name} = 1;
                   16929:                     }
1.655     raeburn  16930:                 }
                   16931:             }
                   16932:         }
                   16933:     }
                   16934:     return;
                   16935: }
                   16936: 
                   16937: =pod
                   16938: 
1.1162    raeburn  16939: =item * &recurse_categories()
1.655     raeburn  16940: 
                   16941: Recursively used to generate breadcrumb trails for course categories.
                   16942: 
                   16943: Inputs:
1.663     raeburn  16944: 
1.655     raeburn  16945: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16946:       categories and subcategories).
1.663     raeburn  16947: 
1.655     raeburn  16948: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16949: 
                   16950: category (current course category, for which breadcrumb trail is being generated).
                   16951: 
                   16952: trails (reference to array of breadcrumb trails for each category).
                   16953: 
1.655     raeburn  16954: allitems (reference to hash - key is category key
                   16955:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16956: 
1.655     raeburn  16957: parents (array containing containers directories for current category, 
                   16958:          back to top level). 
                   16959: 
                   16960: Returns: nothing
                   16961: 
                   16962: Side effects: populates trails and allitems hash references
                   16963: 
                   16964: =cut
                   16965: 
                   16966: sub recurse_categories {
1.1321    raeburn  16967:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16968:     my $shallower = $depth - 1;
                   16969:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16970:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16971:             my $name = $cats->[$depth]{$category}[$k];
                   16972:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16973:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16974:             if ($allitems->{$item} eq '') {
                   16975:                 push(@{$trails},$trailstr);
                   16976:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16977:             }
                   16978:             my $deeper = $depth+1;
                   16979:             push(@{$parents},$category);
1.665     raeburn  16980:             if (ref($subcats) eq 'HASH') {
                   16981:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16982:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16983:                     my $higher;
                   16984:                     if ($j > 0) {
                   16985:                         $higher = &escape($parents->[$j]).':'.
                   16986:                                   &escape($parents->[$j-1]).':'.$j;
                   16987:                     } else {
                   16988:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16989:                     }
                   16990:                     push(@{$subcats->{$higher}},$subcat);
                   16991:                 }
                   16992:             }
                   16993:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16994:                                 $subcats,$maxd);
1.655     raeburn  16995:             pop(@{$parents});
                   16996:         }
                   16997:     } else {
                   16998:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16999:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  17000:         if ($allitems->{$item} eq '') {
                   17001:             push(@{$trails},$trailstr);
                   17002:             $allitems->{$item} = scalar(@{$trails})-1;
                   17003:         }
1.1321    raeburn  17004:         if (ref($maxd) eq 'HASH') {
                   17005:             if ($depth > $maxd->{$parents->[0]}) {
                   17006:                 $maxd->{$parents->[0]} = $depth;
                   17007:             }
                   17008:         }
1.655     raeburn  17009:     }
                   17010:     return;
                   17011: }
                   17012: 
1.663     raeburn  17013: =pod
                   17014: 
1.1162    raeburn  17015: =item * &assign_categories_table()
1.663     raeburn  17016: 
                   17017: Create a datatable for display of hierarchical categories in a domain,
                   17018: with checkboxes to allow a course to be categorized. 
                   17019: 
                   17020: Inputs:
                   17021: 
                   17022: cathash - reference to hash of categories defined for the domain (from
                   17023:           configuration.db)
                   17024: 
                   17025: currcat - scalar with an & separated list of categories assigned to a course. 
                   17026: 
1.919     raeburn  17027: type    - scalar contains course type (Course or Community).
                   17028: 
1.1260    raeburn  17029: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   17030:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   17031: 
1.663     raeburn  17032: Returns: $output (markup to be displayed) 
                   17033: 
                   17034: =cut
                   17035: 
                   17036: sub assign_categories_table {
1.1259    raeburn  17037:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  17038:     my $output;
                   17039:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  17040:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   17041:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  17042:         $maxdepth = scalar(@cats);
                   17043:         if (@cats > 0) {
                   17044:             my $itemcount = 0;
                   17045:             if (ref($cats[0]) eq 'ARRAY') {
                   17046:                 my @currcategories;
                   17047:                 if ($currcat ne '') {
                   17048:                     @currcategories = split('&',$currcat);
                   17049:                 }
1.919     raeburn  17050:                 my $table;
1.663     raeburn  17051:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   17052:                     my $parent = $cats[0][$i];
1.919     raeburn  17053:                     next if ($parent eq 'instcode');
                   17054:                     if ($type eq 'Community') {
                   17055:                         next unless ($parent eq 'communities');
1.1239    raeburn  17056:                     } elsif ($type eq 'Placement') {
                   17057:                         next unless ($parent eq 'placement');
1.919     raeburn  17058:                     } else {
1.1239    raeburn  17059:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  17060:                     }
1.663     raeburn  17061:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   17062:                     my $item = &escape($parent).'::0';
                   17063:                     my $checked = '';
                   17064:                     if (@currcategories > 0) {
                   17065:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   17066:                             $checked = ' checked="checked"';
1.663     raeburn  17067:                         }
                   17068:                     }
1.919     raeburn  17069:                     my $parent_title = $parent;
                   17070:                     if ($parent eq 'communities') {
                   17071:                         $parent_title = &mt('Communities');
1.1239    raeburn  17072:                     } elsif ($parent eq 'placement') {
                   17073:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  17074:                     }
                   17075:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   17076:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17077:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  17078:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  17079:                     my $depth = 1;
                   17080:                     push(@path,$parent);
1.1259    raeburn  17081:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  17082:                     pop(@path);
1.919     raeburn  17083:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  17084:                     $itemcount ++;
                   17085:                 }
1.919     raeburn  17086:                 if ($itemcount) {
                   17087:                     $output = &Apache::loncommon::start_data_table().
                   17088:                               $table.
                   17089:                               &Apache::loncommon::end_data_table();
                   17090:                 }
1.663     raeburn  17091:             }
                   17092:         }
                   17093:     }
                   17094:     return $output;
                   17095: }
                   17096: 
                   17097: =pod
                   17098: 
1.1162    raeburn  17099: =item * &assign_category_rows()
1.663     raeburn  17100: 
                   17101: Create a datatable row for display of nested categories in a domain,
                   17102: with checkboxes to allow a course to be categorized,called recursively.
                   17103: 
                   17104: Inputs:
                   17105: 
                   17106: itemcount - track row number for alternating colors
                   17107: 
                   17108: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   17109:       categories and subcategories.
                   17110: 
                   17111: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   17112: 
                   17113: parent - parent of current category item
                   17114: 
                   17115: path - Array containing all categories back up through the hierarchy from the
                   17116:        current category to the top level.
                   17117: 
                   17118: currcategories - reference to array of current categories assigned to the course
                   17119: 
1.1260    raeburn  17120: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   17121:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   17122: 
1.663     raeburn  17123: Returns: $output (markup to be displayed).
                   17124: 
                   17125: =cut
                   17126: 
                   17127: sub assign_category_rows {
1.1259    raeburn  17128:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  17129:     my ($text,$name,$item,$chgstr);
                   17130:     if (ref($cats) eq 'ARRAY') {
                   17131:         my $maxdepth = scalar(@{$cats});
                   17132:         if (ref($cats->[$depth]) eq 'HASH') {
                   17133:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   17134:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   17135:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  17136:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  17137:                 for (my $j=0; $j<$numchildren; $j++) {
                   17138:                     $name = $cats->[$depth]{$parent}[$j];
                   17139:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   17140:                     my $deeper = $depth+1;
                   17141:                     my $checked = '';
                   17142:                     if (ref($currcategories) eq 'ARRAY') {
                   17143:                         if (@{$currcategories} > 0) {
                   17144:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   17145:                                 $checked = ' checked="checked"';
1.663     raeburn  17146:                             }
                   17147:                         }
                   17148:                     }
1.664     raeburn  17149:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   17150:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17151:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  17152:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   17153:                              '</td><td>';
1.663     raeburn  17154:                     if (ref($path) eq 'ARRAY') {
                   17155:                         push(@{$path},$name);
1.1259    raeburn  17156:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  17157:                         pop(@{$path});
                   17158:                     }
                   17159:                     $text .= '</td></tr>';
                   17160:                 }
                   17161:                 $text .= '</table></td>';
                   17162:             }
                   17163:         }
                   17164:     }
                   17165:     return $text;
                   17166: }
                   17167: 
1.1181    raeburn  17168: =pod
                   17169: 
                   17170: =back
                   17171: 
                   17172: =cut
                   17173: 
1.655     raeburn  17174: ############################################################
                   17175: ############################################################
                   17176: 
                   17177: 
1.443     albertel 17178: sub commit_customrole {
1.1408    raeburn  17179:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  17180:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  17181:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   17182:                      $context,$othdomby,$requester);
1.630     raeburn  17183:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 17184:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  17185:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17186:     if (wantarray) {
                   17187:         return ($output,$result);
                   17188:     } else {
                   17189:         return $output;
                   17190:     }
1.443     albertel 17191: }
                   17192: 
                   17193: sub commit_standardrole {
1.1408    raeburn  17194:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17195:         $othdomby,$requester) = @_;
1.1399    raeburn  17196:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17197:     if ($context eq 'auto') {
                   17198:         $linefeed = "\n";
                   17199:     } else {
                   17200:         $linefeed = "<br />\n";
                   17201:     }  
1.443     albertel 17202:     if ($three eq 'st') {
1.1399    raeburn  17203:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17204:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17205:                                       $requester);
1.541     raeburn  17206:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17207:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17208:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17209:         } else {
1.541     raeburn  17210:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17211:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17212:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17213:             if ($context eq 'auto') {
                   17214:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17215:             } else {
                   17216:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17217:                &mt('Add to classlist').': <b>ok</b>';
                   17218:             }
                   17219:             $output .= $linefeed;
1.443     albertel 17220:         }
                   17221:     } else {
                   17222:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17223:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17224:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17225:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17226:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17227:         if ($context eq 'auto') {
                   17228:             $output .= $result.$linefeed;
                   17229:         } else {
                   17230:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17231:         }
1.443     albertel 17232:     }
1.1399    raeburn  17233:     if (wantarray) {
                   17234:         return ($output,$result);
                   17235:     } else {
                   17236:         return $output;
                   17237:     }
1.443     albertel 17238: }
                   17239: 
                   17240: sub commit_studentrole {
1.1116    raeburn  17241:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17242:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17243:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17244:     if ($context eq 'auto') {
                   17245:         $linefeed = "\n";
                   17246:     } else {
                   17247:         $linefeed = '<br />'."\n";
                   17248:     }
1.443     albertel 17249:     if (defined($one) && defined($two)) {
                   17250:         my $cid=$one.'_'.$two;
                   17251:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17252:         my $secchange = 0;
                   17253:         my $expire_role_result;
                   17254:         my $modify_section_result;
1.628     raeburn  17255:         if ($oldsec ne '-1') { 
                   17256:             if ($oldsec ne $sec) {
1.443     albertel 17257:                 $secchange = 1;
1.628     raeburn  17258:                 my $now = time;
1.443     albertel 17259:                 my $uurl='/'.$cid;
                   17260:                 $uurl=~s/\_/\//g;
                   17261:                 if ($oldsec) {
                   17262:                     $uurl.='/'.$oldsec;
                   17263:                 }
1.626     raeburn  17264:                 $oldsecurl = $uurl;
1.628     raeburn  17265:                 $expire_role_result = 
1.1408    raeburn  17266:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17267:                                                 '','','',$context,$othdomby,$requester);
                   17268:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17269:                     if ($expire_role_result eq 'refused') {
                   17270:                         my @roles = ('st');
                   17271:                         my @statuses = ('previous');
                   17272:                         my @roledoms = ($one);
                   17273:                         my $withsec = 1;
                   17274:                         my %roleshash = 
                   17275:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17276:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17277:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17278:                             my ($oldstart,$oldend) = 
                   17279:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17280:                             if ($oldend > 0 && $oldend <= $now) {
                   17281:                                 $expire_role_result = 'ok';
                   17282:                             }
                   17283:                         }
                   17284:                     }
                   17285:                 }
1.443     albertel 17286:                 $result = $expire_role_result;
                   17287:             }
                   17288:         }
                   17289:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17290:             $modify_section_result = 
                   17291:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17292:                                                            undef,undef,undef,$sec,
                   17293:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17294:                                                            '',$context,$credits,'',
                   17295:                                                            $othdomby,$requester);
1.443     albertel 17296:             if ($modify_section_result =~ /^ok/) {
                   17297:                 if ($secchange == 1) {
1.628     raeburn  17298:                     if ($sec eq '') {
                   17299:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17300:                     } else {
                   17301:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17302:                     }
1.443     albertel 17303:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17304:                     if ($sec eq '') {
                   17305:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17306:                     } else {
                   17307:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17308:                     }
1.443     albertel 17309:                 } else {
1.628     raeburn  17310:                     if ($sec eq '') {
                   17311:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17312:                     } else {
                   17313:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17314:                     }
1.443     albertel 17315:                 }
                   17316:             } else {
1.1115    raeburn  17317:                 if ($secchange) { 
1.628     raeburn  17318:                     $$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;
                   17319:                 } else {
                   17320:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17321:                 }
1.443     albertel 17322:             }
                   17323:             $result = $modify_section_result;
                   17324:         } elsif ($secchange == 1) {
1.628     raeburn  17325:             if ($oldsec eq '') {
1.1103    raeburn  17326:                 $$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  17327:             } else {
                   17328:                 $$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;
                   17329:             }
1.626     raeburn  17330:             if ($expire_role_result eq 'refused') {
                   17331:                 my $newsecurl = '/'.$cid;
                   17332:                 $newsecurl =~ s/\_/\//g;
                   17333:                 if ($sec ne '') {
                   17334:                     $newsecurl.='/'.$sec;
                   17335:                 }
                   17336:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17337:                     if ($sec eq '') {
                   17338:                         $$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;
                   17339:                     } else {
                   17340:                         $$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;
                   17341:                     }
                   17342:                 }
                   17343:             }
1.443     albertel 17344:         }
                   17345:     } else {
1.626     raeburn  17346:         $$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 17347:         $result = "error: incomplete course id\n";
                   17348:     }
                   17349:     return $result;
                   17350: }
                   17351: 
1.1108    raeburn  17352: sub show_role_extent {
                   17353:     my ($scope,$context,$role) = @_;
                   17354:     $scope =~ s{^/}{};
                   17355:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17356:     push(@courseroles,'co');
                   17357:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17358:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17359:         $scope =~ s{/}{_};
                   17360:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17361:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17362:         my ($audom,$auname) = split(/\//,$scope);
                   17363:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17364:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17365:     } else {
                   17366:         $scope =~ s{/$}{};
                   17367:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17368:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17369:     }
                   17370: }
                   17371: 
1.443     albertel 17372: ############################################################
                   17373: ############################################################
                   17374: 
1.566     albertel 17375: sub check_clone {
1.578     raeburn  17376:     my ($args,$linefeed) = @_;
1.566     albertel 17377:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17378:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17379:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17380:     my $clonetitle;
                   17381:     my @clonemsg;
1.566     albertel 17382:     my $can_clone = 0;
1.944     raeburn  17383:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17384:     if ($lctype ne 'community') {
                   17385:         $lctype = 'course';
                   17386:     }
1.566     albertel 17387:     if ($clonehome eq 'no_host') {
1.944     raeburn  17388:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17389:             push(@clonemsg,({
                   17390:                               mt => 'No new community created.',
                   17391:                               args => [],
                   17392:                             },
                   17393:                             {
                   17394:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17395:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17396:                             }));
1.908     raeburn  17397:         } else {
1.1344    raeburn  17398:             push(@clonemsg,({
                   17399:                               mt => 'No new course created.',
                   17400:                               args => [],
                   17401:                             },
                   17402:                             {
                   17403:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17404:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17405:                             }));
                   17406:         }
1.566     albertel 17407:     } else {
                   17408: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17409:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17410:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17411:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17412:                 push(@clonemsg,({
                   17413:                                   mt => 'No new community created.',
                   17414:                                   args => [],
                   17415:                                 },
                   17416:                                 {
                   17417:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17418:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17419:                                 }));
                   17420:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17421:             }
                   17422:         }
1.1262    raeburn  17423: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17424:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17425: 	    $can_clone = 1;
                   17426: 	} else {
1.1221    raeburn  17427: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17428: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17429:             if ($clonehash{'cloners'} eq '') {
                   17430:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17431:                 if ($domdefs{'canclone'}) {
                   17432:                     unless ($domdefs{'canclone'} eq 'none') {
                   17433:                         if ($domdefs{'canclone'} eq 'domain') {
                   17434:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17435:                                 $can_clone = 1;
                   17436:                             }
                   17437:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17438:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17439:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17440:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17441:                                 $can_clone = 1;
                   17442:                             }
                   17443:                         }
                   17444:                     }
                   17445:                 }
1.578     raeburn  17446:             } else {
1.1221    raeburn  17447: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17448:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17449:                     $can_clone = 1;
1.1221    raeburn  17450:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17451:                     $can_clone = 1;
1.1225    raeburn  17452:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17453:                     $can_clone = 1;
1.1221    raeburn  17454:                 }
                   17455:                 unless ($can_clone) {
1.1225    raeburn  17456:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17457:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17458:                         my (%gotdomdefaults,%gotcodedefaults);
                   17459:                         foreach my $cloner (@cloners) {
                   17460:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17461:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17462:                                 my (%codedefaults,@code_order);
                   17463:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17464:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17465:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17466:                                     }
                   17467:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17468:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17469:                                     }
                   17470:                                 } else {
                   17471:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17472:                                                                             \%codedefaults,
                   17473:                                                                             \@code_order);
                   17474:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17475:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17476:                                 }
                   17477:                                 if (@code_order > 0) {
                   17478:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17479:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17480:                                                                                 $args->{'crscode'})) {
                   17481:                                         $can_clone = 1;
                   17482:                                         last;
                   17483:                                     }
                   17484:                                 }
                   17485:                             }
                   17486:                         }
                   17487:                     }
1.1225    raeburn  17488:                 }
                   17489:             }
                   17490:             unless ($can_clone) {
                   17491:                 my $ccrole = 'cc';
                   17492:                 if ($args->{'crstype'} eq 'Community') {
                   17493:                     $ccrole = 'co';
                   17494:                 }
                   17495: 	        my %roleshash =
                   17496: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17497: 					          $args->{'ccdomain'},
                   17498:                                                   'userroles',['active'],[$ccrole],
                   17499: 					          [$args->{'clonedomain'}]);
                   17500: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17501:                     $can_clone = 1;
                   17502:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17503:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17504:                     $can_clone = 1;
1.1221    raeburn  17505:                 }
                   17506:             }
                   17507:             unless ($can_clone) {
                   17508:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17509:                     push(@clonemsg,({
                   17510:                                       mt => 'No new community created.',
                   17511:                                       args => [],
                   17512:                                     },
                   17513:                                     {
                   17514:                                       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]).',
                   17515:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17516:                                     }));
1.942     raeburn  17517:                 } else {
1.1344    raeburn  17518:                     push(@clonemsg,({
                   17519:                                       mt => 'No new course created.',
                   17520:                                       args => [],
                   17521:                                     },
                   17522:                                     {
                   17523:                                       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]).',
                   17524:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17525:                                     }));
1.1221    raeburn  17526:                 }
1.566     albertel 17527: 	    }
1.578     raeburn  17528:         }
1.566     albertel 17529:     }
1.1344    raeburn  17530:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17531: }
                   17532: 
1.444     albertel 17533: sub construct_course {
1.1262    raeburn  17534:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17535:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17536:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17537:     my $linefeed =  '<br />'."\n";
                   17538:     if ($context eq 'auto') {
                   17539:         $linefeed = "\n";
                   17540:     }
1.566     albertel 17541: 
                   17542: #
                   17543: # Are we cloning?
                   17544: #
1.1344    raeburn  17545:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17546:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17547: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17548:         if (!$can_clone) {
1.1344    raeburn  17549: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17550: 	}
                   17551:     }
                   17552: 
1.444     albertel 17553: #
                   17554: # Open course
                   17555: #
1.1239    raeburn  17556:     my $showncrstype;
                   17557:     if ($args->{'crstype'} eq 'Placement') {
                   17558:         $showncrstype = 'placement test'; 
                   17559:     } else {  
                   17560:         $showncrstype = lc($args->{'crstype'});
                   17561:     }
1.444     albertel 17562:     my %cenv=();
                   17563:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17564:                                              $args->{'cdescr'},
                   17565:                                              $args->{'curl'},
                   17566:                                              $args->{'course_home'},
                   17567:                                              $args->{'nonstandard'},
                   17568:                                              $args->{'crscode'},
                   17569:                                              $args->{'ccuname'}.':'.
                   17570:                                              $args->{'ccdomain'},
1.882     raeburn  17571:                                              $args->{'crstype'},
1.1344    raeburn  17572:                                              $cnum,$context,$category,
                   17573:                                              $callercontext);
1.444     albertel 17574: 
                   17575:     # Note: The testing routines depend on this being output; see 
                   17576:     # Utils::Course. This needs to at least be output as a comment
                   17577:     # if anyone ever decides to not show this, and Utils::Course::new
                   17578:     # will need to be suitably modified.
1.1344    raeburn  17579:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17580:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17581:     } else {
                   17582:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17583:     }
1.943     raeburn  17584:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17585:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17586:     }
                   17587: 
1.444     albertel 17588: #
                   17589: # Check if created correctly
                   17590: #
1.479     albertel 17591:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17592:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17593:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17594:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17595:             $outcome .= &mt_user($user_lh,
                   17596:                             'Course creation failed, unrecognized course home server.');
                   17597:         } else {
                   17598:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17599:         }
                   17600:         $outcome .= $linefeed;
                   17601:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17602:     }
1.541     raeburn  17603:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17604: 
1.444     albertel 17605: #
1.566     albertel 17606: # Do the cloning
                   17607: #   
1.1344    raeburn  17608:     my @clonemsg;
1.566     albertel 17609:     if ($can_clone && $cloneid) {
1.1344    raeburn  17610:         push(@clonemsg,
                   17611:                       {
                   17612:                           mt => 'Created [_1] by cloning from [_2]',
                   17613:                           args => [$showncrstype,$clonetitle],
                   17614:                       });
1.566     albertel 17615: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17616: # Copy all files
1.1344    raeburn  17617:         my @info =
                   17618: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17619: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17620:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17621:                                                      $args->{'tinyurls'});
                   17622:         if (@info) {
                   17623:             push(@clonemsg,@info);
                   17624:         }
1.444     albertel 17625: # Restore URL
1.566     albertel 17626: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17627: # Restore title
1.566     albertel 17628: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17629: # Restore creation date, creator and creation context.
                   17630:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17631:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17632:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17633: # Mark as cloned
1.566     albertel 17634: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17635: # Need to clone grading mode
                   17636:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17637:         $cenv{'grading'}=$newenv{'grading'};
                   17638: # Do not clone these environment entries
                   17639:         &Apache::lonnet::del('environment',
                   17640:                   ['default_enrollment_start_date',
                   17641:                    'default_enrollment_end_date',
                   17642:                    'question.email',
                   17643:                    'policy.email',
                   17644:                    'comment.email',
                   17645:                    'pch.users.denied',
1.725     raeburn  17646:                    'plc.users.denied',
                   17647:                    'hidefromcat',
1.1121    raeburn  17648:                    'checkforpriv',
1.1355    raeburn  17649:                    'categories'],
1.638     www      17650:                    $$crsudom,$$crsunum);
1.1170    raeburn  17651:         if ($args->{'textbook'}) {
                   17652:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17653:         }
1.444     albertel 17654:     }
1.566     albertel 17655: 
1.444     albertel 17656: #
                   17657: # Set environment (will override cloned, if existing)
                   17658: #
                   17659:     my @sections = ();
                   17660:     my @xlists = ();
                   17661:     if ($args->{'crstype'}) {
                   17662:         $cenv{'type'}=$args->{'crstype'};
                   17663:     }
1.1371    raeburn  17664:     if ($args->{'lti'}) {
                   17665:         $cenv{'internal.lti'}=$args->{'lti'};
                   17666:     }
1.444     albertel 17667:     if ($args->{'crsid'}) {
                   17668:         $cenv{'courseid'}=$args->{'crsid'};
                   17669:     }
                   17670:     if ($args->{'crscode'}) {
                   17671:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17672:     }
                   17673:     if ($args->{'crsquota'} ne '') {
                   17674:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17675:     } else {
                   17676:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17677:     }
                   17678:     if ($args->{'ccuname'}) {
                   17679:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17680:                                         ':'.$args->{'ccdomain'};
                   17681:     } else {
                   17682:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17683:     }
1.1116    raeburn  17684:     if ($args->{'defaultcredits'}) {
                   17685:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17686:     }
1.444     albertel 17687:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17688:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17689:     if ($args->{'crssections'}) {
                   17690:         $cenv{'internal.sectionnums'} = '';
                   17691:         if ($args->{'crssections'} =~ m/,/) {
                   17692:             @sections = split/,/,$args->{'crssections'};
                   17693:         } else {
                   17694:             $sections[0] = $args->{'crssections'};
                   17695:         }
                   17696:         if (@sections > 0) {
                   17697:             foreach my $item (@sections) {
                   17698:                 my ($sec,$gp) = split/:/,$item;
                   17699:                 my $class = $args->{'crscode'}.$sec;
                   17700:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17701:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17702:                 if ($addcheck eq 'ok') {
                   17703:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17704:                         push(@oklcsecs,$gp);
                   17705:                     }
                   17706:                 } else {
1.1263    raeburn  17707:                     push(@badclasses,$class);
1.444     albertel 17708:                 }
                   17709:             }
                   17710:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17711:         }
                   17712:     }
                   17713: # do not hide course coordinator from staff listing, 
                   17714: # even if privileged
                   17715:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17716: # add course coordinator's domain to domains to check for privileged users
                   17717: # if different to course domain
                   17718:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17719:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17720:     }
1.444     albertel 17721: # add crosslistings
                   17722:     if ($args->{'crsxlist'}) {
                   17723:         $cenv{'internal.crosslistings'}='';
                   17724:         if ($args->{'crsxlist'} =~ m/,/) {
                   17725:             @xlists = split/,/,$args->{'crsxlist'};
                   17726:         } else {
                   17727:             $xlists[0] = $args->{'crsxlist'};
                   17728:         }
                   17729:         if (@xlists > 0) {
                   17730:             foreach my $item (@xlists) {
                   17731:                 my ($xl,$gp) = split/:/,$item;
                   17732:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17733:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17734:                 if ($addcheck eq 'ok') {
                   17735:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17736:                         push(@oklcsecs,$gp);
                   17737:                     }
                   17738:                 } else {
1.1263    raeburn  17739:                     push(@badclasses,$xl);
1.444     albertel 17740:                 }
                   17741:             }
                   17742:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17743:         }
                   17744:     }
                   17745:     if ($args->{'autoadds'}) {
                   17746:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17747:     }
                   17748:     if ($args->{'autodrops'}) {
                   17749:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17750:     }
                   17751: # check for notification of enrollment changes
                   17752:     my @notified = ();
                   17753:     if ($args->{'notify_owner'}) {
                   17754:         if ($args->{'ccuname'} ne '') {
                   17755:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17756:         }
                   17757:     }
                   17758:     if ($args->{'notify_dc'}) {
                   17759:         if ($uname ne '') { 
1.630     raeburn  17760:             push(@notified,$uname.':'.$udom);
1.444     albertel 17761:         }
                   17762:     }
                   17763:     if (@notified > 0) {
                   17764:         my $notifylist;
                   17765:         if (@notified > 1) {
                   17766:             $notifylist = join(',',@notified);
                   17767:         } else {
                   17768:             $notifylist = $notified[0];
                   17769:         }
                   17770:         $cenv{'internal.notifylist'} = $notifylist;
                   17771:     }
                   17772:     if (@badclasses > 0) {
                   17773:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17774:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17775:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17776:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17777:         );
1.1264    raeburn  17778:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17779:                            &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  17780:         if ($context eq 'auto') {
                   17781:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17782:         } else {
1.566     albertel 17783:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17784:         }
                   17785:         foreach my $item (@badclasses) {
1.541     raeburn  17786:             if ($context eq 'auto') {
1.1261    raeburn  17787:                 $outcome .= " - $item\n";
1.541     raeburn  17788:             } else {
1.1261    raeburn  17789:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17790:             }
1.1261    raeburn  17791:         }
                   17792:         if ($context eq 'auto') {
                   17793:             $outcome .= $linefeed;
                   17794:         } else {
                   17795:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17796:         } 
1.444     albertel 17797:     }
                   17798:     if ($args->{'no_end_date'}) {
                   17799:         $args->{'endaccess'} = 0;
                   17800:     }
1.1412    raeburn  17801: #  If an official course with institutional sections is created by cloning 
                   17802: #  an existing course, section-specific hiding of course totals in student's
                   17803: #  view of grades as copied from cloned course, will be checked for valid 
                   17804: #  sections.
                   17805:     if (($can_clone && $cloneid) &&
                   17806:         ($cenv{'internal.coursecode'} ne '') &&
                   17807:         ($cenv{'grading'} eq 'standard') &&
                   17808:         ($cenv{'hidetotals'} ne '') &&
                   17809:         ($cenv{'hidetotals'} ne 'all')) {
                   17810:         my @hidesecs;
                   17811:         my $deletehidetotals;
                   17812:         if (@oklcsecs) {
                   17813:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17814:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17815:                     push(@hidesecs,$sec);
                   17816:                 }
                   17817:             }
                   17818:             if (@hidesecs) {
                   17819:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17820:             } else {
                   17821:                 $deletehidetotals = 1;
                   17822:             }
                   17823:         } else {
                   17824:             $deletehidetotals = 1;
                   17825:         }
                   17826:         if ($deletehidetotals) {
                   17827:             delete($cenv{'hidetotals'});
                   17828:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17829:         }
                   17830:     }
1.444     albertel 17831:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17832:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17833:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17834:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17835:     if ($args->{'showphotos'}) {
                   17836:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17837:     }
                   17838:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17839:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17840:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17841:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17842:             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'); 
                   17843:             if ($context eq 'auto') {
                   17844:                 $outcome .= $krb_msg;
                   17845:             } else {
1.566     albertel 17846:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17847:             }
                   17848:             $outcome .= $linefeed;
1.444     albertel 17849:         }
                   17850:     }
                   17851:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17852:        if ($args->{'setpolicy'}) {
                   17853:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17854:        }
                   17855:        if ($args->{'setcontent'}) {
                   17856:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17857:        }
1.1251    raeburn  17858:        if ($args->{'setcomment'}) {
                   17859:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17860:        }
1.444     albertel 17861:     }
                   17862:     if ($args->{'reshome'}) {
                   17863: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17864: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17865:     }
                   17866: #
                   17867: # course has keyed access
                   17868: #
                   17869:     if ($args->{'setkeys'}) {
                   17870:        $cenv{'keyaccess'}='yes';
                   17871:     }
                   17872: # if specified, key authority is not course, but user
                   17873: # only active if keyaccess is yes
                   17874:     if ($args->{'keyauth'}) {
1.487     albertel 17875: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17876: 	$user = &LONCAPA::clean_username($user);
                   17877: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17878: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17879: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17880: 	}
                   17881:     }
                   17882: 
1.1166    raeburn  17883: #
1.1167    raeburn  17884: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17885: #
                   17886:     if ($args->{'uniquecode'}) {
                   17887:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17888:         if ($code) {
                   17889:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17890:             my %crsinfo =
                   17891:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17892:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17893:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17894:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17895:             } 
1.1166    raeburn  17896:             if (ref($coderef)) {
                   17897:                 $$coderef = $code;
                   17898:             }
                   17899:         }
                   17900:     }
                   17901: 
1.444     albertel 17902:     if ($args->{'disresdis'}) {
                   17903:         $cenv{'pch.roles.denied'}='st';
                   17904:     }
                   17905:     if ($args->{'disablechat'}) {
                   17906:         $cenv{'plc.roles.denied'}='st';
                   17907:     }
                   17908: 
                   17909:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17910:     # course
                   17911:     $cenv{'course.helper.not.run'} = 1;
                   17912:     #
                   17913:     # Use new Randomseed
                   17914:     #
                   17915:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17916:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17917:     #
                   17918:     # The encryption code and receipt prefix for this course
                   17919:     #
                   17920:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17921:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17922:     #
                   17923:     # By default, use standard grading
                   17924:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17925: 
1.541     raeburn  17926:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17927:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17928: #
                   17929: # Open all assignments
                   17930: #
                   17931:     if ($args->{'openall'}) {
1.1341    raeburn  17932:        my $opendate = time;
                   17933:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17934:            $opendate = $args->{'openallfrom'};
                   17935:        }
1.444     albertel 17936:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17937:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17938:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17939:        $outcome .= &mt('All assignments open starting [_1]',
                   17940:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17941:                    &Apache::lonnet::cput
                   17942:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17943:    }
                   17944: #
                   17945: # Set first page
                   17946: #
                   17947:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17948: 	    || ($cloneid)) {
                   17949: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17950: 
                   17951: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17952:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17953: 
1.444     albertel 17954:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17955:         my $title; my $url;
                   17956:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17957: 	    $title=&mt('Syllabus');
1.444     albertel 17958:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17959:         } else {
1.963     raeburn  17960:             $title=&mt('Table of Contents');
1.444     albertel 17961:             $url='/adm/navmaps';
                   17962:         }
1.445     albertel 17963: 
                   17964:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17965: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17966: 
                   17967: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17968:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17969:     }
1.566     albertel 17970: 
1.1237    raeburn  17971: # 
                   17972: # Set params for Placement Tests
                   17973: #
1.1239    raeburn  17974:     if ($args->{'crstype'} eq 'Placement') {
                   17975:        my %storecontent; 
                   17976:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17977:        my %defaults = (
                   17978:                         buttonshide   => { value => 'yes',
                   17979:                                            type => 'string_yesno',},
                   17980:                         type          => { value => 'randomizetry',
                   17981:                                            type  => 'string_questiontype',},
                   17982:                         maxtries      => { value => 1,
                   17983:                                            type => 'int_pos',},
                   17984:                         problemstatus => { value => 'no',
                   17985:                                            type  => 'string_problemstatus',},
                   17986:                       );
                   17987:        foreach my $key (keys(%defaults)) {
                   17988:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17989:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17990:        }
1.1237    raeburn  17991:        &Apache::lonnet::cput
                   17992:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17993:     }
                   17994: 
1.1344    raeburn  17995:     return (1,$outcome,\@clonemsg);
1.444     albertel 17996: }
                   17997: 
1.1166    raeburn  17998: sub make_unique_code {
                   17999:     my ($cdom,$cnum) = @_;
                   18000:     # get lock on uniquecodes db
                   18001:     my $lockhash = {
                   18002:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   18003:                                                   ':'.$env{'user.domain'},
                   18004:                    };
                   18005:     my $tries = 0;
                   18006:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   18007:     my ($code,$error);
                   18008:   
                   18009:     while (($gotlock ne 'ok') && ($tries<3)) {
                   18010:         $tries ++;
                   18011:         sleep 1;
                   18012:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   18013:     }
                   18014:     if ($gotlock eq 'ok') {
                   18015:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   18016:         my $gotcode;
                   18017:         my $attempts = 0;
                   18018:         while ((!$gotcode) && ($attempts < 100)) {
                   18019:             $code = &generate_code();
                   18020:             if (!exists($currcodes{$code})) {
                   18021:                 $gotcode = 1;
                   18022:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   18023:                     $error = 'nostore';
                   18024:                 }
                   18025:             }
                   18026:             $attempts ++;
                   18027:         }
                   18028:         my @del_lock = ($cnum."\0".'uniquecodes');
                   18029:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   18030:     } else {
                   18031:         $error = 'nolock';
                   18032:     }
                   18033:     return ($code,$error);
                   18034: }
                   18035: 
                   18036: sub generate_code {
                   18037:     my $code;
                   18038:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   18039:     for (my $i=0; $i<6; $i++) {
                   18040:         my $lettnum = int (rand 2);
                   18041:         my $item = '';
                   18042:         if ($lettnum) {
                   18043:             $item = $letts[int( rand(18) )];
                   18044:         } else {
                   18045:             $item = 1+int( rand(8) );
                   18046:         }
                   18047:         $code .= $item;
                   18048:     }
                   18049:     return $code;
                   18050: }
                   18051: 
1.444     albertel 18052: ############################################################
                   18053: ############################################################
                   18054: 
1.1237    raeburn  18055: # Community, Course and Placement Test
1.378     raeburn  18056: sub course_type {
                   18057:     my ($cid) = @_;
                   18058:     if (!defined($cid)) {
                   18059:         $cid = $env{'request.course.id'};
                   18060:     }
1.404     albertel 18061:     if (defined($env{'course.'.$cid.'.type'})) {
                   18062:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  18063:     } else {
                   18064:         return 'Course';
1.377     raeburn  18065:     }
                   18066: }
1.156     albertel 18067: 
1.406     raeburn  18068: sub group_term {
                   18069:     my $crstype = &course_type();
                   18070:     my %names = (
                   18071:                   'Course' => 'group',
1.865     raeburn  18072:                   'Community' => 'group',
1.1237    raeburn  18073:                   'Placement' => 'group',
1.406     raeburn  18074:                 );
                   18075:     return $names{$crstype};
                   18076: }
                   18077: 
1.902     raeburn  18078: sub course_types {
1.1310    raeburn  18079:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  18080:     my %typename = (
                   18081:                          official   => 'Official course',
                   18082:                          unofficial => 'Unofficial course',
                   18083:                          community  => 'Community',
1.1165    raeburn  18084:                          textbook   => 'Textbook course',
1.1237    raeburn  18085:                          placement  => 'Placement test',
1.1310    raeburn  18086:                          lti        => 'LTI provider',
1.902     raeburn  18087:                    );
                   18088:     return (\@types,\%typename);
                   18089: }
                   18090: 
1.156     albertel 18091: sub icon {
                   18092:     my ($file)=@_;
1.505     albertel 18093:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 18094:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 18095:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 18096:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   18097: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   18098: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18099: 	            $curfext.".gif") {
                   18100: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18101: 		$curfext.".gif";
                   18102: 	}
                   18103:     }
1.249     albertel 18104:     return &lonhttpdurl($iconname);
1.154     albertel 18105: } 
1.84      albertel 18106: 
1.575     albertel 18107: sub lonhttpdurl {
1.692     www      18108: #
                   18109: # Had been used for "small fry" static images on separate port 8080.
                   18110: # Modify here if lightweight http functionality desired again.
                   18111: # Currently eliminated due to increasing firewall issues.
                   18112: #
1.575     albertel 18113:     my ($url)=@_;
1.692     www      18114:     return $url;
1.215     albertel 18115: }
                   18116: 
1.213     albertel 18117: sub connection_aborted {
                   18118:     my ($r)=@_;
                   18119:     $r->print(" ");$r->rflush();
                   18120:     my $c = $r->connection;
                   18121:     return $c->aborted();
                   18122: }
                   18123: 
1.221     foxr     18124: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     18125: #    strings as 'strings'.
                   18126: sub escape_single {
1.221     foxr     18127:     my ($input) = @_;
1.223     albertel 18128:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     18129:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   18130:     return $input;
                   18131: }
1.223     albertel 18132: 
1.222     foxr     18133: #  Same as escape_single, but escape's "'s  This 
                   18134: #  can be used for  "strings"
                   18135: sub escape_double {
                   18136:     my ($input) = @_;
                   18137:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   18138:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   18139:     return $input;
                   18140: }
1.223     albertel 18141:  
1.222     foxr     18142: #   Escapes the last element of a full URL.
                   18143: sub escape_url {
                   18144:     my ($url)   = @_;
1.238     raeburn  18145:     my @urlslices = split(/\//, $url,-1);
1.369     www      18146:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  18147:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     18148: }
1.462     albertel 18149: 
1.820     raeburn  18150: sub compare_arrays {
                   18151:     my ($arrayref1,$arrayref2) = @_;
                   18152:     my (@difference,%count);
                   18153:     @difference = ();
                   18154:     %count = ();
                   18155:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   18156:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   18157:         foreach my $element (keys(%count)) {
                   18158:             if ($count{$element} == 1) {
                   18159:                 push(@difference,$element);
                   18160:             }
                   18161:         }
                   18162:     }
                   18163:     return @difference;
                   18164: }
                   18165: 
1.1322    raeburn  18166: sub lon_status_items {
                   18167:     my %defaults = (
                   18168:                      E         => 100,
                   18169:                      W         => 4,
                   18170:                      N         => 1,
1.1324    raeburn  18171:                      U         => 5,
1.1322    raeburn  18172:                      threshold => 200,
                   18173:                      sysmail   => 2500,
                   18174:                    );
                   18175:     my %names = (
                   18176:                    E => 'Errors',
                   18177:                    W => 'Warnings',
                   18178:                    N => 'Notices',
1.1324    raeburn  18179:                    U => 'Unsent',
1.1322    raeburn  18180:                 );
                   18181:     return (\%defaults,\%names);
                   18182: }
                   18183: 
1.817     bisitz   18184: # -------------------------------------------------------- Initialize user login
1.462     albertel 18185: sub init_user_environment {
1.463     albertel 18186:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18187:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18188: 
                   18189:     my $public=($username eq 'public' && $domain eq 'public');
                   18190: 
1.1415    raeburn  18191:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18192:         $coauthorenv);
1.462     albertel 18193:     my $now=time;
                   18194: 
                   18195:     if ($public) {
                   18196: 	my $max_public=100;
                   18197: 	my $oldest;
                   18198: 	my $oldest_time=0;
                   18199: 	for(my $next=1;$next<=$max_public;$next++) {
                   18200: 	    if (-e $lonids."/publicuser_$next.id") {
                   18201: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18202: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18203: 		    $oldest_time=$mtime;
                   18204: 		    $oldest=$next;
                   18205: 		}
                   18206: 	    } else {
                   18207: 		$cookie="publicuser_$next";
                   18208: 		last;
                   18209: 	    }
                   18210: 	}
                   18211: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18212:     } else {
1.1275    raeburn  18213: 	# See if old ID present, if so, remove if this isn't a robot,
                   18214: 	# killing any existing non-robot sessions
1.463     albertel 18215: 	if (!$args->{'robot'}) {
                   18216: 	    opendir(DIR,$lonids);
                   18217: 	    while ($filename=readdir(DIR)) {
                   18218: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18219:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18220:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18221:                         my $linkedfile;
1.1320    raeburn  18222:                         if (exists($oldenv{'user.linkedenv'})) {
                   18223:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18224:                         }
1.1320    raeburn  18225:                         untie(%oldenv);
                   18226:                         if (unlink("$lonids/$filename")) {
                   18227:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18228:                                 if (-l "$lonids/$linkedfile.id") {
                   18229:                                     unlink("$lonids/$linkedfile.id");
                   18230:                                 }
1.1295    raeburn  18231:                             }
                   18232:                         }
                   18233:                     } else {
                   18234:                         unlink($lonids.'/'.$filename);
                   18235:                     }
1.463     albertel 18236: 		}
1.462     albertel 18237: 	    }
1.463     albertel 18238: 	    closedir(DIR);
1.1204    raeburn  18239: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18240:             my $namespace = 'nohist_courseeditor';
                   18241:             my $lockingkey = 'paste'."\0".'locked_num';
                   18242:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18243:                                                 $domain,$username);
                   18244:             if (exists($lockhash{$lockingkey})) {
                   18245:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18246:                 unless ($delresult eq 'ok') {
                   18247:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18248:                 }
                   18249:             }
1.462     albertel 18250: 	}
                   18251: # Give them a new cookie
1.463     albertel 18252: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18253: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18254: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18255:     
                   18256: # Initialize roles
                   18257: 
1.1414    raeburn  18258: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18259:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18260:     }
                   18261: # ------------------------------------ Check browser type and MathML capability
                   18262: 
1.1194    raeburn  18263:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18264:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18265: 
                   18266: # ------------------------------------------------------------- Get environment
                   18267: 
                   18268:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18269:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18270:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18271: 	undef(%userenv);
                   18272:     }
                   18273:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18274: 	$form->{'interface'}=$userenv{'interface'};
                   18275:     }
                   18276:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18277: 
                   18278: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18279:     foreach my $option ('interface','localpath','localres') {
                   18280:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18281:     }
                   18282: # --------------------------------------------------------- Write first profile
                   18283: 
                   18284:     {
1.1350    raeburn  18285:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18286: 	my %initial_env = 
                   18287: 	    ("user.name"          => $username,
                   18288: 	     "user.domain"        => $domain,
                   18289: 	     "user.home"          => $authhost,
                   18290: 	     "browser.type"       => $clientbrowser,
                   18291: 	     "browser.version"    => $clientversion,
                   18292: 	     "browser.mathml"     => $clientmathml,
                   18293: 	     "browser.unicode"    => $clientunicode,
                   18294: 	     "browser.os"         => $clientos,
1.1137    raeburn  18295:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18296:              "browser.info"       => $clientinfo,
1.1194    raeburn  18297:              "browser.osversion"  => $clientosversion,
1.462     albertel 18298: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18299: 	     "request.course.fn"  => '',
                   18300: 	     "request.course.uri" => '',
                   18301: 	     "request.course.sec" => '',
                   18302: 	     "request.role"       => 'cm',
                   18303: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18304: 	     "request.host"       => $ip,);
1.462     albertel 18305: 
                   18306:         if ($form->{'localpath'}) {
                   18307: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18308: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18309:         }
                   18310: 	
                   18311: 	if ($form->{'interface'}) {
                   18312: 	    $form->{'interface'}=~s/\W//gs;
                   18313: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18314: 	    $env{'browser.interface'}=$form->{'interface'};
                   18315: 	}
                   18316: 
1.1157    raeburn  18317:         if ($form->{'iptoken'}) {
                   18318:             my $lonhost = $r->dir_config('lonHostID');
                   18319:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18320:             $env{'user.noloadbalance'} = $lonhost;
                   18321:         }
                   18322: 
1.1268    raeburn  18323:         if ($form->{'noloadbalance'}) {
                   18324:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18325:             my $hosthere = $form->{'noloadbalance'};
                   18326:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18327:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18328:                 $env{'user.noloadbalance'} = $hosthere;
                   18329:             }
                   18330:         }
                   18331: 
1.1016    raeburn  18332:         unless ($domain eq 'public') {
1.1273    raeburn  18333:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18334:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18335: 
1.1414    raeburn  18336:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18337:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18338:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18339:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18340:             }
1.980     raeburn  18341: 
1.1311    raeburn  18342:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18343:                 $userenv{'canrequest.'.$crstype} =
                   18344:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18345:                                                       'reload','requestcourses',
                   18346:                                                       \%userenv,\%domdef,\%is_adv);
                   18347:             }
1.724     raeburn  18348: 
1.1418    raeburn  18349:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18350:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18351:                 if ($userenv{'authoreditors'}) {
                   18352:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18353:                 } elsif ($domdef{'editors'} ne '') {
                   18354:                     $userenv{'editors'} = $domdef{'editors'};
                   18355:                 } else {
                   18356:                     $userenv{'editors'} = 'edit,xml';
                   18357:                 }
1.1431    raeburn  18358:                 if ($userenv{'authorarchive'}) {
                   18359:                     $userenv{'canarchive'} = 1;
                   18360:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18361:                          ($domdef{'archive'})) {
                   18362:                     $userenv{'canarchive'} = 1;
                   18363:                 }
1.1418    raeburn  18364:             }
                   18365: 
1.1273    raeburn  18366:             $userenv{'canrequest.author'} =
                   18367:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18368:                                                   'reload','requestauthor',
1.980     raeburn  18369:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18370:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18371:                                                  $domain,$username);
                   18372:             my $reqstatus = $reqauthor{'author_status'};
                   18373:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18374:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18375:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18376:                                                       $reqauthor{'author'}{'timestamp'};
                   18377:                 }
1.1092    raeburn  18378:             }
1.1287    raeburn  18379:             my ($types,$typename) = &course_types();
                   18380:             if (ref($types) eq 'ARRAY') {
                   18381:                 my @options = ('approval','validate','autolimit');
                   18382:                 my $optregex = join('|',@options);
                   18383:                 my (%willtrust,%trustchecked);
                   18384:                 foreach my $type (@{$types}) {
                   18385:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18386:                     if ($dom_str ne '') {
                   18387:                         my $updatedstr = '';
                   18388:                         my @possdomains = split(',',$dom_str);
                   18389:                         foreach my $entry (@possdomains) {
                   18390:                             my ($extdom,$extopt) = split(':',$entry);
                   18391:                             unless ($trustchecked{$extdom}) {
                   18392:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18393:                                 $trustchecked{$extdom} = 1;
                   18394:                             }
                   18395:                             if ($willtrust{$extdom}) {
                   18396:                                 $updatedstr .= $entry.',';
                   18397:                             }
                   18398:                         }
                   18399:                         $updatedstr =~ s/,$//;
                   18400:                         if ($updatedstr) {
                   18401:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18402:                         } else {
                   18403:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18404:                         }
                   18405:                     }
                   18406:                 }
                   18407:             }
1.1092    raeburn  18408:         }
1.462     albertel 18409: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18410: 
1.462     albertel 18411: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18412: 		 &GDBM_WRCREAT(),0640)) {
                   18413: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18414: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18415: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18416:             if (ref($firstaccenv) eq 'HASH') {
                   18417:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18418:             }
                   18419:             if (ref($timerintenv) eq 'HASH') {
                   18420:                 &_add_to_env(\%disk_env,$timerintenv);
                   18421:             }
1.1414    raeburn  18422:             if (ref($coauthorenv) eq 'HASH') {
                   18423:                 if (keys(%{$coauthorenv})) {
                   18424:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18425:                 }
                   18426:             }
1.463     albertel 18427: 	    if (ref($args->{'extra_env'})) {
                   18428: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18429: 	    }
1.462     albertel 18430: 	    untie(%disk_env);
                   18431: 	} else {
1.705     tempelho 18432: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18433: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18434: 	    return 'error: '.$!;
                   18435: 	}
                   18436:     }
                   18437:     $env{'request.role'}='cm';
                   18438:     $env{'request.role.adv'}=$env{'user.adv'};
                   18439:     $env{'browser.type'}=$clientbrowser;
                   18440: 
                   18441:     return $cookie;
                   18442: 
                   18443: }
                   18444: 
                   18445: sub _add_to_env {
                   18446:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18447:     if (ref($env_data) eq 'HASH') {
                   18448:         while (my ($key,$value) = each(%$env_data)) {
                   18449: 	    $idf->{$prefix.$key} = $value;
                   18450: 	    $env{$prefix.$key}   = $value;
                   18451:         }
1.462     albertel 18452:     }
                   18453: }
                   18454: 
1.685     tempelho 18455: # --- Get the symbolic name of a problem and the url
                   18456: sub get_symb {
                   18457:     my ($request,$silent) = @_;
1.726     raeburn  18458:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18459:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18460:     if ($symb eq '') {
                   18461:         if (!$silent) {
1.1071    raeburn  18462:             if (ref($request)) { 
                   18463:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18464:             }
1.685     tempelho 18465:             return ();
                   18466:         }
                   18467:     }
                   18468:     &Apache::lonenc::check_decrypt(\$symb);
                   18469:     return ($symb);
                   18470: }
                   18471: 
                   18472: # --------------------------------------------------------------Get annotation
                   18473: 
                   18474: sub get_annotation {
                   18475:     my ($symb,$enc) = @_;
                   18476: 
                   18477:     my $key = $symb;
                   18478:     if (!$enc) {
                   18479:         $key =
                   18480:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18481:     }
                   18482:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18483:     return $annotation{$key};
                   18484: }
                   18485: 
                   18486: sub clean_symb {
1.731     raeburn  18487:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18488: 
                   18489:     &Apache::lonenc::check_decrypt(\$symb);
                   18490:     my $enc = $env{'request.enc'};
1.731     raeburn  18491:     if ($delete_enc) {
1.730     raeburn  18492:         delete($env{'request.enc'});
                   18493:     }
1.685     tempelho 18494: 
                   18495:     return ($symb,$enc);
                   18496: }
1.462     albertel 18497: 
1.1181    raeburn  18498: ############################################################
                   18499: ############################################################
                   18500: 
                   18501: =pod
                   18502: 
                   18503: =head1 Routines for building display used to search for courses
                   18504: 
                   18505: 
                   18506: =over 4
                   18507: 
                   18508: =item * &build_filters()
                   18509: 
                   18510: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18511: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18512: and quotacheck.pl
                   18513: 
1.1181    raeburn  18514: 
                   18515: Inputs:
                   18516: 
                   18517: filterlist - anonymous array of fields to include as potential filters 
                   18518: 
                   18519: crstype - course type
                   18520: 
                   18521: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18522:               to pop-open a course selector (will contain "extra element"). 
                   18523: 
                   18524: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18525: 
                   18526: filter - anonymous hash of criteria and their values
                   18527: 
                   18528: action - form action
                   18529: 
                   18530: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18531: 
1.1182    raeburn  18532: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18533: 
                   18534: cloneruname - username of owner of new course who wants to clone
                   18535: 
                   18536: clonerudom - domain of owner of new course who wants to clone
                   18537: 
                   18538: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18539: 
                   18540: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18541: 
                   18542: codedom - domain
                   18543: 
                   18544: formname - value of form element named "form". 
                   18545: 
                   18546: fixeddom - domain, if fixed.
                   18547: 
                   18548: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18549: 
                   18550: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18551: 
                   18552: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18553: 
                   18554: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18555: 
                   18556: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18557: 
                   18558: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18559: 
                   18560: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18561: 
1.1182    raeburn  18562: 
1.1181    raeburn  18563: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18564: 
1.1182    raeburn  18565: 
1.1181    raeburn  18566: Side Effects: None
                   18567: 
                   18568: =cut
                   18569: 
                   18570: # ---------------------------------------------- search for courses based on last activity etc.
                   18571: 
                   18572: sub build_filters {
                   18573:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18574:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18575:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18576:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18577:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18578:     my ($list,$jscript);
1.1181    raeburn  18579:     my $onchange = 'javascript:updateFilters(this)';
                   18580:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18581:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18582:         $typeselectform,$instcodetitle);
                   18583:     if ($formname eq '') {
                   18584:         $formname = $caller;
                   18585:     }
                   18586:     foreach my $item (@{$filterlist}) {
                   18587:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18588:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18589:             if ($item eq 'domainfilter') {
                   18590:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18591:             } elsif ($item eq 'coursefilter') {
                   18592:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18593:             } elsif ($item eq 'ownerfilter') {
                   18594:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18595:             } elsif ($item eq 'ownerdomfilter') {
                   18596:                 $filter->{'ownerdomfilter'} =
                   18597:                     &LONCAPA::clean_domain($filter->{$item});
                   18598:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18599:                                                        'ownerdomfilter',1);
                   18600:             } elsif ($item eq 'personfilter') {
                   18601:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18602:             } elsif ($item eq 'persondomfilter') {
                   18603:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18604:                                                         'persondomfilter',1);
                   18605:             } else {
                   18606:                 $filter->{$item} =~ s/\W//g;
                   18607:             }
                   18608:             if (!$filter->{$item}) {
                   18609:                 $filter->{$item} = '';
                   18610:             }
                   18611:         }
                   18612:         if ($item eq 'domainfilter') {
                   18613:             my $allow_blank = 1;
                   18614:             if ($formname eq 'portform') {
                   18615:                 $allow_blank=0;
                   18616:             } elsif ($formname eq 'studentform') {
                   18617:                 $allow_blank=0;
                   18618:             }
                   18619:             if ($fixeddom) {
                   18620:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18621:                                     ' value="'.$codedom.'" />'.
                   18622:                                     &Apache::lonnet::domain($codedom,'description');
                   18623:             } else {
                   18624:                 $domainselectform = &select_dom_form($filter->{$item},
                   18625:                                                      'domainfilter',
                   18626:                                                       $allow_blank,'',$onchange);
                   18627:             }
                   18628:         } else {
                   18629:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18630:         }
                   18631:     }
                   18632: 
                   18633:     # last course activity filter and selection
                   18634:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18635: 
                   18636:     # course created filter and selection
                   18637:     if (exists($filter->{'createdfilter'})) {
                   18638:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18639:     }
                   18640: 
1.1239    raeburn  18641:     my $prefix = $crstype;
                   18642:     if ($crstype eq 'Placement') {
                   18643:         $prefix = 'Placement Test'
                   18644:     }
1.1181    raeburn  18645:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18646:                 'cac' => "$prefix Activity",
                   18647:                 'ccr' => "$prefix Created",
                   18648:                 'cde' => "$prefix Title",
                   18649:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18650:                 'ins' => 'Institutional Code',
                   18651:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18652:                 'cow' => "$prefix Owner/Co-owner",
                   18653:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18654:                 'cog' => 'Type',
                   18655:              );
                   18656: 
                   18657:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18658:         my $typeval = 'Course';
                   18659:         if ($crstype eq 'Community') {
                   18660:             $typeval = 'Community';
1.1239    raeburn  18661:         } elsif ($crstype eq 'Placement') {
                   18662:             $typeval = 'Placement';
1.1181    raeburn  18663:         }
                   18664:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18665:     } else {
                   18666:         $typeselectform =  '<select name="type" size="1"';
                   18667:         if ($onchange) {
                   18668:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18669:         }
                   18670:         $typeselectform .= '>'."\n";
1.1237    raeburn  18671:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18672:             my $shown;
                   18673:             if ($posstype eq 'Placement') {
                   18674:                 $shown = &mt('Placement Test');
                   18675:             } else {
                   18676:                 $shown = &mt($posstype);
                   18677:             }
1.1181    raeburn  18678:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18679:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18680:         }
                   18681:         $typeselectform.="</select>";
                   18682:     }
                   18683: 
                   18684:     my ($cloneableonlyform,$cloneabletitle);
                   18685:     if (exists($filter->{'cloneableonly'})) {
                   18686:         my $cloneableon = '';
                   18687:         my $cloneableoff = ' checked="checked"';
                   18688:         if ($filter->{'cloneableonly'}) {
                   18689:             $cloneableon = $cloneableoff;
                   18690:             $cloneableoff = '';
                   18691:         }
                   18692:         $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>';
                   18693:         if ($formname eq 'ccrs') {
1.1187    bisitz   18694:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18695:         } else {
                   18696:             $cloneabletitle = &mt('Cloneable by you');
                   18697:         }
                   18698:     }
                   18699:     my $officialjs;
                   18700:     if ($crstype eq 'Course') {
                   18701:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18702: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18703: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18704:             if ($codedom) { 
1.1181    raeburn  18705:                 $officialjs = 1;
                   18706:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18707:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18708:                                                                   $officialjs,$codetitlesref);
                   18709:                 if ($jscript) {
1.1182    raeburn  18710:                     $jscript = '<script type="text/javascript">'."\n".
                   18711:                                '// <![CDATA['."\n".
                   18712:                                $jscript."\n".
                   18713:                                '// ]]>'."\n".
                   18714:                                '</script>'."\n";
1.1181    raeburn  18715:                 }
                   18716:             }
                   18717:             if ($instcodeform eq '') {
                   18718:                 $instcodeform =
                   18719:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18720:                     $list->{'instcodefilter'}.'" />';
                   18721:                 $instcodetitle = $lt{'ins'};
                   18722:             } else {
                   18723:                 $instcodetitle = $lt{'inc'};
                   18724:             }
                   18725:             if ($fixeddom) {
                   18726:                 $instcodetitle .= '<br />('.$codedom.')';
                   18727:             }
                   18728:         }
                   18729:     }
                   18730:     my $output = qq|
                   18731: <form method="post" name="filterpicker" action="$action">
                   18732: <input type="hidden" name="form" value="$formname" />
                   18733: |;
                   18734:     if ($formname eq 'modifycourse') {
                   18735:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18736:                    '<input type="hidden" name="prevphase" value="'.
                   18737:                    $prevphase.'" />'."\n";
1.1198    musolffc 18738:     } elsif ($formname eq 'quotacheck') {
                   18739:         $output .= qq|
                   18740: <input type="hidden" name="sortby" value="" />
                   18741: <input type="hidden" name="sortorder" value="" />
                   18742: |;
                   18743:     } else {
1.1181    raeburn  18744:         my $name_input;
                   18745:         if ($cnameelement ne '') {
                   18746:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18747:                           $cnameelement.'" />';
                   18748:         }
                   18749:         $output .= qq|
1.1182    raeburn  18750: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18751: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18752: $name_input
                   18753: $roleelement
                   18754: $multelement
                   18755: $typeelement
                   18756: |;
                   18757:         if ($formname eq 'portform') {
                   18758:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18759:         }
                   18760:     }
                   18761:     if ($fixeddom) {
                   18762:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18763:     }
                   18764:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18765:     if ($sincefilterform) {
                   18766:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18767:                   .$sincefilterform
                   18768:                   .&Apache::lonhtmlcommon::row_closure();
                   18769:     }
                   18770:     if ($createdfilterform) {
                   18771:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18772:                   .$createdfilterform
                   18773:                   .&Apache::lonhtmlcommon::row_closure();
                   18774:     }
                   18775:     if ($domainselectform) {
                   18776:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18777:                   .$domainselectform
                   18778:                   .&Apache::lonhtmlcommon::row_closure();
                   18779:     }
                   18780:     if ($typeselectform) {
                   18781:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18782:             $output .= $typeselectform;
                   18783:         } else {
                   18784:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18785:                       .$typeselectform
                   18786:                       .&Apache::lonhtmlcommon::row_closure();
                   18787:         }
                   18788:     }
                   18789:     if ($instcodeform) {
                   18790:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18791:                   .$instcodeform
                   18792:                   .&Apache::lonhtmlcommon::row_closure();
                   18793:     }
                   18794:     if (exists($filter->{'ownerfilter'})) {
                   18795:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18796:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18797:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18798:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18799:                    $ownerdomselectform.'</td></tr></table>'.
                   18800:                    &Apache::lonhtmlcommon::row_closure();
                   18801:     }
                   18802:     if (exists($filter->{'personfilter'})) {
                   18803:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18804:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18805:                    '<input type="text" name="personfilter" size="20" value="'.
                   18806:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18807:                    $persondomselectform.'</td></tr></table>'.
                   18808:                    &Apache::lonhtmlcommon::row_closure();
                   18809:     }
                   18810:     if (exists($filter->{'coursefilter'})) {
                   18811:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18812:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18813:                   .$list->{'coursefilter'}.'" />'
                   18814:                   .&Apache::lonhtmlcommon::row_closure();
                   18815:     }
                   18816:     if ($cloneableonlyform) {
                   18817:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18818:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18819:     }
                   18820:     if (exists($filter->{'descriptfilter'})) {
                   18821:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18822:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18823:                   .$list->{'descriptfilter'}.'" />'
                   18824:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18825:     }
                   18826:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18827:                '<input type="hidden" name="updater" value="" />'."\n".
                   18828:                '<input type="submit" name="gosearch" value="'.
                   18829:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18830:     return $jscript.$clonewarning.$output;
                   18831: }
                   18832: 
                   18833: =pod 
                   18834: 
                   18835: =item * &timebased_select_form()
                   18836: 
1.1182    raeburn  18837: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18838: filter e.g., Course Activity, Course Created, when searching for courses
                   18839: or communities
                   18840: 
                   18841: Inputs:
                   18842: 
                   18843: item - name of form element (sincefilter or createdfilter)
                   18844: 
                   18845: filter - anonymous hash of criteria and their values
                   18846: 
                   18847: Returns: HTML for a select box contained a blank, then six time selections,
                   18848:          with value set in incoming form variables currently selected. 
                   18849: 
                   18850: Side Effects: None
                   18851: 
                   18852: =cut
                   18853: 
                   18854: sub timebased_select_form {
                   18855:     my ($item,$filter) = @_;
                   18856:     if (ref($filter) eq 'HASH') {
                   18857:         $filter->{$item} =~ s/[^\d-]//g;
                   18858:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18859:         return &select_form(
                   18860:                             $filter->{$item},
                   18861:                             $item,
                   18862:                             {      '-1' => '',
                   18863:                                 '86400' => &mt('today'),
                   18864:                                '604800' => &mt('last week'),
                   18865:                               '2592000' => &mt('last month'),
                   18866:                               '7776000' => &mt('last three months'),
                   18867:                              '15552000' => &mt('last six months'),
                   18868:                              '31104000' => &mt('last year'),
                   18869:                     'select_form_order' =>
                   18870:                            ['-1','86400','604800','2592000','7776000',
                   18871:                             '15552000','31104000']});
                   18872:     }
                   18873: }
                   18874: 
                   18875: =pod
                   18876: 
                   18877: =item * &js_changer()
                   18878: 
                   18879: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18880: when course type or domain is changed, and also to hide 'Searching ...' on
                   18881: page load completion for page showing search result.
1.1181    raeburn  18882: 
                   18883: Inputs: None
                   18884: 
1.1183    raeburn  18885: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18886: 
                   18887: Side Effects: None
                   18888: 
                   18889: =cut
                   18890: 
                   18891: sub js_changer {
                   18892:     return <<ENDJS;
                   18893: <script type="text/javascript">
                   18894: // <![CDATA[
                   18895: function updateFilters(caller) {
                   18896:     if (typeof(caller) != "undefined") {
                   18897:         document.filterpicker.updater.value = caller.name;
                   18898:     }
                   18899:     document.filterpicker.submit();
                   18900: }
1.1183    raeburn  18901: 
                   18902: function hideSearching() {
                   18903:     if (document.getElementById('searching')) {
                   18904:         document.getElementById('searching').style.display = 'none';
                   18905:     }
                   18906:     return;
                   18907: }
                   18908: 
1.1181    raeburn  18909: // ]]>
                   18910: </script>
                   18911: 
                   18912: ENDJS
                   18913: }
                   18914: 
                   18915: =pod
                   18916: 
1.1182    raeburn  18917: =item * &search_courses()
                   18918: 
                   18919: Process selected filters form course search form and pass to lonnet::courseiddump
                   18920: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18921: 
                   18922: Inputs:
                   18923: 
                   18924: dom - domain being searched 
                   18925: 
                   18926: type - course type ('Course' or 'Community' or '.' if any).
                   18927: 
                   18928: filter - anonymous hash of criteria and their values
                   18929: 
                   18930: numtitles - for institutional codes - number of categories
                   18931: 
                   18932: cloneruname - optional username of new course owner
                   18933: 
                   18934: clonerudom - optional domain of new course owner
                   18935: 
1.1221    raeburn  18936: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18937:             (used when DC is using course creation form)
                   18938: 
                   18939: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18940: 
1.1221    raeburn  18941: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18942:            (and so can clone automatically)
                   18943: 
                   18944: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18945: 
                   18946: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18947:               courses to clone 
1.1182    raeburn  18948: 
                   18949: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18950: 
                   18951: 
                   18952: Side Effects: None
                   18953: 
                   18954: =cut
                   18955: 
                   18956: 
                   18957: sub search_courses {
1.1221    raeburn  18958:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18959:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18960:     my (%courses,%showcourses,$cloner);
                   18961:     if (($filter->{'ownerfilter'} ne '') ||
                   18962:         ($filter->{'ownerdomfilter'} ne '')) {
                   18963:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18964:                                        $filter->{'ownerdomfilter'};
                   18965:     }
                   18966:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18967:         if (!$filter->{$item}) {
                   18968:             $filter->{$item}='.';
                   18969:         }
                   18970:     }
                   18971:     my $now = time;
                   18972:     my $timefilter =
                   18973:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18974:     my ($createdbefore,$createdafter);
                   18975:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18976:         $createdbefore = $now;
                   18977:         $createdafter = $now-$filter->{'createdfilter'};
                   18978:     }
                   18979:     my ($instcodefilter,$regexpok);
                   18980:     if ($numtitles) {
                   18981:         if ($env{'form.official'} eq 'on') {
                   18982:             $instcodefilter =
                   18983:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18984:             $regexpok = 1;
                   18985:         } elsif ($env{'form.official'} eq 'off') {
                   18986:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18987:             unless ($instcodefilter eq '') {
                   18988:                 $regexpok = -1;
                   18989:             }
                   18990:         }
                   18991:     } else {
                   18992:         $instcodefilter = $filter->{'instcodefilter'};
                   18993:     }
                   18994:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18995:     if ($type eq '') { $type = '.'; }
                   18996: 
                   18997:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18998:         $cloner = $cloneruname.':'.$clonerudom;
                   18999:     }
                   19000:     %courses = &Apache::lonnet::courseiddump($dom,
                   19001:                                              $filter->{'descriptfilter'},
                   19002:                                              $timefilter,
                   19003:                                              $instcodefilter,
                   19004:                                              $filter->{'combownerfilter'},
                   19005:                                              $filter->{'coursefilter'},
                   19006:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  19007:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  19008:                                              $filter->{'cloneableonly'},
                   19009:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  19010:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  19011:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   19012:         my $ccrole;
                   19013:         if ($type eq 'Community') {
                   19014:             $ccrole = 'co';
                   19015:         } else {
                   19016:             $ccrole = 'cc';
                   19017:         }
                   19018:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   19019:                                                      $filter->{'persondomfilter'},
                   19020:                                                      'userroles',undef,
                   19021:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   19022:                                                      $dom);
                   19023:         foreach my $role (keys(%rolehash)) {
                   19024:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   19025:             my $cid = $cdom.'_'.$cnum;
                   19026:             if (exists($courses{$cid})) {
                   19027:                 if (ref($courses{$cid}) eq 'HASH') {
                   19028:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   19029:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  19030:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  19031:                         }
                   19032:                     } else {
                   19033:                         $courses{$cid}{roles} = [$courserole];
                   19034:                     }
                   19035:                     $showcourses{$cid} = $courses{$cid};
                   19036:                 }
                   19037:             }
                   19038:         }
                   19039:         %courses = %showcourses;
                   19040:     }
                   19041:     return %courses;
                   19042: }
                   19043: 
                   19044: =pod
                   19045: 
1.1181    raeburn  19046: =back
                   19047: 
1.1207    raeburn  19048: =head1 Routines for version requirements for current course.
                   19049: 
                   19050: =over 4
                   19051: 
                   19052: =item * &check_release_required()
                   19053: 
                   19054: Compares required LON-CAPA version with version on server, and
                   19055: if required version is newer looks for a server with the required version.
                   19056: 
                   19057: Looks first at servers in user's owen domain; if none suitable, looks at
                   19058: servers in course's domain are permitted to host sessions for user's domain.
                   19059: 
                   19060: Inputs:
                   19061: 
                   19062: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19063: 
                   19064: $courseid - Course ID of current course
                   19065: 
                   19066: $rolecode - User's current role in course (for switchserver query string).
                   19067: 
                   19068: $required - LON-CAPA version needed by course (format: Major.Minor).
                   19069: 
                   19070: 
                   19071: Returns:
                   19072: 
                   19073: $switchserver - query string tp append to /adm/switchserver call (if 
                   19074:                 current server's LON-CAPA version is too old. 
                   19075: 
                   19076: $warning - Message is displayed if no suitable server could be found.
                   19077: 
                   19078: =cut
                   19079: 
                   19080: sub check_release_required {
                   19081:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   19082:     my ($switchserver,$warning);
                   19083:     if ($required ne '') {
                   19084:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   19085:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19086:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   19087:             my $otherserver;
                   19088:             if (($major eq '' && $minor eq '') ||
                   19089:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   19090:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   19091:                 my $switchlcrev =
                   19092:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   19093:                                                            $userdomserver);
                   19094:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19095:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   19096:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   19097:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   19098:                     if ($cdom ne $env{'user.domain'}) {
                   19099:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   19100:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   19101:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   19102:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   19103:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   19104:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   19105:                         my $canhost =
                   19106:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   19107:                                                               $coursedomserver,
                   19108:                                                               $remoterev,
                   19109:                                                               $udomdefaults{'remotesessions'},
                   19110:                                                               $defdomdefaults{'hostedsessions'});
                   19111: 
                   19112:                         if ($canhost) {
                   19113:                             $otherserver = $coursedomserver;
                   19114:                         } else {
                   19115:                             $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.");
                   19116:                         }
                   19117:                     } else {
                   19118:                         $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).");
                   19119:                     }
                   19120:                 } else {
                   19121:                     $otherserver = $userdomserver;
                   19122:                 }
                   19123:             }
                   19124:             if ($otherserver ne '') {
                   19125:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   19126:             }
                   19127:         }
                   19128:     }
                   19129:     return ($switchserver,$warning);
                   19130: }
                   19131: 
                   19132: =pod
                   19133: 
                   19134: =item * &check_release_result()
                   19135: 
                   19136: Inputs:
                   19137: 
                   19138: $switchwarning - Warning message if no suitable server found to host session.
                   19139: 
                   19140: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19141:                 and current role.
                   19142: 
                   19143: Returns: HTML to display with information about requirement to switch server.
                   19144:          Either displaying warning with link to Roles/Courses screen or
                   19145:          display link to switchserver.
                   19146: 
1.1181    raeburn  19147: =cut
                   19148: 
1.1207    raeburn  19149: sub check_release_result {
                   19150:     my ($switchwarning,$switchserver) = @_;
                   19151:     my $output = &start_page('Selected course unavailable on this server').
1.1463    raeburn  19152:                  '<div class="LC_landmark" role="main"><p class="LC_warning">';
1.1207    raeburn  19153:     if ($switchwarning) {
                   19154:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   19155:         if (&show_course()) {
                   19156:             $output .= &mt('Display courses');
                   19157:         } else {
                   19158:             $output .= &mt('Display roles');
                   19159:         }
                   19160:         $output .= '</a>';
                   19161:     } elsif ($switchserver) {
                   19162:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   19163:                    '<br />'.
                   19164:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   19165:                    &mt('Switch Server').
                   19166:                    '</a>';
                   19167:     }
1.1463    raeburn  19168:     $output .= '</p></div>'.&end_page();
1.1207    raeburn  19169:     return $output;
                   19170: }
                   19171: 
                   19172: =pod
                   19173: 
                   19174: =item * &needs_coursereinit()
                   19175: 
                   19176: Determine if course contents stored for user's session needs to be
                   19177: refreshed, because content has changed since "Big Hash" last tied.
                   19178: 
                   19179: Check for change is made if time last checked is more than 10 minutes ago
                   19180: (by default).
                   19181: 
                   19182: Inputs:
                   19183: 
                   19184: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19185: 
                   19186: $interval (optional) - Time which may elapse (in s) between last check for content
                   19187:                        change in current course. (default: 600 s).  
                   19188: 
                   19189: Returns: an array; first element is:
                   19190: 
                   19191: =over 4
                   19192: 
                   19193: 'switch' - if content updates mean user's session
                   19194:            needs to be switched to a server running a newer LON-CAPA version
                   19195:  
                   19196: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19197:            on current server hosting user's session                
                   19198: 
                   19199: ''       - if no action required.
                   19200: 
                   19201: =back
                   19202: 
                   19203: If first item element is 'switch':
                   19204: 
                   19205: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19206: 
                   19207: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19208:                               and current role. 
                   19209: 
                   19210: otherwise: no other elements returned.
                   19211: 
                   19212: =back
                   19213: 
                   19214: =cut
                   19215: 
                   19216: sub needs_coursereinit {
                   19217:     my ($loncaparev,$interval) = @_;
                   19218:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19219:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19220:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19221:     my $now = time;
                   19222:     if ($interval eq '') {
                   19223:         $interval = 600;
                   19224:     }
                   19225:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19226:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19227:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19228:         if ($blocked) {
                   19229:             return ();
                   19230:         }
1.1391    raeburn  19231:         my $update;
                   19232:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19233:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19234:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19235:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19236:             if ($needswitch) {
                   19237:                 return ('switch',$switchwarning,$switchserver);
                   19238:             }
                   19239:             $update = 'main';
                   19240:         }
                   19241:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19242:             if ($update) {
                   19243:                 $update = 'both';
                   19244:             } else {
                   19245:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19246:                 if ($needswitch) {
                   19247:                     return ('switch',$switchwarning,$switchserver);
                   19248:                 } else {
                   19249:                     $update = 'supp';
1.1207    raeburn  19250:                 }
                   19251:             }
1.1391    raeburn  19252:         }
1.1453    raeburn  19253:         return ($update);
1.1391    raeburn  19254:     }
                   19255:     return ();
                   19256: }
                   19257: 
                   19258: sub switch_for_update {
                   19259:     my ($loncaparev,$cdom,$cnum) = @_;
                   19260:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19261:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19262:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19263:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19264:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19265:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19266:             my ($switchserver,$switchwarning) =
                   19267:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19268:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19269:             if ($switchwarning ne '' || $switchserver ne '') {
                   19270:                 return ('switch',$switchwarning,$switchserver);
                   19271:             }
1.1207    raeburn  19272:         }
                   19273:     }
                   19274:     return ();
                   19275: }
1.1181    raeburn  19276: 
1.1083    raeburn  19277: sub update_content_constraints {
1.1395    raeburn  19278:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19279:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19280:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19281:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19282:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19283:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19284:         if ($item eq 'resourcetag') {
                   19285:             if ($name eq 'responsetype') {
                   19286:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19287:             }
1.1307    raeburn  19288:         } elsif ($item eq 'course') {
                   19289:             if ($name eq 'courserestype') {
                   19290:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19291:             }
1.1083    raeburn  19292:         }
                   19293:     }
                   19294:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19295:     if (defined($navmap)) {
1.1307    raeburn  19296:         my (%allresponses,%allcrsrestypes);
                   19297:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19298:             if ($res->is_tool()) {
                   19299:                 if ($allcrsrestypes{'exttool'}) {
                   19300:                     $allcrsrestypes{'exttool'} ++;
                   19301:                 } else {
                   19302:                     $allcrsrestypes{'exttool'} = 1;
                   19303:                 }
                   19304:                 next;
                   19305:             }
1.1083    raeburn  19306:             my %responses = $res->responseTypes();
                   19307:             foreach my $key (keys(%responses)) {
                   19308:                 next unless(exists($checkresponsetypes{$key}));
                   19309:                 $allresponses{$key} += $responses{$key};
                   19310:             }
                   19311:         }
                   19312:         foreach my $key (keys(%allresponses)) {
                   19313:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19314:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19315:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19316:             }
                   19317:         }
1.1307    raeburn  19318:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19319:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19320:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19321:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19322:             }
                   19323:         }
1.1083    raeburn  19324:         undef($navmap);
                   19325:     }
1.1391    raeburn  19326:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19327:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19328:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19329:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19330:         }
                   19331:     }
1.1083    raeburn  19332:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19333:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19334:     }
                   19335:     return;
                   19336: }
                   19337: 
1.1110    raeburn  19338: sub allmaps_incourse {
                   19339:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19340:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19341:         $cid = $env{'request.course.id'};
                   19342:         $cdom = $env{'course.'.$cid.'.domain'};
                   19343:         $cnum = $env{'course.'.$cid.'.num'};
                   19344:         $chome = $env{'course.'.$cid.'.home'};
                   19345:     }
                   19346:     my %allmaps = ();
                   19347:     my $lastchange =
                   19348:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19349:     if ($lastchange > $env{'request.course.tied'}) {
                   19350:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19351:         unless ($ferr) {
1.1395    raeburn  19352:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19353:         }
                   19354:     }
                   19355:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19356:     if (defined($navmap)) {
                   19357:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19358:             $allmaps{$res->src()} = 1;
                   19359:         }
                   19360:     }
                   19361:     return \%allmaps;
                   19362: }
                   19363: 
1.1083    raeburn  19364: sub parse_supplemental_title {
                   19365:     my ($title) = @_;
                   19366: 
                   19367:     my ($foldertitle,$renametitle);
                   19368:     if ($title =~ /&amp;&amp;&amp;/) {
                   19369:         $title = &HTML::Entites::decode($title);
                   19370:     }
                   19371:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19372:         $renametitle=$4;
                   19373:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19374:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19375:         my $name =  &plainname($uname,$udom);
                   19376:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19377:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19378:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19379:         if ($foldertitle ne '') {
1.1401    raeburn  19380:             $title .= ': <br />'.$foldertitle;
                   19381:         }
1.1083    raeburn  19382:     }
                   19383:     if (wantarray) {
                   19384:         return ($title,$foldertitle,$renametitle);
                   19385:     }
                   19386:     return $title;
                   19387: }
                   19388: 
1.1395    raeburn  19389: sub get_supplemental {
                   19390:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19391:     my $hashid=$cnum.':'.$cdom;
                   19392:     my ($supplemental,$cached,$set_httprefs);
                   19393:     unless ($ignorecache) {
                   19394:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19395:     }
                   19396:     unless (defined($cached)) {
                   19397:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19398:         unless ($chome eq 'no_host') {
                   19399:             my @order = @LONCAPA::map::order;
                   19400:             my @resources = @LONCAPA::map::resources;
                   19401:             my @resparms = @LONCAPA::map::resparms;
                   19402:             my @zombies = @LONCAPA::map::zombies;
                   19403:             my ($errors,%ids,%hidden);
                   19404:             $errors =
                   19405:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19406:                                       $errors,$possdel,\%ids,\%hidden);
                   19407:             @LONCAPA::map::order = @order;
                   19408:             @LONCAPA::map::resources = @resources;
                   19409:             @LONCAPA::map::resparms = @resparms;
                   19410:             @LONCAPA::map::zombies = @zombies;
                   19411:             $set_httprefs = 1;
                   19412:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19413:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19414:             }
                   19415:             $supplemental = {
                   19416:                                ids => \%ids,
                   19417:                                hidden => \%hidden,
                   19418:                             };
                   19419:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19420:         }
                   19421:     }
                   19422:     return ($supplemental,$set_httprefs);
                   19423: }
                   19424: 
1.1143    raeburn  19425: sub recurse_supplemental {
1.1391    raeburn  19426:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19427:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19428:         my $mapnum;
                   19429:         if ($suppmap eq 'supplemental.sequence') {
                   19430:             $mapnum = 0;
                   19431:         } else {
                   19432:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19433:         }
1.1143    raeburn  19434:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19435:         if ($fatal) {
                   19436:             $errors ++;
                   19437:         } else {
1.1389    raeburn  19438:             my @order = @LONCAPA::map::order;
                   19439:             if (@order > 0) {
                   19440:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19441:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19442:                 foreach my $idx (@order) {
                   19443:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19444:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19445:                         my $id = $mapnum.':'.$idx;
                   19446:                         push(@{$suppids->{$src}},$id);
                   19447:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19448:                             $hiddensupp->{$id} = 1;
                   19449:                         }
1.1146    raeburn  19450:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19451:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19452:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19453:                         } else {
1.1391    raeburn  19454:                             my $allowed;
                   19455:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19456:                                 $allowed = 1;
                   19457:                             } elsif ($possdel) {
                   19458:                                 foreach my $item (@{$suppids->{$src}}) {
                   19459:                                     next if ($item eq $id);
                   19460:                                     unless ($hiddensupp->{$item}) {
                   19461:                                        $allowed = 1;
                   19462:                                        last;
                   19463:                                     }
                   19464:                                 }
                   19465:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19466:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19467:                                 }
                   19468:                             }
                   19469:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19470:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19471:                             }
1.1143    raeburn  19472:                         }
                   19473:                     }
                   19474:                 }
                   19475:             }
                   19476:         }
                   19477:     }
1.1391    raeburn  19478:     return $errors;
                   19479: }
                   19480: 
                   19481: sub set_supp_httprefs {
                   19482:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19483:     if (ref($supplemental) eq 'HASH') {
                   19484:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19485:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19486:                 next if ($src =~ /\.sequence$/);
                   19487:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19488:                     my $allowed;
                   19489:                     if ($env{'request.role.adv'}) {
                   19490:                         $allowed = 1;
                   19491:                     } else {
                   19492:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19493:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19494:                                 $allowed = 1;
                   19495:                                 last;
                   19496:                             }
                   19497:                         }
                   19498:                     }
                   19499:                     if (exists($env{'httpref.'.$src})) {
                   19500:                         if ($possdel) {
                   19501:                             unless ($allowed) {
                   19502:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19503:                             }
                   19504:                         }
                   19505:                     } elsif ($allowed) {
                   19506:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19507:                     }
                   19508:                 }
                   19509:             }
                   19510:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19511:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19512:             }
                   19513:         }
                   19514:     }
                   19515: }
                   19516: 
                   19517: sub get_supp_parameter {
                   19518:     my ($resparm,$name)=@_;
                   19519:     return if ($resparm eq '');
                   19520:     my $value=undef;
                   19521:     my $ptype=undef;
                   19522:     foreach (split('&&&',$resparm)) {
                   19523:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19524:         if ($thisname eq $name) {
                   19525:             $value=$thisvalue;
                   19526:             $ptype=$thistype;
                   19527:         }
                   19528:     }
                   19529:     return $value;
1.1143    raeburn  19530: }
                   19531: 
1.1101    raeburn  19532: sub symb_to_docspath {
1.1267    raeburn  19533:     my ($symb,$navmapref) = @_;
                   19534:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19535:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19536:     if ($resurl=~/\.(sequence|page)$/) {
                   19537:         $mapurl=$resurl;
                   19538:     } elsif ($resurl eq 'adm/navmaps') {
                   19539:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19540:     }
                   19541:     my $mapresobj;
1.1267    raeburn  19542:     unless (ref($$navmapref)) {
                   19543:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19544:     }
                   19545:     if (ref($$navmapref)) {
                   19546:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19547:     }
                   19548:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19549:     my $type=$2;
                   19550:     my $path;
                   19551:     if (ref($mapresobj)) {
                   19552:         my $pcslist = $mapresobj->map_hierarchy();
                   19553:         if ($pcslist ne '') {
                   19554:             foreach my $pc (split(/,/,$pcslist)) {
                   19555:                 next if ($pc <= 1);
1.1267    raeburn  19556:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19557:                 if (ref($res)) {
                   19558:                     my $thisurl = $res->src();
                   19559:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19560:                     my $thistitle = $res->title();
                   19561:                     $path .= '&'.
                   19562:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19563:                              &escape($thistitle).
1.1101    raeburn  19564:                              ':'.$res->randompick().
                   19565:                              ':'.$res->randomout().
                   19566:                              ':'.$res->encrypted().
                   19567:                              ':'.$res->randomorder().
                   19568:                              ':'.$res->is_page();
                   19569:                 }
                   19570:             }
                   19571:         }
                   19572:         $path =~ s/^\&//;
                   19573:         my $maptitle = $mapresobj->title();
                   19574:         if ($mapurl eq 'default') {
1.1129    raeburn  19575:             $maptitle = 'Main Content';
1.1101    raeburn  19576:         }
                   19577:         $path .= (($path ne '')? '&' : '').
                   19578:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19579:                  &escape($maptitle).
1.1101    raeburn  19580:                  ':'.$mapresobj->randompick().
                   19581:                  ':'.$mapresobj->randomout().
                   19582:                  ':'.$mapresobj->encrypted().
                   19583:                  ':'.$mapresobj->randomorder().
                   19584:                  ':'.$mapresobj->is_page();
                   19585:     } else {
                   19586:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19587:         my $ispage = (($type eq 'page')? 1 : '');
                   19588:         if ($mapurl eq 'default') {
1.1129    raeburn  19589:             $maptitle = 'Main Content';
1.1101    raeburn  19590:         }
                   19591:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19592:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19593:     }
                   19594:     unless ($mapurl eq 'default') {
                   19595:         $path = 'default&'.
1.1146    raeburn  19596:                 &escape('Main Content').
1.1101    raeburn  19597:                 ':::::&'.$path;
                   19598:     }
                   19599:     return $path;
                   19600: }
                   19601: 
1.1393    raeburn  19602: sub validate_folderpath {
                   19603:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19604:     if ($env{'form.folderpath'} ne '') {
                   19605:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19606:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19607:         for (my $i=0; $i<@items; $i++) {
                   19608:             my $odd = $i%2;
                   19609:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19610:                 $badpath = 1;
1.1394    raeburn  19611:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19612:                 my $idx = $i-1;
1.1394    raeburn  19613:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19614:                     my $esc_name = $1;
                   19615:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19616:                         $supppath .= '&'.$esc_name;
                   19617:                         $changed = 1;
                   19618:                     } else {
                   19619:                         $supppath .= '&'.$items[$i];
                   19620:                     }
                   19621:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19622:                     $changed = 1;
1.1393    raeburn  19623:                     my $is_hidden;
                   19624:                     unless ($got_supp) {
1.1395    raeburn  19625:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19626:                         if (ref($supplemental) eq 'HASH') {
                   19627:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19628:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19629:                             }
                   19630:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19631:                                 %suppids = %{$supplemental->{'ids'}};
                   19632:                             }
                   19633:                         }
                   19634:                         $got_supp = 1;
                   19635:                     }
                   19636:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19637:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19638:                         if ($supphidden{$mapid}) {
                   19639:                             $is_hidden = 1;
                   19640:                         }
                   19641:                     }
1.1394    raeburn  19642:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19643:                 } else {
                   19644:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19645:                 }
                   19646:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19647:                 $badpath = 1;
1.1394    raeburn  19648:             } elsif ($supplementalflag) {
1.1393    raeburn  19649:                 $supppath .= '&'.$items[$i];
                   19650:             }
                   19651:             last if ($badpath);
                   19652:         }
                   19653:         if ($badpath) {
                   19654:             delete($env{'form.folderpath'});
1.1394    raeburn  19655:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19656:             $supppath =~ s/^\&//;
                   19657:             $env{'form.folderpath'} = $supppath;
                   19658:         }
                   19659:     }
                   19660:     return;
                   19661: }
                   19662: 
1.1094    raeburn  19663: sub captcha_display {
1.1327    raeburn  19664:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19665:     my ($output,$error);
1.1234    raeburn  19666:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19667:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19668:     if ($captcha eq 'original') {
1.1094    raeburn  19669:         $output = &create_captcha();
                   19670:         unless ($output) {
1.1172    raeburn  19671:             $error = 'captcha';
1.1094    raeburn  19672:         }
                   19673:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19674:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19675:         unless ($output) {
1.1172    raeburn  19676:             $error = 'recaptcha';
1.1094    raeburn  19677:         }
                   19678:     }
1.1234    raeburn  19679:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19680: }
                   19681: 
                   19682: sub captcha_response {
1.1327    raeburn  19683:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19684:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19685:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19686:     if ($captcha eq 'original') {
1.1094    raeburn  19687:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19688:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19689:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19690:     } else {
                   19691:         $captcha_chk = 1;
                   19692:     }
                   19693:     return ($captcha_chk,$captcha_error);
                   19694: }
                   19695: 
                   19696: sub get_captcha_config {
1.1327    raeburn  19697:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19698:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19699:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19700:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19701:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19702:     if ($context eq 'usercreation') {
                   19703:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19704:         if (ref($domconfig{$context}) eq 'HASH') {
                   19705:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19706:             if (ref($hashtocheck) eq 'HASH') {
                   19707:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19708:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19709:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19710:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19711:                     }
                   19712:                     if ($privkey && $pubkey) {
                   19713:                         $captcha = 'recaptcha';
1.1234    raeburn  19714:                         $version = $hashtocheck->{'recaptchaversion'};
                   19715:                         if ($version ne '2') {
                   19716:                             $version = 1;
                   19717:                         }
1.1095    raeburn  19718:                     } else {
                   19719:                         $captcha = 'original';
                   19720:                     }
                   19721:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19722:                     $captcha = 'original';
                   19723:                 }
1.1094    raeburn  19724:             }
1.1095    raeburn  19725:         } else {
                   19726:             $captcha = 'captcha';
                   19727:         }
                   19728:     } elsif ($context eq 'login') {
                   19729:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19730:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19731:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19732:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19733:             if ($privkey && $pubkey) {
                   19734:                 $captcha = 'recaptcha';
1.1234    raeburn  19735:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19736:                 if ($version ne '2') {
                   19737:                     $version = 1; 
                   19738:                 }
1.1095    raeburn  19739:             } else {
                   19740:                 $captcha = 'original';
1.1094    raeburn  19741:             }
1.1095    raeburn  19742:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19743:             $captcha = 'original';
1.1094    raeburn  19744:         }
1.1327    raeburn  19745:     } elsif ($context eq 'passwords') {
                   19746:         if ($dom_in_effect) {
                   19747:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19748:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19749:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19750:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19751:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19752:                 }
                   19753:                 if ($privkey && $pubkey) {
                   19754:                     $captcha = 'recaptcha';
                   19755:                     $version = $passwdconf{'recaptchaversion'};
                   19756:                     if ($version ne '2') {
                   19757:                         $version = 1;
                   19758:                     }
                   19759:                 } else {
                   19760:                     $captcha = 'original';
                   19761:                 }
                   19762:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19763:                 $captcha = 'original';
                   19764:             }
                   19765:         }
                   19766:     } 
1.1234    raeburn  19767:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19768: }
                   19769: 
                   19770: sub create_captcha {
                   19771:     my %captcha_params = &captcha_settings();
                   19772:     my ($output,$maxtries,$tries) = ('',10,0);
                   19773:     while ($tries < $maxtries) {
                   19774:         $tries ++;
                   19775:         my $captcha = Authen::Captcha->new (
                   19776:                                            output_folder => $captcha_params{'output_dir'},
                   19777:                                            data_folder   => $captcha_params{'db_dir'},
                   19778:                                           );
                   19779:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19780: 
                   19781:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19782:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19783:                       '<span class="LC_nobreak">'.
1.1453    raeburn  19784:                       '<label>'.&mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1463    raeburn  19785:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" aria-required="true" />'.
1.1453    raeburn  19786:                       '</label></span><br />'.
1.1176    raeburn  19787:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19788:             last;
                   19789:         }
                   19790:     }
1.1323    raeburn  19791:     if ($output eq '') {
                   19792:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19793:     }
1.1094    raeburn  19794:     return $output;
                   19795: }
                   19796: 
                   19797: sub captcha_settings {
                   19798:     my %captcha_params = (
                   19799:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19800:                            www_output_dir => "/captchaspool",
                   19801:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19802:                            numchars       => '5',
                   19803:                          );
                   19804:     return %captcha_params;
                   19805: }
                   19806: 
                   19807: sub check_captcha {
                   19808:     my ($captcha_chk,$captcha_error);
                   19809:     my $code = $env{'form.code'};
                   19810:     my $md5sum = $env{'form.crypt'};
                   19811:     my %captcha_params = &captcha_settings();
                   19812:     my $captcha = Authen::Captcha->new(
                   19813:                       output_folder => $captcha_params{'output_dir'},
                   19814:                       data_folder   => $captcha_params{'db_dir'},
                   19815:                   );
1.1109    raeburn  19816:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19817:     my %captcha_hash = (
                   19818:                         0       => 'Code not checked (file error)',
                   19819:                        -1      => 'Failed: code expired',
                   19820:                        -2      => 'Failed: invalid code (not in database)',
                   19821:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19822:     );
                   19823:     if ($captcha_chk != 1) {
                   19824:         $captcha_error = $captcha_hash{$captcha_chk}
                   19825:     }
                   19826:     return ($captcha_chk,$captcha_error);
                   19827: }
                   19828: 
                   19829: sub create_recaptcha {
1.1234    raeburn  19830:     my ($pubkey,$version) = @_;
                   19831:     if ($version >= 2) {
1.1367    raeburn  19832:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19833:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19834:     } else {
                   19835:         my $use_ssl;
                   19836:         if ($ENV{'SERVER_PORT'} == 443) {
                   19837:             $use_ssl = 1;
                   19838:         }
                   19839:         my $captcha = Captcha::reCAPTCHA->new;
                   19840:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19841:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19842:                &mt('If the text is hard to read, [_1] will replace them.',
                   19843:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19844:                '<br /><br />';
                   19845:     }
1.1094    raeburn  19846: }
                   19847: 
                   19848: sub check_recaptcha {
1.1234    raeburn  19849:     my ($privkey,$version) = @_;
1.1094    raeburn  19850:     my $captcha_chk;
1.1350    raeburn  19851:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19852:     if ($version >= 2) {
                   19853:         my %info = (
                   19854:                      secret   => $privkey, 
                   19855:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19856:                      remoteip => $ip,
1.1234    raeburn  19857:                    );
1.1280    raeburn  19858:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19859:         $request->content(join('&',map {
                   19860:                          my $name = escape($_);
                   19861:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19862:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19863:                          : &escape($info{$_}) );
                   19864:         } keys(%info)));
                   19865:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19866:         if ($response->is_success)  {
                   19867:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19868:             if (ref($data) eq 'HASH') {
                   19869:                 if ($data->{'success'}) {
                   19870:                     $captcha_chk = 1;
                   19871:                 }
                   19872:             }
                   19873:         }
                   19874:     } else {
                   19875:         my $captcha = Captcha::reCAPTCHA->new;
                   19876:         my $captcha_result =
                   19877:             $captcha->check_answer(
                   19878:                                     $privkey,
1.1350    raeburn  19879:                                     $ip,
1.1234    raeburn  19880:                                     $env{'form.recaptcha_challenge_field'},
                   19881:                                     $env{'form.recaptcha_response_field'},
                   19882:                                   );
                   19883:         if ($captcha_result->{is_valid}) {
                   19884:             $captcha_chk = 1;
                   19885:         }
1.1094    raeburn  19886:     }
                   19887:     return $captcha_chk;
                   19888: }
                   19889: 
1.1174    raeburn  19890: sub emailusername_info {
1.1244    raeburn  19891:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19892:     my %titles = &Apache::lonlocal::texthash (
                   19893:                      lastname      => 'Last Name',
                   19894:                      firstname     => 'First Name',
                   19895:                      institution   => 'School/college/university',
                   19896:                      location      => "School's city, state/province, country",
                   19897:                      web           => "School's web address",
                   19898:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19899:                      id            => 'Student/Employee ID',
1.1174    raeburn  19900:                  );
                   19901:     return (\@fields,\%titles);
                   19902: }
                   19903: 
1.1161    raeburn  19904: sub cleanup_html {
                   19905:     my ($incoming) = @_;
                   19906:     my $outgoing;
                   19907:     if ($incoming ne '') {
                   19908:         $outgoing = $incoming;
                   19909:         $outgoing =~ s/;/&#059;/g;
                   19910:         $outgoing =~ s/\#/&#035;/g;
                   19911:         $outgoing =~ s/\&/&#038;/g;
                   19912:         $outgoing =~ s/</&#060;/g;
                   19913:         $outgoing =~ s/>/&#062;/g;
                   19914:         $outgoing =~ s/\(/&#040/g;
                   19915:         $outgoing =~ s/\)/&#041;/g;
                   19916:         $outgoing =~ s/"/&#034;/g;
                   19917:         $outgoing =~ s/'/&#039;/g;
                   19918:         $outgoing =~ s/\$/&#036;/g;
                   19919:         $outgoing =~ s{/}{&#047;}g;
                   19920:         $outgoing =~ s/=/&#061;/g;
                   19921:         $outgoing =~ s/\\/&#092;/g
                   19922:     }
                   19923:     return $outgoing;
                   19924: }
                   19925: 
1.1190    musolffc 19926: # Checks for critical messages and returns a redirect url if one exists.
                   19927: # $interval indicates how often to check for messages.
1.1282    raeburn  19928: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19929: sub critical_redirect {
1.1282    raeburn  19930:     my ($interval,$context) = @_;
1.1356    raeburn  19931:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19932:         return ();
                   19933:     }
1.1190    musolffc 19934:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19935:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19936:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19937:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19938:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19939:             if ($blocked) {
                   19940:                 my $checkrole = "cm./$cdom/$cnum";
                   19941:                 if ($env{'request.course.sec'} ne '') {
                   19942:                     $checkrole .= "/$env{'request.course.sec'}";
                   19943:                 }
                   19944:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19945:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19946:                     return;
                   19947:                 }
                   19948:             }
                   19949:         }
1.1190    musolffc 19950:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19951:                                         $env{'user.name'});
                   19952:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19953:         my $redirecturl;
1.1190    musolffc 19954:         if ($what[0]) {
1.1356    raeburn  19955: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19956: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19957: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19958:                 return (1, $url);
1.1190    musolffc 19959:             }
1.1191    raeburn  19960:         }
                   19961:     } 
                   19962:     return ();
1.1190    musolffc 19963: }
                   19964: 
1.1174    raeburn  19965: # Use:
                   19966: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19967: #
                   19968: ##################################################
                   19969: #          password associated functions         #
                   19970: ##################################################
                   19971: sub des_keys {
                   19972:     # Make a new key for DES encryption.
                   19973:     # Each key has two parts which are returned separately.
                   19974:     # Please note:  Each key must be passed through the &hex function
                   19975:     # before it is output to the web browser.  The hex versions cannot
                   19976:     # be used to decrypt.
                   19977:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19978:                 '8','9','a','b','c','d','e','f');
                   19979:     my $lkey='';
                   19980:     for (0..7) {
                   19981:         $lkey.=$hexstr[rand(15)];
                   19982:     }
                   19983:     my $ukey='';
                   19984:     for (0..7) {
                   19985:         $ukey.=$hexstr[rand(15)];
                   19986:     }
                   19987:     return ($lkey,$ukey);
                   19988: }
                   19989: 
                   19990: sub des_decrypt {
                   19991:     my ($key,$cyphertext) = @_;
                   19992:     my $keybin=pack("H16",$key);
                   19993:     my $cypher;
                   19994:     if ($Crypt::DES::VERSION>=2.03) {
                   19995:         $cypher=new Crypt::DES $keybin;
                   19996:     } else {
                   19997:         $cypher=new DES $keybin;
                   19998:     }
1.1233    raeburn  19999:     my $plaintext='';
                   20000:     my $cypherlength = length($cyphertext);
                   20001:     my $numchunks = int($cypherlength/32);
                   20002:     for (my $j=0; $j<$numchunks; $j++) {
                   20003:         my $start = $j*32;
                   20004:         my $cypherblock = substr($cyphertext,$start,32);
                   20005:         my $chunk =
                   20006:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   20007:         $chunk .=
                   20008:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   20009:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   20010:         $plaintext .= $chunk;
                   20011:     }
1.1174    raeburn  20012:     return $plaintext;
                   20013: }
                   20014: 
1.1344    raeburn  20015: sub get_requested_shorturls {
1.1309    raeburn  20016:     my ($cdom,$cnum,$navmap) = @_;
                   20017:     return unless (ref($navmap));
1.1344    raeburn  20018:     my ($numnew,$errors);
1.1309    raeburn  20019:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   20020:     if (@toshorten) {
                   20021:         my (%maps,%resources,%titles);
                   20022:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   20023:                                                                'shorturls',$cdom,$cnum);
                   20024:         if (keys(%resources)) {
1.1344    raeburn  20025:             my %tocreate;
1.1309    raeburn  20026:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   20027:                 my $symb = $resources{$item};
                   20028:                 if ($symb) {
                   20029:                     $tocreate{$cnum.'&'.$symb} = 1;
                   20030:                 }
                   20031:             }
1.1344    raeburn  20032:             if (keys(%tocreate)) {
                   20033:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   20034:                                                       \%tocreate);
                   20035:             }
1.1309    raeburn  20036:         }
1.1344    raeburn  20037:     }
                   20038:     return ($numnew,$errors);
                   20039: }
                   20040: 
                   20041: sub make_short_symbs {
                   20042:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   20043:     my ($numnew,@errors);
                   20044:     if (ref($tocreateref) eq 'HASH') {
                   20045:         my %tocreate = %{$tocreateref};
1.1309    raeburn  20046:         if (keys(%tocreate)) {
                   20047:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   20048:             my $su = Short::URL->new(no_vowels => 1);
                   20049:             my $init = '';
                   20050:             my (%newunique,%addcourse,%courseonly,%failed);
                   20051:             # get lock on tiny db
                   20052:             my $now = time;
1.1344    raeburn  20053:             if ($lockuser eq '') {
                   20054:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   20055:             }
1.1309    raeburn  20056:             my $lockhash = {
1.1344    raeburn  20057:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  20058:                             };
                   20059:             my $tries = 0;
                   20060:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   20061:             my ($code,$error);
                   20062:             while (($gotlock ne 'ok') && ($tries<3)) {
                   20063:                 $tries ++;
                   20064:                 sleep 1;
1.1319    raeburn  20065:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  20066:             }
                   20067:             if ($gotlock eq 'ok') {
                   20068:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   20069:                                        \%addcourse,\%courseonly,\%failed);
                   20070:                 if (keys(%failed)) {
                   20071:                     my $numfailed = scalar(keys(%failed));
                   20072:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   20073:                 }
                   20074:                 if (keys(%newunique)) {
                   20075:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   20076:                     if ($putres eq 'ok') {
                   20077:                         $numnew = scalar(keys(%newunique));
                   20078:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   20079:                         unless ($newputres eq 'ok') {
                   20080:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   20081:                         }
                   20082:                     } else {
                   20083:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   20084:                     }
                   20085:                 }
                   20086:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   20087:                 unless ($dellockres eq 'ok') {
                   20088:                     push(@errors,&mt('error: could not release lockfile'));
                   20089:                 }
                   20090:             } else {
                   20091:                 push(@errors,&mt('error: could not obtain lockfile'));
                   20092:             }
                   20093:             if (keys(%courseonly)) {
                   20094:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   20095:                 if ($result ne 'ok') {
                   20096:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   20097:                 }
                   20098:             }
                   20099:         }
                   20100:     }
                   20101:     return ($numnew,\@errors);
                   20102: }
                   20103: 
                   20104: sub shorten_symbs {
                   20105:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   20106:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   20107:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   20108:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   20109:     my (%possibles,%collisions);
                   20110:     foreach my $key (keys(%{$tocreate})) {
                   20111:         my $num = String::CRC32::crc32($key);
                   20112:         my $tiny = $su->encode($num,$init);
                   20113:         if ($tiny) {
                   20114:             $possibles{$tiny} = $key;
                   20115:         }
                   20116:     }
                   20117:     if (!$init) {
                   20118:         $init = 1;
                   20119:     } else {
                   20120:         $init ++;
                   20121:     }
                   20122:     if (keys(%possibles)) {
                   20123:         my @posstiny = keys(%possibles);
                   20124:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   20125:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   20126:         if (keys(%currtiny)) {
                   20127:             foreach my $key (keys(%currtiny)) {
                   20128:                 next if ($currtiny{$key} eq '');
                   20129:                 if ($currtiny{$key} eq $possibles{$key}) {
                   20130:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   20131:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20132:                         $courseonly->{$tsymb} = $key;
                   20133:                     }
                   20134:                 } else {
                   20135:                     $collisions{$possibles{$key}} = 1;
                   20136:                 }
                   20137:                 delete($possibles{$key});
                   20138:             }
                   20139:         }
                   20140:         foreach my $key (keys(%possibles)) {
                   20141:             $newunique->{$key} = $possibles{$key};
                   20142:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   20143:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20144:                 $addcourse->{$tsymb} = $key;
                   20145:             }
                   20146:         }
                   20147:     }
                   20148:     if (keys(%collisions)) {
                   20149:         if ($init <5) {
                   20150:             if (!$init) {
                   20151:                 $init = 1;
                   20152:             } else {
                   20153:                 $init ++;
                   20154:             }
                   20155:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   20156:                                    $newunique,$addcourse,$courseonly,$failed);
                   20157:         } else {
                   20158:             foreach my $key (keys(%collisions)) {
                   20159:                 $failed->{$key} = 1;
                   20160:             }
                   20161:         }
                   20162:     }
                   20163:     return $init;
                   20164: }
                   20165: 
1.1328    raeburn  20166: sub is_nonframeable {
1.1329    raeburn  20167:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   20168:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  20169:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  20170: 
                   20171:     $remprotocol = lc($remprotocol);
                   20172:     $remhost = lc($remhost);
                   20173:     my $remport = 80;
                   20174:     if ($remprotocol eq 'https') {
                   20175:         $remport = 443;
                   20176:     }
1.1330    raeburn  20177:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  20178:     if ($cached) {
                   20179:         unless ($nocache) {
                   20180:             if ($result) {
                   20181:                 return 1;
                   20182:             } else {
                   20183:                 return 0;
                   20184:             }
                   20185:         }
                   20186:     }
1.1328    raeburn  20187:     my $uselink;
                   20188:     my $request = new HTTP::Request('HEAD',$url);
                   20189:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20190:     if ($response->is_success()) {
                   20191:         my $secpolicy = lc($response->header('content-security-policy'));
                   20192:         my $xframeop = lc($response->header('x-frame-options'));
                   20193:         $secpolicy =~ s/^\s+|\s+$//g;
                   20194:         $xframeop =~ s/^\s+|\s+$//g;
                   20195:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20196:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20197:             my ($origin,$protocol,$port);
                   20198:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20199:                 $port = $ENV{'SERVER_PORT'};
                   20200:             } else {
                   20201:                 $port = 80;
                   20202:             }
                   20203:             if ($absolute eq '') {
                   20204:                 $protocol = 'http:';
                   20205:                 if ($port == 443) {
                   20206:                     $protocol = 'https:';
                   20207:                 }
                   20208:                 $origin = $protocol.'//'.lc($hostname);
                   20209:             } else {
                   20210:                 $origin = lc($absolute);
                   20211:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20212:             }
                   20213:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20214:                 my $framepolicy = $1;
                   20215:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20216:                 my @policies = split(/\s+/,$framepolicy);
                   20217:                 if (@policies) {
                   20218:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20219:                         $uselink = 1;
                   20220:                     } else {
                   20221:                         $uselink = 1;
                   20222:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20223:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20224:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20225:                             undef($uselink);
                   20226:                         }
                   20227:                         if ($uselink) {
                   20228:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20229:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20230:                                     undef($uselink);
                   20231:                                 }
                   20232:                             }
                   20233:                         }
                   20234:                         if ($uselink) {
                   20235:                             my @possok;
                   20236:                             if ($ip ne '') {
                   20237:                                 push(@possok,$ip);
                   20238:                             }
                   20239:                             my $hoststr = '';
                   20240:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20241:                                 if ($hoststr eq '') {
                   20242:                                     $hoststr = $part;
                   20243:                                 } else {
                   20244:                                     $hoststr = "$part.$hoststr";
                   20245:                                 }
                   20246:                                 if ($hoststr eq $hostname) {
                   20247:                                     push(@possok,$hostname);
                   20248:                                 } else {
                   20249:                                     push(@possok,"*.$hoststr");
                   20250:                                 }
                   20251:                             }
                   20252:                             if (@possok) {
                   20253:                                 foreach my $poss (@possok) {
                   20254:                                     last if (!$uselink);
                   20255:                                     foreach my $policy (@policies) {
                   20256:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20257:                                             undef($uselink);
                   20258:                                             last;
                   20259:                                         }
                   20260:                                     }
                   20261:                                 }
                   20262:                             }
                   20263:                         }
                   20264:                     }
                   20265:                 }
                   20266:             } elsif ($xframeop ne '') {
                   20267:                 $uselink = 1;
                   20268:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20269:                 if (@policies) {
                   20270:                     unless (grep(/^deny$/,@policies)) {
                   20271:                         if ($origin ne '') {
                   20272:                             if (grep(/^sameorigin$/,@policies)) {
                   20273:                                 if ($remotehost eq $origin) {
                   20274:                                     undef($uselink);
                   20275:                                 }
                   20276:                             }
                   20277:                             if ($uselink) {
                   20278:                                 foreach my $policy (@policies) {
                   20279:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20280:                                         my $allowfrom = $1;
                   20281:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20282:                                             undef($uselink);
                   20283:                                             last;
                   20284:                                         }
                   20285:                                     }
                   20286:                                 }
                   20287:                             }
                   20288:                         }
                   20289:                     }
                   20290:                 }
                   20291:             }
                   20292:         }
                   20293:     }
1.1329    raeburn  20294:     if ($nocache) {
                   20295:         if ($cached) {
                   20296:             my $devalidate;
                   20297:             if ($uselink && !$result) {
                   20298:                 $devalidate = 1;
                   20299:             } elsif (!$uselink && $result) {
                   20300:                 $devalidate = 1;
                   20301:             }
                   20302:             if ($devalidate) {
                   20303:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20304:             }
                   20305:         }
                   20306:     } else {
                   20307:         if ($uselink) {
                   20308:             $result = 1;
                   20309:         } else {
                   20310:             $result = 0;
                   20311:         }
                   20312:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20313:     }
1.1328    raeburn  20314:     return $uselink;
                   20315: }
                   20316: 
1.1359    raeburn  20317: sub page_menu {
                   20318:     my ($menucolls,$menunum) = @_;
                   20319:     my %menu;
                   20320:     foreach my $item (split(/;/,$menucolls)) {
                   20321:         my ($num,$value) = split(/\%/,$item);
                   20322:         if ($num eq $menunum) {
                   20323:             my @entries = split(/\&/,$value);
                   20324:             foreach my $entry (@entries) {
                   20325:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20326:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20327:                     $menu{$name} = $fields;
                   20328:                 } else {
                   20329:                     my @shown;
                   20330:                     if ($fields =~ /,/) {
                   20331:                         @shown = split(/,/,$fields);
                   20332:                     } else {
                   20333:                         @shown = ($fields);
                   20334:                     }
                   20335:                     if (@shown) {
                   20336:                         foreach my $field (@shown) {
                   20337:                             next if ($field eq '');
                   20338:                             $menu{$field} = 1;
                   20339:                         }
                   20340:                     }
                   20341:                 }
                   20342:             }
                   20343:         }
                   20344:     }
                   20345:     return %menu;
                   20346: }
                   20347: 
1.112     bowersj2 20348: 1;
                   20349: __END__;
1.41      ng       20350: 

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