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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1472  ! raeburn     4: # $Id: loncommon.pm,v 1.1471 2025/03/18 18:57:28 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.579     raeburn  8176: span.LC_helpform_receipt_cat {
                   8177:   font-weight: bold;
                   8178: }
1.795     www      8179: 
1.424     albertel 8180: table.LC_group_priv_box {
                   8181:   background: white;
                   8182:   border: 1px solid black;
                   8183:   border-spacing: 1px;
                   8184: }
1.795     www      8185: 
1.424     albertel 8186: table.LC_group_priv_box td.LC_pick_box_title {
                   8187:   background: $tabbg;
                   8188:   font-weight: bold;
                   8189:   text-align: right;
                   8190:   width: 184px;
                   8191: }
1.795     www      8192: 
1.424     albertel 8193: table.LC_group_priv_box td.LC_groups_fixed {
                   8194:   background: $data_table_light;
                   8195:   text-align: center;
                   8196: }
1.795     www      8197: 
1.424     albertel 8198: table.LC_group_priv_box td.LC_groups_optional {
                   8199:   background: $data_table_dark;
                   8200:   text-align: center;
                   8201: }
1.795     www      8202: 
1.424     albertel 8203: table.LC_group_priv_box td.LC_groups_functionality {
                   8204:   background: $data_table_darker;
                   8205:   text-align: center;
                   8206:   font-weight: bold;
                   8207: }
1.795     www      8208: 
1.424     albertel 8209: table.LC_group_priv td {
                   8210:   text-align: left;
1.803     bisitz   8211:   padding: 0;
1.424     albertel 8212: }
                   8213: 
                   8214: .LC_navbuttons {
                   8215:   margin: 2ex 0ex 2ex 0ex;
                   8216: }
1.795     www      8217: 
1.423     albertel 8218: .LC_topic_bar {
                   8219:   font-weight: bold;
                   8220:   background: $tabbg;
1.918     wenzelju 8221:   margin: 1em 0em 1em 2em;
1.805     bisitz   8222:   padding: 3px;
1.918     wenzelju 8223:   font-size: 1.2em;
1.423     albertel 8224: }
1.795     www      8225: 
1.423     albertel 8226: .LC_topic_bar span {
1.918     wenzelju 8227:   left: 0.5em;
                   8228:   position: absolute;
1.423     albertel 8229:   vertical-align: middle;
1.918     wenzelju 8230:   font-size: 1.2em;
1.423     albertel 8231: }
1.795     www      8232: 
1.423     albertel 8233: table.LC_course_group_status {
                   8234:   margin: 20px;
                   8235: }
1.795     www      8236: 
1.423     albertel 8237: table.LC_status_selector td {
                   8238:   vertical-align: top;
                   8239:   text-align: center;
1.424     albertel 8240:   padding: 4px;
                   8241: }
1.795     www      8242: 
1.599     albertel 8243: div.LC_feedback_link {
1.616     albertel 8244:   clear: both;
1.829     kalberla 8245:   background: $sidebg;
1.779     bisitz   8246:   width: 100%;
1.829     kalberla 8247:   padding-bottom: 10px;
                   8248:   border: 1px $tabbg solid;
1.833     kalberla 8249:   height: 22px;
                   8250:   line-height: 22px;
                   8251:   padding-top: 5px;
                   8252: }
                   8253: 
                   8254: div.LC_feedback_link img {
                   8255:   height: 22px;
1.867     kalberla 8256:   vertical-align:middle;
1.829     kalberla 8257: }
                   8258: 
1.911     bisitz   8259: div.LC_feedback_link a {
1.829     kalberla 8260:   text-decoration: none;
1.489     raeburn  8261: }
1.795     www      8262: 
1.867     kalberla 8263: div.LC_comblock {
1.911     bisitz   8264:   display:inline;
1.867     kalberla 8265:   color:$font;
                   8266:   font-size:90%;
                   8267: }
                   8268: 
                   8269: div.LC_feedback_link div.LC_comblock {
                   8270:   padding-left:5px;
                   8271: }
                   8272: 
                   8273: div.LC_feedback_link div.LC_comblock a {
                   8274:   color:$font;
                   8275: }
                   8276: 
1.489     raeburn  8277: span.LC_feedback_link {
1.858     bisitz   8278:   /* background: $feedback_link_bg; */
1.599     albertel 8279:   font-size: larger;
                   8280: }
1.795     www      8281: 
1.599     albertel 8282: span.LC_message_link {
1.858     bisitz   8283:   /* background: $feedback_link_bg; */
1.599     albertel 8284:   font-size: larger;
                   8285:   position: absolute;
                   8286:   right: 1em;
1.489     raeburn  8287: }
1.421     albertel 8288: 
1.515     albertel 8289: table.LC_prior_tries {
1.524     albertel 8290:   border: 1px solid #000000;
                   8291:   border-collapse: separate;
                   8292:   border-spacing: 1px;
1.515     albertel 8293: }
1.523     albertel 8294: 
1.515     albertel 8295: table.LC_prior_tries td {
1.524     albertel 8296:   padding: 2px;
1.515     albertel 8297: }
1.523     albertel 8298: 
                   8299: .LC_answer_correct {
1.795     www      8300:   background: lightgreen;
                   8301:   color: darkgreen;
                   8302:   padding: 6px;
1.523     albertel 8303: }
1.795     www      8304: 
1.523     albertel 8305: .LC_answer_charged_try {
1.797     www      8306:   background: #FFAAAA;
1.795     www      8307:   color: darkred;
                   8308:   padding: 6px;
1.523     albertel 8309: }
1.795     www      8310: 
1.779     bisitz   8311: .LC_answer_not_charged_try,
1.523     albertel 8312: .LC_answer_no_grade,
                   8313: .LC_answer_late {
1.795     www      8314:   background: lightyellow;
1.523     albertel 8315:   color: black;
1.795     www      8316:   padding: 6px;
1.523     albertel 8317: }
1.795     www      8318: 
1.523     albertel 8319: .LC_answer_previous {
1.795     www      8320:   background: lightblue;
                   8321:   color: darkblue;
                   8322:   padding: 6px;
1.523     albertel 8323: }
1.795     www      8324: 
1.779     bisitz   8325: .LC_answer_no_message {
1.777     tempelho 8326:   background: #FFFFFF;
                   8327:   color: black;
1.795     www      8328:   padding: 6px;
1.779     bisitz   8329: }
1.795     www      8330: 
1.1334    raeburn  8331: .LC_answer_unknown,
                   8332: .LC_answer_warning {
1.779     bisitz   8333:   background: orange;
                   8334:   color: black;
1.795     www      8335:   padding: 6px;
1.777     tempelho 8336: }
1.795     www      8337: 
1.1467    raeburn  8338: span.LC_prob_status {
                   8339:   margin: 5px 0 0 0;
                   8340:   padding: 0 5px 0 0;
                   8341:   vertical-align: middle;
                   8342: }
                   8343: 
                   8344: div.LC_prob_status_outer {
                   8345:   display: inline-block;
                   8346:   margin: -5px 0 0 0;
                   8347:   padding: 0;
                   8348: }
                   8349: 
                   8350: div.LC_prob_status_inner {
                   8351:   display: inline-block;
                   8352:   margin: 0 5px 0 0;
                   8353:   padding: 5px;
1.1446    raeburn  8354: }
                   8355: 
1.1468    raeburn  8356: caption.LC_filesub_status {
                   8357:   text-align: left;
                   8358:   font-weight: bold;
                   8359: }
                   8360: 
1.1448    raeburn  8361: .LC_mail_actions {
                   8362:   float: left;
                   8363:   padding: 0;
                   8364:   margin: 6px;
                   8365: }
                   8366: 
                   8367: .LC_vertical_line {
                   8368:   width: 1px;
                   8369:   background-color: black;
                   8370:   height: 4em;
                   8371:   float: left;
                   8372:   margin: 0;
                   8373:   padding: 0;
                   8374: }
                   8375: 
1.529     albertel 8376: span.LC_prior_numerical,
                   8377: span.LC_prior_string,
                   8378: span.LC_prior_custom,
                   8379: span.LC_prior_reaction,
                   8380: span.LC_prior_math {
1.925     bisitz   8381:   font-family: $mono;
1.523     albertel 8382:   white-space: pre;
                   8383: }
                   8384: 
1.525     albertel 8385: span.LC_prior_string {
1.925     bisitz   8386:   font-family: $mono;
1.525     albertel 8387:   white-space: pre;
                   8388: }
                   8389: 
1.523     albertel 8390: table.LC_prior_option {
                   8391:   width: 100%;
                   8392:   border-collapse: collapse;
                   8393: }
1.795     www      8394: 
1.911     bisitz   8395: table.LC_prior_rank,
1.795     www      8396: table.LC_prior_match {
1.528     albertel 8397:   border-collapse: collapse;
                   8398: }
1.795     www      8399: 
1.528     albertel 8400: table.LC_prior_option tr td,
                   8401: table.LC_prior_rank tr td,
                   8402: table.LC_prior_match tr td {
1.524     albertel 8403:   border: 1px solid #000000;
1.515     albertel 8404: }
                   8405: 
1.855     bisitz   8406: .LC_nobreak {
1.544     albertel 8407:   white-space: nowrap;
1.519     raeburn  8408: }
                   8409: 
1.576     raeburn  8410: span.LC_cusr_emph {
                   8411:   font-style: italic;
                   8412: }
                   8413: 
1.633     raeburn  8414: span.LC_cusr_subheading {
                   8415:   font-weight: normal;
                   8416:   font-size: 85%;
                   8417: }
                   8418: 
1.861     bisitz   8419: div.LC_docs_entry_move {
1.859     bisitz   8420:   border: 1px solid #BBBBBB;
1.545     albertel 8421:   background: #DDDDDD;
1.861     bisitz   8422:   width: 22px;
1.859     bisitz   8423:   padding: 1px;
                   8424:   margin: 0;
1.545     albertel 8425: }
                   8426: 
1.861     bisitz   8427: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8428: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8429:   font-size: x-small;
                   8430: }
1.795     www      8431: 
1.861     bisitz   8432: .LC_docs_entry_parameter {
                   8433:   white-space: nowrap;
                   8434: }
                   8435: 
1.544     albertel 8436: .LC_docs_copy {
1.545     albertel 8437:   color: #000099;
1.544     albertel 8438: }
1.795     www      8439: 
1.544     albertel 8440: .LC_docs_cut {
1.545     albertel 8441:   color: #550044;
1.544     albertel 8442: }
1.795     www      8443: 
1.544     albertel 8444: .LC_docs_rename {
1.545     albertel 8445:   color: #009900;
1.544     albertel 8446: }
1.795     www      8447: 
1.544     albertel 8448: .LC_docs_remove {
1.545     albertel 8449:   color: #990000;
                   8450: }
                   8451: 
1.1284    raeburn  8452: .LC_docs_alias {
                   8453:   color: #440055;  
                   8454: }
                   8455: 
1.1286    raeburn  8456: .LC_domprefs_email,
1.1284    raeburn  8457: .LC_docs_alias_name,
1.547     albertel 8458: .LC_docs_reinit_warn,
                   8459: .LC_docs_ext_edit {
                   8460:   font-size: x-small;
                   8461: }
                   8462: 
1.545     albertel 8463: table.LC_docs_adddocs td,
                   8464: table.LC_docs_adddocs th {
                   8465:   border: 1px solid #BBBBBB;
                   8466:   padding: 4px;
                   8467:   background: #DDDDDD;
1.543     albertel 8468: }
                   8469: 
1.584     albertel 8470: table.LC_sty_begin {
                   8471:   background: #BBFFBB;
                   8472: }
1.795     www      8473: 
1.584     albertel 8474: table.LC_sty_end {
                   8475:   background: #FFBBBB;
                   8476: }
                   8477: 
1.589     raeburn  8478: table.LC_double_column {
1.803     bisitz   8479:   border-width: 0;
1.589     raeburn  8480:   border-collapse: collapse;
                   8481:   width: 100%;
                   8482:   padding: 2px;
                   8483: }
                   8484: 
                   8485: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8486:   top: 2px;
1.589     raeburn  8487:   left: 2px;
                   8488:   width: 47%;
                   8489:   vertical-align: top;
                   8490: }
                   8491: 
                   8492: table.LC_double_column tr td.LC_right_col {
                   8493:   top: 2px;
1.779     bisitz   8494:   right: 2px;
1.589     raeburn  8495:   width: 47%;
                   8496:   vertical-align: top;
                   8497: }
                   8498: 
1.591     raeburn  8499: div.LC_left_float {
                   8500:   float: left;
                   8501:   padding-right: 5%;
1.597     albertel 8502:   padding-bottom: 4px;
1.591     raeburn  8503: }
                   8504: 
                   8505: div.LC_clear_float_header {
1.597     albertel 8506:   padding-bottom: 2px;
1.591     raeburn  8507: }
                   8508: 
                   8509: div.LC_clear_float_footer {
1.597     albertel 8510:   padding-top: 10px;
1.591     raeburn  8511:   clear: both;
                   8512: }
                   8513: 
1.597     albertel 8514: div.LC_grade_show_user {
1.941     bisitz   8515: /*  border-left: 5px solid $sidebg; */
                   8516:   border-top: 5px solid #000000;
                   8517:   margin: 50px 0 0 0;
1.936     bisitz   8518:   padding: 15px 0 5px 10px;
1.597     albertel 8519: }
1.795     www      8520: 
1.936     bisitz   8521: div.LC_grade_show_user_odd_row {
1.941     bisitz   8522: /*  border-left: 5px solid #000000; */
                   8523: }
                   8524: 
                   8525: div.LC_grade_show_user div.LC_Box {
                   8526:   margin-right: 50px;
1.597     albertel 8527: }
                   8528: 
1.1461    raeburn  8529: div.LC_grade_show_user div.LC_Box table tr th {
                   8530:   font-weight: normal;
                   8531: }
                   8532: 
1.597     albertel 8533: div.LC_grade_submissions,
                   8534: div.LC_grade_message_center,
1.936     bisitz   8535: div.LC_grade_info_links {
1.597     albertel 8536:   margin: 5px;
                   8537:   width: 99%;
                   8538:   background: #FFFFFF;
                   8539: }
1.795     www      8540: 
1.597     albertel 8541: div.LC_grade_submissions_header,
1.936     bisitz   8542: div.LC_grade_message_center_header {
1.705     tempelho 8543:   font-weight: bold;
                   8544:   font-size: large;
1.597     albertel 8545: }
1.795     www      8546: 
1.597     albertel 8547: div.LC_grade_submissions_body,
1.936     bisitz   8548: div.LC_grade_message_center_body {
1.597     albertel 8549:   border: 1px solid black;
                   8550:   width: 99%;
                   8551:   background: #FFFFFF;
                   8552: }
1.795     www      8553: 
1.613     albertel 8554: table.LC_scantron_action {
                   8555:   width: 100%;
                   8556: }
1.795     www      8557: 
1.613     albertel 8558: table.LC_scantron_action tr th {
1.698     harmsja  8559:   font-weight:bold;
                   8560:   font-style:normal;
1.613     albertel 8561: }
1.795     www      8562: 
1.1461    raeburn  8563: div.LC_edit_problem_daxe_header {
                   8564:   padding: 3px;
                   8565:   background: $tabbg;
                   8566:   z-index: 100;
                   8567: }
                   8568: 
1.779     bisitz   8569: .LC_edit_problem_header,
1.614     albertel 8570: div.LC_edit_problem_footer {
1.705     tempelho 8571:   font-weight: normal;
                   8572:   font-size:  medium;
1.602     albertel 8573:   margin: 2px;
1.1060    bisitz   8574:   background-color: $sidebg;
1.600     albertel 8575: }
1.795     www      8576: 
1.600     albertel 8577: div.LC_edit_problem_header,
1.602     albertel 8578: div.LC_edit_problem_header div,
1.614     albertel 8579: div.LC_edit_problem_footer,
                   8580: div.LC_edit_problem_footer div,
1.602     albertel 8581: div.LC_edit_problem_editxml_header,
                   8582: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8583:   z-index: 100;
1.600     albertel 8584: }
1.795     www      8585: 
1.600     albertel 8586: div.LC_edit_problem_header_title {
1.705     tempelho 8587:   font-weight: bold;
                   8588:   font-size: larger;
1.602     albertel 8589:   background: $tabbg;
                   8590:   padding: 3px;
1.1060    bisitz   8591:   margin: 0 0 5px 0;
1.602     albertel 8592: }
1.795     www      8593: 
1.602     albertel 8594: table.LC_edit_problem_header_title {
                   8595:   width: 100%;
1.600     albertel 8596:   background: $tabbg;
1.602     albertel 8597: }
                   8598: 
1.1205    golterma 8599: div.LC_edit_actionbar {
                   8600:     background-color: $sidebg;
1.1218    droeschl 8601:     margin: 0;
                   8602:     padding: 0;
                   8603:     line-height: 200%;
1.602     albertel 8604: }
1.795     www      8605: 
1.1218    droeschl 8606: div.LC_edit_actionbar div{
                   8607:     padding: 0;
                   8608:     margin: 0;
                   8609:     display: inline-block;
1.600     albertel 8610: }
1.795     www      8611: 
1.1124    bisitz   8612: .LC_edit_opt {
                   8613:   padding-left: 1em;
                   8614:   white-space: nowrap;
                   8615: }
                   8616: 
1.1152    golterma 8617: .LC_edit_problem_latexhelper{
                   8618:     text-align: right;
                   8619: }
                   8620: 
                   8621: #LC_edit_problem_colorful div{
                   8622:     margin-left: 40px;
                   8623: }
                   8624: 
1.1205    golterma 8625: #LC_edit_problem_codemirror div{
                   8626:     margin-left: 0px;
                   8627: }
                   8628: 
1.911     bisitz   8629: img.stift {
1.803     bisitz   8630:   border-width: 0;
                   8631:   vertical-align: middle;
1.677     riegler  8632: }
1.680     riegler  8633: 
1.1460    raeburn  8634: div.LC_mainmenu {
                   8635:   margin: 3px 2px 2px 1px;
                   8636:   float: left;
1.777     tempelho 8637: }
1.795     www      8638: 
1.716     raeburn  8639: div.LC_createcourse {
1.911     bisitz   8640:   margin: 10px 10px 10px 10px;
1.716     raeburn  8641: }
                   8642: 
1.917     raeburn  8643: .LC_dccid {
1.1130    raeburn  8644:   float: right;
1.917     raeburn  8645:   margin: 0.2em 0 0 0;
                   8646:   padding: 0;
                   8647:   font-size: 90%;
                   8648:   display:none;
                   8649: }
                   8650: 
1.897     wenzelju 8651: ol.LC_primary_menu a:hover,
1.721     harmsja  8652: ol#LC_MenuBreadcrumbs a:hover,
                   8653: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8654: ul#LC_secondary_menu a:hover,
1.721     harmsja  8655: .LC_FormSectionClearButton input:hover
1.795     www      8656: ul.LC_TabContent   li:hover a {
1.952     onken    8657:   color:$button_hover;
1.911     bisitz   8658:   text-decoration:none;
1.693     droeschl 8659: }
                   8660: 
1.779     bisitz   8661: h1 {
1.911     bisitz   8662:   padding: 0;
                   8663:   line-height:130%;
1.693     droeschl 8664: }
1.698     harmsja  8665: 
1.911     bisitz   8666: h2,
                   8667: h3,
                   8668: h4,
                   8669: h5,
                   8670: h6 {
                   8671:   margin: 5px 0 5px 0;
                   8672:   padding: 0;
                   8673:   line-height:130%;
1.693     droeschl 8674: }
1.795     www      8675: 
                   8676: .LC_hcell {
1.911     bisitz   8677:   padding:3px 15px 3px 15px;
                   8678:   margin: 0;
                   8679:   background-color:$tabbg;
                   8680:   color:$fontmenu;
                   8681:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8682: }
1.795     www      8683: 
1.840     bisitz   8684: .LC_Box > .LC_hcell {
1.911     bisitz   8685:   margin: 0 -10px 10px -10px;
1.835     bisitz   8686: }
                   8687: 
1.721     harmsja  8688: .LC_noBorder {
1.911     bisitz   8689:   border: 0;
1.698     harmsja  8690: }
1.693     droeschl 8691: 
1.721     harmsja  8692: .LC_FormSectionClearButton input {
1.911     bisitz   8693:   background-color:transparent;
                   8694:   border: none;
                   8695:   cursor:pointer;
                   8696:   text-decoration:underline;
1.693     droeschl 8697: }
1.763     bisitz   8698: 
                   8699: .LC_help_open_topic {
1.911     bisitz   8700:   color: #FFFFFF;
                   8701:   background-color: #EEEEFF;
                   8702:   margin: 1px;
                   8703:   padding: 4px;
                   8704:   border: 1px solid #000033;
                   8705:   white-space: nowrap;
                   8706:   /* vertical-align: middle; */
1.759     neumanie 8707: }
1.693     droeschl 8708: 
1.911     bisitz   8709: dl,
                   8710: ul,
                   8711: div,
                   8712: fieldset {
                   8713:   margin: 10px 10px 10px 0;
                   8714:   /* overflow: hidden; */
1.693     droeschl 8715: }
1.795     www      8716: 
1.1404    raeburn  8717: fieldset#LC_selectuser {
1.1460    raeburn  8718:   margin: -1px 0 0 0;
                   8719:   padding: 0;
                   8720:   border: 0;
1.1404    raeburn  8721: }
                   8722: 
1.1211    raeburn  8723: article.geogebraweb div {
                   8724:     margin: 0;
                   8725: }
                   8726: 
1.838     bisitz   8727: fieldset > legend {
1.911     bisitz   8728:   font-weight: bold;
                   8729:   padding: 0 5px 0 5px;
1.838     bisitz   8730: }
                   8731: 
1.813     bisitz   8732: #LC_nav_bar {
1.911     bisitz   8733:   float: left;
1.995     raeburn  8734:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8735:   margin: 0 0 2px 0;
1.807     droeschl 8736: }
                   8737: 
1.916     droeschl 8738: #LC_realm {
                   8739:   margin: 0.2em 0 0 0;
                   8740:   padding: 0;
                   8741:   font-weight: bold;
                   8742:   text-align: center;
1.995     raeburn  8743:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8744: }
                   8745: 
1.911     bisitz   8746: #LC_nav_bar em {
                   8747:   font-weight: bold;
                   8748:   font-style: normal;
1.807     droeschl 8749: }
                   8750: 
1.897     wenzelju 8751: ol.LC_primary_menu {
1.934     droeschl 8752:   margin: 0;
1.1076    raeburn  8753:   padding: 0;
1.807     droeschl 8754: }
                   8755: 
1.852     droeschl 8756: ol#LC_PathBreadcrumbs {
1.911     bisitz   8757:   margin: 0;
1.693     droeschl 8758: }
                   8759: 
1.897     wenzelju 8760: ol.LC_primary_menu li {
1.1076    raeburn  8761:   color: RGB(80, 80, 80);
                   8762:   vertical-align: middle;
                   8763:   text-align: left;
                   8764:   list-style: none;
1.1205    golterma 8765:   position: relative;
1.1076    raeburn  8766:   float: left;
1.1205    golterma 8767:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8768:   line-height: 1.5em;
1.1076    raeburn  8769: }
                   8770: 
1.1205    golterma 8771: ol.LC_primary_menu li a,
                   8772: ol.LC_primary_menu li p {
1.1076    raeburn  8773:   display: block;
                   8774:   margin: 0;
                   8775:   padding: 0 5px 0 10px;
                   8776:   text-decoration: none;
                   8777: }
                   8778: 
1.1205    golterma 8779: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8780:   display: inline-block;
                   8781:   width: 95%;
                   8782:   text-align: left;
                   8783: }
                   8784: 
                   8785: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8786:   display: inline-block;	
                   8787:   width: 5%;
                   8788:   float: right;
                   8789:   text-align: right;
                   8790:   font-size: 70%;
                   8791: }
                   8792: 
                   8793: ol.LC_primary_menu ul {
1.1076    raeburn  8794:   display: none;
1.1205    golterma 8795:   width: 15em;
1.1076    raeburn  8796:   background-color: $data_table_light;
1.1205    golterma 8797:   position: absolute;
                   8798:   top: 100%;
1.1076    raeburn  8799: }
                   8800: 
1.1205    golterma 8801: ol.LC_primary_menu ul ul {
                   8802:   left: 100%;
                   8803:   top: 0;
                   8804: }
                   8805: 
                   8806: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8807:   display: block;
                   8808:   position: absolute;
                   8809:   margin: 0;
                   8810:   padding: 0;
1.1078    raeburn  8811:   z-index: 2;
1.1076    raeburn  8812: }
                   8813: 
                   8814: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8815: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8816:   font-size: 90%;
1.911     bisitz   8817:   vertical-align: top;
1.1076    raeburn  8818:   float: none;
1.1079    raeburn  8819:   border-left: 1px solid black;
                   8820:   border-right: 1px solid black;
1.1205    golterma 8821: /* A dark bottom border to visualize different menu options; 
                   8822: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8823:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8824: }
                   8825: 
1.1205    golterma 8826: ol.LC_primary_menu li li p:hover {
                   8827:   color:$button_hover;
                   8828:   text-decoration:none;
                   8829:   background-color:$data_table_dark;
1.1076    raeburn  8830: }
                   8831: 
                   8832: ol.LC_primary_menu li li a:hover {
                   8833:    color:$button_hover;
                   8834:    background-color:$data_table_dark;
1.693     droeschl 8835: }
                   8836: 
1.1205    golterma 8837: /* Font-size equal to the size of the predecessors*/
                   8838: ol.LC_primary_menu li:hover li li {
                   8839:   font-size: 100%;
                   8840: }
                   8841: 
1.897     wenzelju 8842: ol.LC_primary_menu li img {
1.911     bisitz   8843:   vertical-align: bottom;
1.934     droeschl 8844:   height: 1.1em;
1.1077    raeburn  8845:   margin: 0.2em 0 0 0;
1.693     droeschl 8846: }
                   8847: 
1.897     wenzelju 8848: ol.LC_primary_menu a {
1.911     bisitz   8849:   color: RGB(80, 80, 80);
                   8850:   text-decoration: none;
1.693     droeschl 8851: }
1.795     www      8852: 
1.949     droeschl 8853: ol.LC_primary_menu a.LC_new_message {
                   8854:   font-weight:bold;
                   8855:   color: darkred;
                   8856: }
                   8857: 
1.975     raeburn  8858: ol.LC_docs_parameters {
                   8859:   margin-left: 0;
                   8860:   padding: 0;
                   8861:   list-style: none;
                   8862: }
                   8863: 
                   8864: ol.LC_docs_parameters li {
                   8865:   margin: 0;
                   8866:   padding-right: 20px;
                   8867:   display: inline;
                   8868: }
                   8869: 
1.976     raeburn  8870: ol.LC_docs_parameters li:before {
                   8871:   content: "\\002022 \\0020";
                   8872: }
                   8873: 
                   8874: li.LC_docs_parameters_title {
                   8875:   font-weight: bold;
                   8876: }
                   8877: 
                   8878: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8879:   content: "";
                   8880: }
                   8881: 
1.897     wenzelju 8882: ul#LC_secondary_menu {
1.1107    raeburn  8883:   clear: right;
1.911     bisitz   8884:   color: $fontmenu;
                   8885:   background: $tabbg;
                   8886:   list-style: none;
                   8887:   padding: 0;
                   8888:   margin: 0;
                   8889:   width: 100%;
1.995     raeburn  8890:   text-align: left;
1.1107    raeburn  8891:   float: left;
1.808     droeschl 8892: }
                   8893: 
1.897     wenzelju 8894: ul#LC_secondary_menu li {
1.911     bisitz   8895:   font-weight: bold;
                   8896:   line-height: 1.8em;
1.1107    raeburn  8897:   border-right: 1px solid black;
                   8898:   float: left;
                   8899: }
                   8900: 
                   8901: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8902:   background-color: $data_table_light;
                   8903: }
                   8904: 
                   8905: ul#LC_secondary_menu li a {
1.911     bisitz   8906:   padding: 0 0.8em;
1.1107    raeburn  8907: }
                   8908: 
                   8909: ul#LC_secondary_menu li ul {
                   8910:   display: none;
                   8911: }
                   8912: 
                   8913: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8914:   display: block;
                   8915:   position: absolute;
                   8916:   margin: 0;
                   8917:   padding: 0;
                   8918:   list-style:none;
                   8919:   float: none;
                   8920:   background-color: $data_table_light;
                   8921:   z-index: 2;
                   8922:   margin-left: -1px;
                   8923: }
                   8924: 
                   8925: ul#LC_secondary_menu li ul li {
                   8926:   font-size: 90%;
                   8927:   vertical-align: top;
                   8928:   border-left: 1px solid black;
1.911     bisitz   8929:   border-right: 1px solid black;
1.1119    raeburn  8930:   background-color: $data_table_light;
1.1107    raeburn  8931:   list-style:none;
                   8932:   float: none;
                   8933: }
                   8934: 
                   8935: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8936:   background-color: $data_table_dark;
1.807     droeschl 8937: }
                   8938: 
1.847     tempelho 8939: ul.LC_TabContent {
1.911     bisitz   8940:   display:block;
                   8941:   background: $sidebg;
                   8942:   border-bottom: solid 1px $lg_border_color;
                   8943:   list-style:none;
1.1020    raeburn  8944:   margin: -1px -10px 0 -10px;
1.911     bisitz   8945:   padding: 0;
1.693     droeschl 8946: }
                   8947: 
1.795     www      8948: ul.LC_TabContent li,
                   8949: ul.LC_TabContentBigger li {
1.911     bisitz   8950:   float:left;
1.741     harmsja  8951: }
1.795     www      8952: 
1.897     wenzelju 8953: ul#LC_secondary_menu li a {
1.911     bisitz   8954:   color: $fontmenu;
                   8955:   text-decoration: none;
1.693     droeschl 8956: }
1.795     www      8957: 
1.721     harmsja  8958: ul.LC_TabContent {
1.952     onken    8959:   min-height:20px;
1.721     harmsja  8960: }
1.795     www      8961: 
                   8962: ul.LC_TabContent li {
1.911     bisitz   8963:   vertical-align:middle;
1.959     onken    8964:   padding: 0 16px 0 10px;
1.911     bisitz   8965:   background-color:$tabbg;
                   8966:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8967:   border-left: solid 1px $font;
1.721     harmsja  8968: }
1.795     www      8969: 
1.847     tempelho 8970: ul.LC_TabContent .right {
1.911     bisitz   8971:   float:right;
1.847     tempelho 8972: }
                   8973: 
1.911     bisitz   8974: ul.LC_TabContent li a,
                   8975: ul.LC_TabContent li {
                   8976:   color:rgb(47,47,47);
                   8977:   text-decoration:none;
                   8978:   font-size:95%;
                   8979:   font-weight:bold;
1.952     onken    8980:   min-height:20px;
                   8981: }
                   8982: 
1.959     onken    8983: ul.LC_TabContent li a:hover,
                   8984: ul.LC_TabContent li a:focus {
1.952     onken    8985:   color: $button_hover;
1.959     onken    8986:   background:none;
                   8987:   outline:none;
1.952     onken    8988: }
                   8989: 
                   8990: ul.LC_TabContent li:hover {
                   8991:   color: $button_hover;
                   8992:   cursor:pointer;
1.721     harmsja  8993: }
1.795     www      8994: 
1.911     bisitz   8995: ul.LC_TabContent li.active {
1.952     onken    8996:   color: $font;
1.911     bisitz   8997:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8998:   border-bottom:solid 1px #FFFFFF;
                   8999:   cursor: default;
1.744     ehlerst  9000: }
1.795     www      9001: 
1.959     onken    9002: ul.LC_TabContent li.active a {
                   9003:   color:$font;
                   9004:   background:#FFFFFF;
                   9005:   outline: none;
                   9006: }
1.1047    raeburn  9007: 
                   9008: ul.LC_TabContent li.goback {
                   9009:   float: left;
                   9010:   border-left: none;
                   9011: }
                   9012: 
1.870     tempelho 9013: #maincoursedoc {
1.911     bisitz   9014:   clear:both;
1.870     tempelho 9015: }
                   9016: 
                   9017: ul.LC_TabContentBigger {
1.911     bisitz   9018:   display:block;
                   9019:   list-style:none;
                   9020:   padding: 0;
1.870     tempelho 9021: }
                   9022: 
1.795     www      9023: ul.LC_TabContentBigger li {
1.911     bisitz   9024:   vertical-align:bottom;
                   9025:   height: 30px;
                   9026:   font-size:110%;
                   9027:   font-weight:bold;
                   9028:   color: #737373;
1.841     tempelho 9029: }
                   9030: 
1.957     onken    9031: ul.LC_TabContentBigger li.active {
                   9032:   position: relative;
                   9033:   top: 1px;
                   9034: }
                   9035: 
1.870     tempelho 9036: ul.LC_TabContentBigger li a {
1.911     bisitz   9037:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   9038:   height: 30px;
                   9039:   line-height: 30px;
                   9040:   text-align: center;
                   9041:   display: block;
                   9042:   text-decoration: none;
1.958     onken    9043:   outline: none;  
1.741     harmsja  9044: }
1.795     www      9045: 
1.870     tempelho 9046: ul.LC_TabContentBigger li.active a {
1.911     bisitz   9047:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   9048:   color:$font;
1.744     ehlerst  9049: }
1.795     www      9050: 
1.870     tempelho 9051: ul.LC_TabContentBigger li b {
1.911     bisitz   9052:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   9053:   display: block;
                   9054:   float: left;
                   9055:   padding: 0 30px;
1.957     onken    9056:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 9057: }
                   9058: 
1.956     onken    9059: ul.LC_TabContentBigger li:hover b {
                   9060:   color:$button_hover;
                   9061: }
                   9062: 
1.870     tempelho 9063: ul.LC_TabContentBigger li.active b {
1.911     bisitz   9064:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   9065:   color:$font;
1.957     onken    9066:   border: 0;
1.741     harmsja  9067: }
1.693     droeschl 9068: 
1.870     tempelho 9069: 
1.862     bisitz   9070: ul.LC_CourseBreadcrumbs {
                   9071:   background: $sidebg;
1.1020    raeburn  9072:   height: 2em;
1.862     bisitz   9073:   padding-left: 10px;
1.1020    raeburn  9074:   margin: 0;
1.862     bisitz   9075:   list-style-position: inside;
                   9076: }
                   9077: 
1.911     bisitz   9078: ol#LC_MenuBreadcrumbs,
1.862     bisitz   9079: ol#LC_PathBreadcrumbs {
1.911     bisitz   9080:   padding-left: 10px;
                   9081:   margin: 0;
1.933     droeschl 9082:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 9083: }
                   9084: 
1.911     bisitz   9085: ol#LC_MenuBreadcrumbs li,
                   9086: ol#LC_PathBreadcrumbs li,
1.862     bisitz   9087: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   9088:   display: inline;
1.933     droeschl 9089:   white-space: normal;  
1.693     droeschl 9090: }
                   9091: 
1.823     bisitz   9092: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   9093: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   9094:   text-decoration: none;
                   9095:   font-size:90%;
1.693     droeschl 9096: }
1.795     www      9097: 
1.969     droeschl 9098: ol#LC_MenuBreadcrumbs h1 {
                   9099:   display: inline;
                   9100:   font-size: 90%;
                   9101:   line-height: 2.5em;
                   9102:   margin: 0;
                   9103:   padding: 0;
                   9104: }
                   9105: 
1.795     www      9106: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   9107:   text-decoration:none;
                   9108:   font-size:100%;
                   9109:   font-weight:bold;
1.693     droeschl 9110: }
1.795     www      9111: 
1.840     bisitz   9112: .LC_Box {
1.911     bisitz   9113:   border: solid 1px $lg_border_color;
                   9114:   padding: 0 10px 10px 10px;
1.746     neumanie 9115: }
1.795     www      9116: 
1.1020    raeburn  9117: .LC_DocsBox {
                   9118:   border: solid 1px $lg_border_color;
                   9119:   padding: 0 0 10px 10px;
                   9120: }
                   9121: 
1.795     www      9122: .LC_AboutMe_Image {
1.911     bisitz   9123:   float:left;
                   9124:   margin-right:10px;
1.747     neumanie 9125: }
1.795     www      9126: 
                   9127: .LC_Clear_AboutMe_Image {
1.911     bisitz   9128:   clear:left;
1.747     neumanie 9129: }
1.795     www      9130: 
1.721     harmsja  9131: dl.LC_ListStyleClean dt {
1.911     bisitz   9132:   padding-right: 5px;
                   9133:   display: table-header-group;
1.693     droeschl 9134: }
                   9135: 
1.721     harmsja  9136: dl.LC_ListStyleClean dd {
1.911     bisitz   9137:   display: table-row;
1.693     droeschl 9138: }
                   9139: 
1.721     harmsja  9140: .LC_ListStyleClean,
                   9141: .LC_ListStyleSimple,
                   9142: .LC_ListStyleNormal,
1.795     www      9143: .LC_ListStyleSpecial {
1.911     bisitz   9144:   /* display:block; */
                   9145:   list-style-position: inside;
                   9146:   list-style-type: none;
                   9147:   overflow: hidden;
                   9148:   padding: 0;
1.693     droeschl 9149: }
                   9150: 
1.721     harmsja  9151: .LC_ListStyleSimple li,
                   9152: .LC_ListStyleSimple dd,
                   9153: .LC_ListStyleNormal li,
                   9154: .LC_ListStyleNormal dd,
                   9155: .LC_ListStyleSpecial li,
1.795     www      9156: .LC_ListStyleSpecial dd {
1.911     bisitz   9157:   margin: 0;
                   9158:   padding: 5px 5px 5px 10px;
                   9159:   clear: both;
1.693     droeschl 9160: }
                   9161: 
1.721     harmsja  9162: .LC_ListStyleClean li,
                   9163: .LC_ListStyleClean dd {
1.911     bisitz   9164:   padding-top: 0;
                   9165:   padding-bottom: 0;
1.693     droeschl 9166: }
                   9167: 
1.721     harmsja  9168: .LC_ListStyleSimple dd,
1.795     www      9169: .LC_ListStyleSimple li {
1.911     bisitz   9170:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9171: }
                   9172: 
1.721     harmsja  9173: .LC_ListStyleSpecial li,
                   9174: .LC_ListStyleSpecial dd {
1.911     bisitz   9175:   list-style-type: none;
                   9176:   background-color: RGB(220, 220, 220);
                   9177:   margin-bottom: 4px;
1.693     droeschl 9178: }
                   9179: 
1.721     harmsja  9180: table.LC_SimpleTable {
1.911     bisitz   9181:   margin:5px;
                   9182:   border:solid 1px $lg_border_color;
1.795     www      9183: }
1.693     droeschl 9184: 
1.721     harmsja  9185: table.LC_SimpleTable tr {
1.911     bisitz   9186:   padding: 0;
                   9187:   border:solid 1px $lg_border_color;
1.693     droeschl 9188: }
1.795     www      9189: 
                   9190: table.LC_SimpleTable thead {
1.911     bisitz   9191:   background:rgb(220,220,220);
1.693     droeschl 9192: }
                   9193: 
1.721     harmsja  9194: div.LC_columnSection {
1.911     bisitz   9195:   display: block;
                   9196:   clear: both;
                   9197:   overflow: hidden;
                   9198:   margin: 0;
1.693     droeschl 9199: }
                   9200: 
1.721     harmsja  9201: div.LC_columnSection>* {
1.911     bisitz   9202:   float: left;
                   9203:   margin: 10px 20px 10px 0;
                   9204:   overflow:hidden;
1.693     droeschl 9205: }
1.721     harmsja  9206: 
1.795     www      9207: table em {
1.911     bisitz   9208:   font-weight: bold;
                   9209:   font-style: normal;
1.748     schulted 9210: }
1.795     www      9211: 
1.779     bisitz   9212: table.LC_tableBrowseRes,
1.795     www      9213: table.LC_tableOfContent {
1.911     bisitz   9214:   border:none;
                   9215:   border-spacing: 1px;
                   9216:   padding: 3px;
                   9217:   background-color: #FFFFFF;
                   9218:   font-size: 90%;
1.753     droeschl 9219: }
1.789     droeschl 9220: 
1.911     bisitz   9221: table.LC_tableOfContent {
                   9222:   border-collapse: collapse;
1.789     droeschl 9223: }
                   9224: 
1.771     droeschl 9225: table.LC_tableBrowseRes a,
1.768     schulted 9226: table.LC_tableOfContent a {
1.911     bisitz   9227:   background-color: transparent;
                   9228:   text-decoration: none;
1.753     droeschl 9229: }
                   9230: 
1.795     www      9231: table.LC_tableOfContent img {
1.911     bisitz   9232:   border: none;
                   9233:   height: 1.3em;
                   9234:   vertical-align: text-bottom;
                   9235:   margin-right: 0.3em;
1.753     droeschl 9236: }
1.757     schulted 9237: 
1.795     www      9238: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9239:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9240: }
                   9241: 
1.795     www      9242: a#LC_content_toolbar_everything {
1.911     bisitz   9243:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9244: }
                   9245: 
1.795     www      9246: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9247:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9248: }
                   9249: 
1.795     www      9250: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9251:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9252: }
                   9253: 
1.795     www      9254: a#LC_content_toolbar_changefolder {
1.911     bisitz   9255:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9256: }
                   9257: 
1.795     www      9258: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9259:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9260: }
                   9261: 
1.1043    raeburn  9262: a#LC_content_toolbar_edittoplevel {
                   9263:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9264: }
                   9265: 
1.1384    raeburn  9266: a#LC_content_toolbar_printout {
                   9267:   background-image:url(/res/adm/pages/printout.gif);
                   9268: }
                   9269: 
1.795     www      9270: ul#LC_toolbar li a:hover {
1.911     bisitz   9271:   background-position: bottom center;
1.757     schulted 9272: }
                   9273: 
1.795     www      9274: ul#LC_toolbar {
1.911     bisitz   9275:   padding: 0;
                   9276:   margin: 2px;
                   9277:   list-style:none;
1.1449    raeburn  9278:   display:inline;
1.911     bisitz   9279:   background-color:white;
1.1082    raeburn  9280:   overflow: auto;
1.757     schulted 9281: }
                   9282: 
1.795     www      9283: ul#LC_toolbar li {
1.911     bisitz   9284:   border:1px solid white;
                   9285:   padding: 0;
                   9286:   margin: 0;
                   9287:   float: left;
                   9288:   display:inline;
                   9289:   vertical-align:middle;
1.1082    raeburn  9290:   white-space: nowrap;
1.911     bisitz   9291: }
1.757     schulted 9292: 
1.783     amueller 9293: 
1.795     www      9294: a.LC_toolbarItem {
1.911     bisitz   9295:   display:block;
                   9296:   padding: 0;
                   9297:   margin: 0;
                   9298:   height: 32px;
                   9299:   width: 32px;
                   9300:   color:white;
                   9301:   border: none;
                   9302:   background-repeat:no-repeat;
                   9303:   background-color:transparent;
1.757     schulted 9304: }
                   9305: 
1.1449    raeburn  9306: .LC_navtools {
                   9307:   display: inline-block;
                   9308:   padding: 0;
                   9309:   margin: 2px;
                   9310:   vertical-align: middle;
                   9311: }
                   9312: 
1.915     droeschl 9313: ul.LC_funclist {
                   9314:     margin: 0;
                   9315:     padding: 0.5em 1em 0.5em 0;
                   9316: }
                   9317: 
1.933     droeschl 9318: ul.LC_funclist > li:first-child {
                   9319:     font-weight:bold; 
                   9320:     margin-left:0.8em;
                   9321: }
                   9322: 
1.915     droeschl 9323: ul.LC_funclist + ul.LC_funclist {
                   9324:     /* 
                   9325:        left border as a seperator if we have more than
                   9326:        one list 
                   9327:     */
                   9328:     border-left: 1px solid $sidebg;
                   9329:     /* 
                   9330:        this hides the left border behind the border of the 
                   9331:        outer box if element is wrapped to the next 'line' 
                   9332:     */
                   9333:     margin-left: -1px;
                   9334: }
                   9335: 
1.843     bisitz   9336: ul.LC_funclist li {
1.915     droeschl 9337:   display: inline;
1.782     bisitz   9338:   white-space: nowrap;
1.915     droeschl 9339:   margin: 0 0 0 25px;
                   9340:   line-height: 150%;
1.782     bisitz   9341: }
                   9342: 
1.974     wenzelju 9343: .LC_hidden {
                   9344:   display: none;
                   9345: }
                   9346: 
1.1030    www      9347: .LCmodal-overlay {
                   9348: 		position:fixed;
                   9349: 		top:0;
                   9350: 		right:0;
                   9351: 		bottom:0;
                   9352: 		left:0;
                   9353: 		height:100%;
                   9354: 		width:100%;
                   9355: 		margin:0;
                   9356: 		padding:0;
                   9357: 		background:#999;
                   9358: 		opacity:.75;
                   9359: 		filter: alpha(opacity=75);
                   9360: 		-moz-opacity: 0.75;
                   9361: 		z-index:101;
                   9362: }
                   9363: 
                   9364: * html .LCmodal-overlay {   
                   9365: 		position: absolute;
                   9366: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9367: }
                   9368: 
                   9369: .LCmodal-window {
                   9370: 		position:fixed;
                   9371: 		top:50%;
                   9372: 		left:50%;
                   9373: 		margin:0;
                   9374: 		padding:0;
                   9375: 		z-index:102;
                   9376: 	}
                   9377: 
                   9378: * html .LCmodal-window {
                   9379: 		position:absolute;
                   9380: }
                   9381: 
                   9382: .LCclose-window {
                   9383: 		position:absolute;
                   9384: 		width:32px;
                   9385: 		height:32px;
                   9386: 		right:8px;
                   9387: 		top:8px;
                   9388: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9389: 		text-indent:-99999px;
                   9390: 		overflow:hidden;
                   9391: 		cursor:pointer;
                   9392: }
                   9393: 
1.1369    raeburn  9394: .LCisDisabled {
                   9395:   cursor: not-allowed;
                   9396:   opacity: 0.5;
                   9397: }
                   9398: 
                   9399: a[aria-disabled="true"] {
                   9400:   color: currentColor;
                   9401:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9402:   pointer-events: none;
                   9403:   text-decoration: none;
                   9404: }
                   9405: 
1.1335    raeburn  9406: pre.LC_wordwrap {
                   9407:   white-space: pre-wrap;
                   9408:   white-space: -moz-pre-wrap;
                   9409:   white-space: -pre-wrap;
                   9410:   white-space: -o-pre-wrap;
                   9411:   word-wrap: break-word;
                   9412: }
                   9413: 
1.1100    raeburn  9414: /*
1.1231    damieng  9415:   styles used for response display
                   9416: */
1.1464    raeburn  9417: div.LC_radiofoil, div.LC_rankfoil, div.LC_optionfoil, div.LC_matchfoil, div.LC_login_links {
1.1231    damieng  9418:   margin: .5em 0em .5em 0em;
                   9419: }
                   9420: table.LC_itemgroup {
                   9421:   margin-top: 1em;
                   9422: }
                   9423: 
1.1462    raeburn  9424: table.LC_itemgroup tr th {
                   9425:   font-weight: normal;
                   9426: }
                   9427: 
                   9428: fieldset.LC_webbubbles {
                   9429:   margin: 2px 0 0 0;
                   9430:   padding: 0;
                   9431:   border: 0;
                   9432: }
                   9433: 
                   9434: ul.LC_webbubbles {
                   9435:   list-style: none;
                   9436:   padding: 0;
                   9437:   margin: 0;
                   9438:   text-align: left;
                   9439:   float: left;
                   9440: }
                   9441: 
                   9442: ul.LC_webbubbles li {
                   9443:   line-height: 1.8em;
                   9444:   border: 1px solid black;
                   9445:   padding: 0 2px 0 5px;
                   9446:   margin: 0 0 0 -1px;
                   9447:   float: left;
                   9448: }
                   9449: 
1.1231    damieng  9450: /*
1.1100    raeburn  9451:   styles used by TTH when "Default set of options to pass to tth/m
                   9452:   when converting TeX" in course settings has been set
                   9453: 
                   9454:   option passed: -t
                   9455: 
                   9456: */
                   9457: 
                   9458: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9459: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9460: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9461: td div.norm {line-height:normal;}
                   9462: 
                   9463: /*
                   9464:   option passed -y3
                   9465: */
                   9466: 
                   9467: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9468: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9469: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9470: 
1.1230    damieng  9471: /*
                   9472:   sections with roles, for content only
                   9473: */
                   9474: section[class^="role-"] {
                   9475:   padding-left: 10px;
                   9476:   padding-right: 5px;
                   9477:   margin-top: 8px;
                   9478:   margin-bottom: 8px;
                   9479:   border: 1px solid #2A4;
                   9480:   border-radius: 5px;
                   9481:   box-shadow: 0px 1px 1px #BBB;
                   9482: }
                   9483: section[class^="role-"]>h1 {
                   9484:   position: relative;
                   9485:   margin: 0px;
                   9486:   padding-top: 10px;
                   9487:   padding-left: 40px;
                   9488: }
                   9489: section[class^="role-"]>h1:before {
                   9490:   position: absolute;
                   9491:   left: -5px;
                   9492:   top: 5px;
                   9493: }
                   9494: section.role-activity>h1:before {
                   9495:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9496: }
                   9497: section.role-advice>h1:before {
                   9498:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9499: }
                   9500: section.role-bibliography>h1:before {
                   9501:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9502: }
                   9503: section.role-citation>h1:before {
                   9504:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9505: }
                   9506: section.role-conclusion>h1:before {
                   9507:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9508: }
                   9509: section.role-definition>h1:before {
                   9510:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9511: }
                   9512: section.role-demonstration>h1:before {
                   9513:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9514: }
                   9515: section.role-example>h1:before {
                   9516:   content:url('/adm/daxe/images/section_icons/example.png');
                   9517: }
                   9518: section.role-explanation>h1:before {
                   9519:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9520: }
                   9521: section.role-introduction>h1:before {
                   9522:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9523: }
                   9524: section.role-method>h1:before {
                   9525:   content:url('/adm/daxe/images/section_icons/method.png');
                   9526: }
                   9527: section.role-more_information>h1:before {
                   9528:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9529: }
                   9530: section.role-objectives>h1:before {
                   9531:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9532: }
                   9533: section.role-prerequisites>h1:before {
                   9534:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9535: }
                   9536: section.role-remark>h1:before {
                   9537:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9538: }
                   9539: section.role-reminder>h1:before {
                   9540:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9541: }
                   9542: section.role-summary>h1:before {
                   9543:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9544: }
                   9545: section.role-syntax>h1:before {
                   9546:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9547: }
                   9548: section.role-warning>h1:before {
                   9549:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9550: }
                   9551: 
1.1269    raeburn  9552: #LC_minitab_header {
                   9553:   float:left;
                   9554:   width:100%;
                   9555:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9556:   font-size:93%;
                   9557:   line-height:normal;
                   9558:   margin: 0.5em 0 0.5em 0;
                   9559: }
                   9560: #LC_minitab_header ul {
                   9561:   margin:0;
                   9562:   padding:10px 10px 0;
                   9563:   list-style:none;
                   9564: }
                   9565: #LC_minitab_header li {
                   9566:   float:left;
                   9567:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9568:   margin:0;
                   9569:   padding:0 0 0 9px;
                   9570: }
                   9571: #LC_minitab_header a {
                   9572:   display:block;
                   9573:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9574:   padding:5px 15px 4px 6px;
                   9575: }
                   9576: #LC_minitab_header #LC_current_minitab {
                   9577:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9578: }
                   9579: #LC_minitab_header #LC_current_minitab a {
                   9580:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9581:   padding-bottom:5px;
                   9582: }
                   9583: 
                   9584: 
1.343     albertel 9585: END
                   9586: }
                   9587: 
1.306     albertel 9588: =pod
                   9589: 
                   9590: =item * &headtag()
                   9591: 
                   9592: Returns a uniform footer for LON-CAPA web pages.
                   9593: 
1.307     albertel 9594: Inputs: $title - optional title for the head
                   9595:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9596:         $args - optional arguments
1.319     albertel 9597:             force_register - if is true call registerurl so the remote is 
                   9598:                              informed
1.415     albertel 9599:             redirect       -> array ref of
                   9600:                                    1- seconds before redirect occurs
                   9601:                                    2- url to redirect to
                   9602:                                    3- whether the side effect should occur
1.315     albertel 9603:                            (side effect of setting 
                   9604:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9605:                                redirected to)
                   9606:                                    4- whether the redirect target should be
                   9607:                                       the opener of the current (pop-up)
                   9608:                                       window (side effect of setting
                   9609:                                       $env{'internal.head.to_opener'} to
                   9610:                                       1, if true.
1.1388    raeburn  9611:                                    5- whether encrypt check should be skipped
1.352     albertel 9612:             domain         -> force to color decorate a page for a specific
                   9613:                                domain
                   9614:             function       -> force usage of a specific rolish color scheme
                   9615:             bgcolor        -> override the default page bgcolor
1.460     albertel 9616:             no_auto_mt_title
                   9617:                            -> prevent &mt()ing the title arg
1.464     albertel 9618: 
1.306     albertel 9619: =cut
                   9620: 
                   9621: sub headtag {
1.313     albertel 9622:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9623:     
1.363     albertel 9624:     my $function = $args->{'function'} || &get_users_function();
                   9625:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9626:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9627:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9628:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9629: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9630: 		   #time(),
1.418     albertel 9631: 		   $env{'environment.color.timestamp'},
1.363     albertel 9632: 		   $function,$domain,$bgcolor);
                   9633: 
1.369     www      9634:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9635: 
1.308     albertel 9636:     my $result =
                   9637: 	'<head>'.
1.1160    raeburn  9638: 	&font_settings($args);
1.319     albertel 9639: 
1.1188    raeburn  9640:     my $inhibitprint;
                   9641:     if ($args->{'print_suppress'}) {
                   9642:         $inhibitprint = &print_suppression();
                   9643:     }
1.1064    raeburn  9644: 
1.1439    raeburn  9645:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9646: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9647:     }
1.962     droeschl 9648:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9649:         $result .= Apache::lonxml::display_title();
1.319     albertel 9650:     }
1.436     albertel 9651:     if (!$args->{'no_nav_bar'} 
                   9652: 	&& !$args->{'only_body'}
1.1438    raeburn  9653: 	&& !$args->{'frameset'}
                   9654: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9655: 	$result .= &help_menu_js($httphost);
1.1032    www      9656:         $result.=&modal_window();
1.1038    www      9657:         $result.=&togglebox_script();
1.1034    www      9658:         $result.=&wishlist_window();
1.1041    www      9659:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9660:     } else {
                   9661:         if ($args->{'add_modal'}) {
                   9662:            $result.=&modal_window();
                   9663:         }
                   9664:         if ($args->{'add_wishlist'}) {
                   9665:            $result.=&wishlist_window();
                   9666:         }
1.1038    www      9667:         if ($args->{'add_togglebox'}) {
                   9668:            $result.=&togglebox_script();
                   9669:         }
1.1041    www      9670:         if ($args->{'add_progressbar'}) {
                   9671:            $result.=&LCprogressbarUpdate_script();
                   9672:         }
1.436     albertel 9673:     }
1.314     albertel 9674:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9675: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9676:         if (!$skip_enc_check) {
                   9677:             $url = &Apache::lonenc::check_encrypt($url);
                   9678:         }
1.414     albertel 9679: 	if (!$inhibit_continue) {
                   9680: 	    $env{'internal.head.redirect'} = $url;
                   9681: 	}
1.1386    raeburn  9682: 	$result.=<<"ADDMETA";
1.313     albertel 9683: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9684: ADDMETA
                   9685:         if ($to_opener) {
                   9686:             $env{'internal.head.to_opener'} = 1;
                   9687:             my $dest = &js_escape($url);
                   9688:             my $timeout = int($time * 1000);
                   9689:             $result .=<<"ENDJS";
                   9690: <script type="text/javascript">
                   9691: // <![CDATA[
                   9692: function LC_To_Opener() {
                   9693:     var dest = '$dest';
                   9694:     if (dest != '') {
                   9695:         if (window.opener != null && !window.opener.closed) {
                   9696:             window.opener.location.href=dest;
                   9697:             window.close();
                   9698:         } else {
                   9699:             window.location.href=dest;
                   9700:         }
                   9701:     }
                   9702: }
                   9703: \$(document).ready(function () {
                   9704:     setTimeout('LC_To_Opener()',$timeout);
                   9705: });
                   9706: // ]]>
                   9707: </script>
                   9708: ENDJS
                   9709:         } else {
                   9710:             $result.=<<"ADDMETA";
1.344     albertel 9711: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9712: ADDMETA
1.1386    raeburn  9713:         }
1.1210    raeburn  9714:     } else {
                   9715:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9716:             my $requrl = $env{'request.uri'};
                   9717:             if ($requrl eq '') {
                   9718:                 $requrl = $ENV{'REQUEST_URI'};
                   9719:                 $requrl =~ s/\?.+$//;
                   9720:             }
                   9721:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9722:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9723:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9724:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9725:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9726:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9727:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9728:                     my ($offload,$offloadoth);
1.1210    raeburn  9729:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9730:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9731:                             $offload = 1;
1.1353    raeburn  9732:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9733:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9734:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9735:                                     $offloadoth = 1;
                   9736:                                     $dom_in_use = $env{'user.domain'};
                   9737:                                 }
                   9738:                             }
1.1340    raeburn  9739:                         }
                   9740:                     }
                   9741:                     unless ($offload) {
                   9742:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9743:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9744:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9745:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9746:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9747:                                         $offload = 1;
1.1352    raeburn  9748:                                         $offloadoth = 1;
1.1340    raeburn  9749:                                         $dom_in_use = $env{'user.domain'};
                   9750:                                     }
1.1210    raeburn  9751:                                 }
1.1340    raeburn  9752:                             }
                   9753:                         }
                   9754:                     }
                   9755:                     if ($offload) {
1.1358    raeburn  9756:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9757:                         if (($newserver eq '') && ($offloadoth)) {
                   9758:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9759:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9760:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9761:                             }
                   9762:                         }
1.1340    raeburn  9763:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9764:                             my $numsec = 5;
                   9765:                             my $timeout = $numsec * 1000;
                   9766:                             my ($newurl,$locknum,%locks,$msg);
                   9767:                             if ($env{'request.role.adv'}) {
                   9768:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9769:                             }
                   9770:                             my $disable_submit = 0;
                   9771:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9772:                                 $disable_submit = 1;
                   9773:                             }
                   9774:                             if ($locknum) {
                   9775:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9776:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9777:                                        join(", ",sort(values(%locks)))."\n";
                   9778:                                 if (&show_course()) {
                   9779:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9780:                                 } else {
                   9781:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9782:                                 }
1.1340    raeburn  9783:                             } else {
                   9784:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9785:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9786:                                 }
                   9787:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9788:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9789:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9790:                                     $newurl .= '&role='.$env{'request.role'};
                   9791:                                 }
                   9792:                                 if ($env{'request.symb'}) {
                   9793:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9794:                                     if ($shownsymb =~ m{^/enc/}) {
                   9795:                                         my $reqdmajor = 2;
                   9796:                                         my $reqdminor = 11;
                   9797:                                         my $reqdsubminor = 3;
                   9798:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9799:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9800:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9801:                                         if (($major eq '' && $minor eq '') ||
                   9802:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9803:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9804:                                              ($reqdsubminor > $subminor))))) {
                   9805:                                             undef($shownsymb);
                   9806:                                         }
1.1210    raeburn  9807:                                     }
1.1340    raeburn  9808:                                     if ($shownsymb) {
                   9809:                                         &js_escape(\$shownsymb);
                   9810:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9811:                                     }
1.1340    raeburn  9812:                                 } else {
                   9813:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9814:                                     &js_escape(\$shownurl);
                   9815:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9816:                                 }
1.1340    raeburn  9817:                             }
                   9818:                             &js_escape(\$msg);
                   9819:                             $result.=<<OFFLOAD
1.1210    raeburn  9820: <meta http-equiv="pragma" content="no-cache" />
                   9821: <script type="text/javascript">
1.1215    raeburn  9822: // <![CDATA[
1.1210    raeburn  9823: function LC_Offload_Now() {
                   9824:     var dest = "$newurl";
                   9825:     if (dest != '') {
                   9826:         window.location.href="$newurl";
                   9827:     }
                   9828: }
1.1214    raeburn  9829: \$(document).ready(function () {
                   9830:     window.alert('$msg');
                   9831:     if ($disable_submit) {
1.1210    raeburn  9832:         \$(".LC_hwk_submit").prop("disabled", true);
                   9833:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9834:     }
                   9835:     setTimeout('LC_Offload_Now()', $timeout);
                   9836: });
1.1215    raeburn  9837: // ]]>
1.1210    raeburn  9838: </script>
                   9839: OFFLOAD
                   9840:                         }
                   9841:                     }
                   9842:                 }
                   9843:             }
                   9844:         }
1.313     albertel 9845:     }
1.306     albertel 9846:     if (!defined($title)) {
                   9847: 	$title = 'The LearningOnline Network with CAPA';
                   9848:     }
1.460     albertel 9849:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9850:     if ($title =~ /^LON-CAPA\s+/) {
                   9851:         $result .= '<title> '.$title.'</title>';
                   9852:     } else {
                   9853:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9854:     }
                   9855:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9856:     if (!$args->{'frameset'}) {
                   9857:         $result .= ' /';
                   9858:     }
                   9859:     $result .= '>' 
1.1064    raeburn  9860:         .$inhibitprint
1.414     albertel 9861: 	.$head_extra;
1.1242    raeburn  9862:     my $clientmobile;
                   9863:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9864:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9865:     } else {
                   9866:         $clientmobile = $env{'browser.mobile'};
                   9867:     }
                   9868:     if ($clientmobile) {
1.1137    raeburn  9869:         $result .= '
1.1435    raeburn  9870: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9871: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9872:     }
1.1455    raeburn  9873:     $result .= '<meta name="google" content="notranslate"';
                   9874:     if (!$args->{'frameset'}) {
                   9875:         $result .= ' /';
                   9876:     }
                   9877:     $result .= '>'."\n";
1.962     droeschl 9878:     return $result.'</head>';
1.306     albertel 9879: }
                   9880: 
                   9881: =pod
                   9882: 
1.340     albertel 9883: =item * &font_settings()
                   9884: 
                   9885: Returns neccessary <meta> to set the proper encoding
                   9886: 
1.1160    raeburn  9887: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9888: 
                   9889: =cut
                   9890: 
                   9891: sub font_settings {
1.1160    raeburn  9892:     my ($args) = @_;
1.340     albertel 9893:     my $headerstring='';
1.1160    raeburn  9894:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9895:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9896:         $headerstring.=
                   9897:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9898:         if (!$args->{'frameset'}) {
                   9899: 	    $headerstring.= ' /';
                   9900:         }
                   9901: 	$headerstring .= '>'."\n";
1.340     albertel 9902:     }
                   9903:     return $headerstring;
                   9904: }
                   9905: 
1.341     albertel 9906: =pod
                   9907: 
1.1064    raeburn  9908: =item * &print_suppression()
                   9909: 
                   9910: In course context returns css which causes the body to be blank when media="print",
                   9911: if printout generation is unavailable for the current resource.
                   9912: 
                   9913: This could be because:
                   9914: 
                   9915: (a) printstartdate is in the future
                   9916: 
                   9917: (b) printenddate is in the past
                   9918: 
                   9919: (c) there is an active exam block with "printout"
                   9920: functionality blocked
                   9921: 
                   9922: Users with pav, pfo or evb privileges are exempt.
                   9923: 
                   9924: Inputs: none
                   9925: 
                   9926: =cut
                   9927: 
                   9928: 
                   9929: sub print_suppression {
                   9930:     my $noprint;
                   9931:     if ($env{'request.course.id'}) {
                   9932:         my $scope = $env{'request.course.id'};
                   9933:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9934:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9935:             return;
                   9936:         }
                   9937:         if ($env{'request.course.sec'} ne '') {
                   9938:             $scope .= "/$env{'request.course.sec'}";
                   9939:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9940:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9941:                 return;
1.1064    raeburn  9942:             }
                   9943:         }
                   9944:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9945:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9946:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9947:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9948:         if ($blocked) {
                   9949:             my $checkrole = "cm./$cdom/$cnum";
                   9950:             if ($env{'request.course.sec'} ne '') {
                   9951:                 $checkrole .= "/$env{'request.course.sec'}";
                   9952:             }
                   9953:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9954:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9955:                 $noprint = 1;
                   9956:             }
                   9957:         }
                   9958:         unless ($noprint) {
                   9959:             my $symb = &Apache::lonnet::symbread();
                   9960:             if ($symb ne '') {
                   9961:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9962:                 if (ref($navmap)) {
                   9963:                     my $res = $navmap->getBySymb($symb);
                   9964:                     if (ref($res)) {
                   9965:                         if (!$res->resprintable()) {
                   9966:                             $noprint = 1;
                   9967:                         }
                   9968:                     }
                   9969:                 }
                   9970:             }
                   9971:         }
                   9972:         if ($noprint) {
                   9973:             return <<"ENDSTYLE";
                   9974: <style type="text/css" media="print">
                   9975:     body { display:none }
                   9976: </style>
                   9977: ENDSTYLE
                   9978:         }
                   9979:     }
                   9980:     return;
                   9981: }
                   9982: 
                   9983: =pod
                   9984: 
1.341     albertel 9985: =item * &xml_begin()
                   9986: 
                   9987: Returns the needed doctype and <html>
                   9988: 
                   9989: Inputs: none
                   9990: 
                   9991: =cut
                   9992: 
                   9993: sub xml_begin {
1.1168    raeburn  9994:     my ($is_frameset) = @_;
1.341     albertel 9995:     my $output='';
                   9996: 
                   9997:     if ($env{'browser.mathml'}) {
                   9998: 	$output='<?xml version="1.0"?>'
                   9999:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   10000: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   10001:             
                   10002: #	    .'<!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">] >'
                   10003: 	    .'<!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">'
                   10004:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   10005: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  10006:     } elsif ($is_frameset) {
                   10007:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
1.1459    raeburn  10008:                 '<html lang="en">'."\n";
1.341     albertel 10009:     } else {
1.1168    raeburn  10010: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   10011:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 10012:     }
                   10013:     return $output;
                   10014: }
1.340     albertel 10015: 
                   10016: =pod
                   10017: 
1.306     albertel 10018: =item * &start_page()
                   10019: 
                   10020: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   10021: 
1.648     raeburn  10022: Inputs:
                   10023: 
                   10024: =over 4
                   10025: 
                   10026: $title - optional title for the page
                   10027: 
                   10028: $head_extra - optional extra HTML to incude inside the <head>
                   10029: 
                   10030: $args - additional optional args supported are:
                   10031: 
                   10032: =over 8
                   10033: 
                   10034:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 10035:                                     arg on
1.814     bisitz   10036:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  10037:              add_entries    -> additional attributes to add to the  <body>
                   10038:              domain         -> force to color decorate a page for a 
1.317     albertel 10039:                                     specific domain
1.648     raeburn  10040:              function       -> force usage of a specific rolish color
1.317     albertel 10041:                                     scheme
1.648     raeburn  10042:              redirect       -> see &headtag()
                   10043:              bgcolor        -> override the default page bg color
                   10044:              js_ready       -> return a string ready for being used in 
1.317     albertel 10045:                                     a javascript writeln
1.648     raeburn  10046:              html_encode    -> return a string ready for being used in 
1.320     albertel 10047:                                     a html attribute
1.648     raeburn  10048:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 10049:                                     $forcereg arg
1.648     raeburn  10050:              frameset       -> if true will start with a <frameset>
1.330     albertel 10051:                                     rather than <body>
1.648     raeburn  10052:              skip_phases    -> hash ref of 
1.338     albertel 10053:                                     head -> skip the <html><head> generation
                   10054:                                     body -> skip all <body> generation
1.648     raeburn  10055:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 10056:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  10057:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  10058:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   10059:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   10060:                                    to override those values, or add to them, specify the value to
                   10061:                                    include in the style attribute to include in the div tag by using
                   10062:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  10063:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   10064:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  10065:              group          -> includes the current group, if page is for a 
1.1274    raeburn  10066:                                specific group
                   10067:              use_absolute   -> for request for external resource or syllabus, this
                   10068:                                will contain https://<hostname> if server uses
                   10069:                                https (as per hosts.tab), but request is for http
                   10070:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  10071:              links_disabled -> Links in primary and secondary menus are disabled
                   10072:                                (Can enable them once page has loaded - see lonroles.pm
                   10073:                                for an example).
1.1380    raeburn  10074:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 10075: 
1.648     raeburn  10076: =back
1.460     albertel 10077: 
1.648     raeburn  10078: =back
1.562     albertel 10079: 
1.306     albertel 10080: =cut
                   10081: 
                   10082: sub start_page {
1.309     albertel 10083:     my ($title,$head_extra,$args) = @_;
1.318     albertel 10084:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 10085: 
1.315     albertel 10086:     $env{'internal.start_page'}++;
1.1359    raeburn  10087:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 10088: 
1.338     albertel 10089:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  10090:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 10091:     }
1.1316    raeburn  10092: 
                   10093:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  10094:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   10095:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   10096:                 $args->{'no_primary_menu'} = 1;
                   10097:             }
                   10098:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   10099:                 $args->{'no_inline_menu'} = 1;
                   10100:             }
                   10101:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   10102:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   10103:             }
                   10104:         } else {
                   10105:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10106:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   10107:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   10108:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   10109:                     $args->{'no_primary_menu'} = 1;
                   10110:                 }
                   10111:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   10112:                     $args->{'no_inline_menu'} = 1;
                   10113:                 }
                   10114:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   10115:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   10116:                 }
                   10117:             }
                   10118:         }
1.1316    raeburn  10119:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   10120:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   10121:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  10122:     } elsif ($env{'request.course.id'}) {
                   10123:         my $expiretime=600;
                   10124:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   10125:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   10126:         }
                   10127:         my ($deeplinkmenu,$menuref);
                   10128:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   10129:         if ($menucoll) {
                   10130:             if (ref($menuref) eq 'HASH') {
                   10131:                 %menu = %{$menuref};
                   10132:             }
                   10133:             if ($menu{'top'} eq 'n') {
                   10134:                 $args->{'no_primary_menu'} = 1;
                   10135:             }
                   10136:             if ($menu{'inline'} eq 'n') {
                   10137:                 unless (&Apache::lonnet::allowed('opa')) {
                   10138:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10139:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10140:                     my $crstype = &course_type();
                   10141:                     my $now = time;
                   10142:                     my $ccrole;
                   10143:                     if ($crstype eq 'Community') {
                   10144:                         $ccrole = 'co';
                   10145:                     } else {
                   10146:                         $ccrole = 'cc';
                   10147:                     }
                   10148:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   10149:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   10150:                         if ((($start) && ($start<0)) ||
                   10151:                             (($end) && ($end<$now))  ||
                   10152:                             (($start) && ($now<$start))) {
                   10153:                             $args->{'no_inline_menu'} = 1;
                   10154:                         }
                   10155:                     } else {
                   10156:                         $args->{'no_inline_menu'} = 1;
                   10157:                     }
                   10158:                 }
                   10159:             }
                   10160:         }
1.1316    raeburn  10161:     }
1.1359    raeburn  10162: 
1.1385    raeburn  10163:     my $showncrumbs;
1.338     albertel 10164:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10165: 	if ($args->{'frameset'}) {
                   10166: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10167: 						$args->{'add_entries'});
                   10168: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10169:         } else {
                   10170:             $result .=
                   10171:                 &bodytag($title, 
                   10172:                          $args->{'function'},       $args->{'add_entries'},
                   10173:                          $args->{'only_body'},      $args->{'domain'},
                   10174:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10175:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10176:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10177:                          \%menu,\$showncrumbs);
1.831     bisitz   10178:         }
1.330     albertel 10179:     }
1.338     albertel 10180: 
1.315     albertel 10181:     if ($args->{'js_ready'}) {
1.713     kaisler  10182: 		$result = &js_ready($result);
1.315     albertel 10183:     }
1.320     albertel 10184:     if ($args->{'html_encode'}) {
1.713     kaisler  10185: 		$result = &html_encode($result);
                   10186:     }
                   10187: 
1.813     bisitz   10188:     # Preparation for new and consistent functionlist at top of screen
                   10189:     # if ($args->{'functionlist'}) {
                   10190:     #            $result .= &build_functionlist();
                   10191:     #}
                   10192: 
1.964     droeschl 10193:     # Don't add anything more if only_body wanted or in const space
                   10194:     return $result if    $args->{'only_body'} 
                   10195:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10196: 
                   10197:     #Breadcrumbs
1.758     kaisler  10198:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10199:         unless ($showncrumbs) {
1.758     kaisler  10200: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10201: 		#if any br links exists, add them to the breadcrumbs
                   10202: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10203: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10204: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10205: 			}
                   10206: 		}
1.1096    raeburn  10207:                 # if @advtools array contains items add then to the breadcrumbs
                   10208:                 if (@advtools > 0) {
                   10209:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10210:                 }
1.1272    raeburn  10211:                 my $menulink;
                   10212:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10213:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10214:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10215:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10216:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10217:                      (!$env{'request.role.adv'}))) {
                   10218:                     $menulink = 0;
                   10219:                 } else {
                   10220:                     undef($menulink);
                   10221:                 }
1.1385    raeburn  10222:                 my $linkprotout;
                   10223:                 if ($env{'request.deeplink.login'}) {
                   10224:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10225:                     if ($linkprotout) {
                   10226:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10227:                     }
                   10228:                 }
1.758     kaisler  10229: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10230: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10231: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10232:                                                                        '',$menulink,'',
                   10233:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10234:                 } else {
1.1437    raeburn  10235: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10236:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10237: 		}
1.1385    raeburn  10238:         }
1.320     albertel 10239:     }
1.315     albertel 10240:     return $result;
1.306     albertel 10241: }
                   10242: 
                   10243: sub end_page {
1.315     albertel 10244:     my ($args) = @_;
                   10245:     $env{'internal.end_page'}++;
1.330     albertel 10246:     my $result;
1.335     albertel 10247:     if ($args->{'discussion'}) {
                   10248: 	my ($target,$parser);
                   10249: 	if (ref($args->{'discussion'})) {
                   10250: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10251: 				$args->{'discussion'}{'parser'});
                   10252: 	}
                   10253: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10254:     }
1.330     albertel 10255:     if ($args->{'frameset'}) {
                   10256: 	$result .= '</frameset>';
                   10257:     } else {
1.635     raeburn  10258: 	$result .= &endbodytag($args);
1.330     albertel 10259:     }
1.1080    raeburn  10260:     unless ($args->{'notbody'}) {
                   10261:         $result .= "\n</html>";
                   10262:     }
1.330     albertel 10263: 
1.315     albertel 10264:     if ($args->{'js_ready'}) {
1.317     albertel 10265: 	$result = &js_ready($result);
1.315     albertel 10266:     }
1.335     albertel 10267: 
1.320     albertel 10268:     if ($args->{'html_encode'}) {
                   10269: 	$result = &html_encode($result);
                   10270:     }
1.335     albertel 10271: 
1.315     albertel 10272:     return $result;
                   10273: }
                   10274: 
1.1359    raeburn  10275: sub menucoll_in_effect {
                   10276:     my ($menucoll,$deeplinkmenu,%menu);
                   10277:     if ($env{'request.course.id'}) {
                   10278:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10279:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10280:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10281:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10282:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10283:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10284:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10285:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10286:                     if (ref($navmap)) {
                   10287:                         $deeplink = $navmap->get_mapparam(undef,
                   10288:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10289:                                                           '0.deeplink');
1.1370    raeburn  10290:                     } else {
                   10291:                         $check_login_symb = 1;
1.1362    raeburn  10292:                     }
                   10293:                 } else {
1.1370    raeburn  10294:                     my $symb = &Apache::lonnet::symbread();
                   10295:                     if ($symb) {
                   10296:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10297:                     } else {
                   10298:                         $check_login_symb = 1;
                   10299:                     }
1.1362    raeburn  10300:                 }
                   10301:             } else {
1.1370    raeburn  10302:                 $check_login_symb = 1;
                   10303:             }
                   10304:             if ($check_login_symb) {
1.1362    raeburn  10305:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10306:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10307:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10308:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10309:                     if (ref($navmap)) {
                   10310:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10311:                     }
                   10312:                 } else {
                   10313:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10314:                 }
                   10315:             }
1.1359    raeburn  10316:             if ($deeplink ne '') {
1.1378    raeburn  10317:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10318:                 if ($display =~ /^\d+$/) {
                   10319:                     $deeplinkmenu = 1;
                   10320:                     $menucoll = $display;
                   10321:                 }
                   10322:             }
                   10323:         }
                   10324:         if ($menucoll) {
                   10325:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10326:         }
                   10327:     }
                   10328:     return ($menucoll,$deeplinkmenu,\%menu);
                   10329: }
                   10330: 
1.1362    raeburn  10331: sub deeplink_login_symb {
                   10332:     my ($cnum,$cdom) = @_;
                   10333:     my $login_symb;
                   10334:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10335:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10336:     }
                   10337:     return $login_symb;
                   10338: }
                   10339: 
                   10340: sub symb_from_tinyurl {
                   10341:     my ($url,$cnum,$cdom) = @_;
                   10342:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10343:         my $key = $1;
                   10344:         my ($tinyurl,$login);
                   10345:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10346:         if (defined($cached)) {
                   10347:             $tinyurl = $result;
                   10348:         } else {
                   10349:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10350:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10351:             if ($currtiny{$key} ne '') {
                   10352:                 $tinyurl = $currtiny{$key};
                   10353:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10354:             }
1.1364    raeburn  10355:         }
                   10356:         if ($tinyurl ne '') {
                   10357:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10358:             if (wantarray) {
                   10359:                 return ($cnumreq,$symb);
                   10360:             } elsif ($cnumreq eq $cnum) {
                   10361:                 return $symb;
1.1362    raeburn  10362:             }
                   10363:         }
                   10364:     }
1.1364    raeburn  10365:     if (wantarray) {
                   10366:         return ();
                   10367:     } else {
                   10368:         return;
                   10369:     }
1.1362    raeburn  10370: }
                   10371: 
1.1405    raeburn  10372: sub usable_exttools {
                   10373:     my %tooltypes;
                   10374:     if ($env{'request.course.id'}) {
                   10375:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10376:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10377:                %tooltypes = (
                   10378:                              crs => 1,
                   10379:                              dom => 1,
                   10380:                             );
                   10381:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10382:                $tooltypes{'crs'} = 1;
                   10383:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10384:                $tooltypes{'dom'} = 1;
                   10385:            }
                   10386:         } else {
                   10387:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10388:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10389:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10390:             if ($crstype eq '') {
                   10391:                 $crstype = 'course';
                   10392:             }
                   10393:             if ($crstype eq 'course') {
                   10394:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10395:                     $crstype = 'official';
                   10396:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10397:                     $crstype = 'textbook';
                   10398:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10399:                     $crstype = 'lti';
                   10400:                 } else {
                   10401:                     $crstype = 'unofficial';
                   10402:                 }
                   10403:             }
                   10404:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10405:             if ($domdefaults{$crstype.'domexttool'}) {
                   10406:                 $tooltypes{'dom'} = 1;
                   10407:             }
                   10408:             if ($domdefaults{$crstype.'exttool'}) {
                   10409:                 $tooltypes{'crs'} = 1;
                   10410:             }
                   10411:         }
                   10412:     }
                   10413:     return %tooltypes;
                   10414: }
                   10415: 
1.1034    www      10416: sub wishlist_window {
                   10417:     return(<<'ENDWISHLIST');
1.1046    raeburn  10418: <script type="text/javascript">
1.1034    www      10419: // <![CDATA[
                   10420: // <!-- BEGIN LON-CAPA Internal
                   10421: function set_wishlistlink(title, path) {
                   10422:     if (!title) {
                   10423:         title = document.title;
                   10424:         title = title.replace(/^LON-CAPA /,'');
                   10425:     }
1.1175    raeburn  10426:     title = encodeURIComponent(title);
1.1203    raeburn  10427:     title = title.replace("'","\\\'");
1.1034    www      10428:     if (!path) {
                   10429:         path = location.pathname;
                   10430:     }
1.1175    raeburn  10431:     path = encodeURIComponent(path);
1.1203    raeburn  10432:     path = path.replace("'","\\\'");
1.1034    www      10433:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10434:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10435: }
                   10436: // END LON-CAPA Internal -->
                   10437: // ]]>
                   10438: </script>
                   10439: ENDWISHLIST
                   10440: }
                   10441: 
1.1030    www      10442: sub modal_window {
                   10443:     return(<<'ENDMODAL');
1.1046    raeburn  10444: <script type="text/javascript">
1.1030    www      10445: // <![CDATA[
                   10446: // <!-- BEGIN LON-CAPA Internal
                   10447: var modalWindow = {
                   10448: 	parent:"body",
                   10449: 	windowId:null,
                   10450: 	content:null,
                   10451: 	width:null,
                   10452: 	height:null,
                   10453: 	close:function()
                   10454: 	{
                   10455: 	        $(".LCmodal-window").remove();
                   10456: 	        $(".LCmodal-overlay").remove();
                   10457: 	},
                   10458: 	open:function()
                   10459: 	{
                   10460: 		var modal = "";
                   10461: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10462: 		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;\">";
                   10463: 		modal += this.content;
                   10464: 		modal += "</div>";	
                   10465: 
                   10466: 		$(this.parent).append(modal);
                   10467: 
                   10468: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10469: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10470: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10471: 	}
                   10472: };
1.1140    raeburn  10473: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10474: 	{
1.1266    raeburn  10475:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10476: 		modalWindow.windowId = "myModal";
                   10477: 		modalWindow.width = width;
                   10478: 		modalWindow.height = height;
1.1196    raeburn  10479: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10480: 		modalWindow.open();
1.1208    raeburn  10481: 	};
1.1030    www      10482: // END LON-CAPA Internal -->
                   10483: // ]]>
                   10484: </script>
                   10485: ENDMODAL
                   10486: }
                   10487: 
                   10488: sub modal_link {
1.1140    raeburn  10489:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10490:     unless ($width) { $width=480; }
                   10491:     unless ($height) { $height=400; }
1.1031    www      10492:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10493:     unless ($transparency) { $transparency='true'; }
                   10494: 
1.1074    raeburn  10495:     my $target_attr;
                   10496:     if (defined($target)) {
                   10497:         $target_attr = 'target="'.$target.'"';
                   10498:     }
                   10499:     return <<"ENDLINK";
1.1336    raeburn  10500: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10501: ENDLINK
1.1030    www      10502: }
                   10503: 
1.1032    www      10504: sub modal_adhoc_script {
1.1365    raeburn  10505:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10506:     my $mathjax;
                   10507:     if ($possmathjax) {
                   10508:         $mathjax = <<'ENDJAX';
                   10509:                if (typeof MathJax == 'object') {
                   10510:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10511:                }
                   10512: ENDJAX
                   10513:     }
1.1032    www      10514:     return (<<ENDADHOC);
1.1046    raeburn  10515: <script type="text/javascript">
1.1032    www      10516: // <![CDATA[
                   10517:         var $funcname = function()
                   10518:         {
                   10519:                 modalWindow.windowId = "myModal";
                   10520:                 modalWindow.width = $width;
                   10521:                 modalWindow.height = $height;
                   10522:                 modalWindow.content = '$content';
                   10523:                 modalWindow.open();
1.1365    raeburn  10524:                 $mathjax
1.1032    www      10525:         };  
                   10526: // ]]>
                   10527: </script>
                   10528: ENDADHOC
                   10529: }
                   10530: 
1.1041    www      10531: sub modal_adhoc_inner {
1.1365    raeburn  10532:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10533:     my $innerwidth=$width-20;
                   10534:     $content=&js_ready(
1.1140    raeburn  10535:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10536:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10537:                  $content.
1.1041    www      10538:                  &end_scrollbox().
1.1140    raeburn  10539:                  &end_page()
1.1041    www      10540:              );
1.1365    raeburn  10541:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10542: }
                   10543: 
                   10544: sub modal_adhoc_window {
1.1365    raeburn  10545:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10546:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10547:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10548: }
                   10549: 
                   10550: sub modal_adhoc_launch {
                   10551:     my ($funcname,$width,$height,$content)=@_;
                   10552:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10553: <script type="text/javascript">
                   10554: // <![CDATA[
                   10555: $funcname();
                   10556: // ]]>
                   10557: </script>
                   10558: ENDLAUNCH
                   10559: }
                   10560: 
                   10561: sub modal_adhoc_close {
                   10562:     return (<<ENDCLOSE);
                   10563: <script type="text/javascript">
                   10564: // <![CDATA[
                   10565: modalWindow.close();
                   10566: // ]]>
                   10567: </script>
                   10568: ENDCLOSE
                   10569: }
                   10570: 
1.1038    www      10571: sub togglebox_script {
                   10572:    return(<<ENDTOGGLE);
                   10573: <script type="text/javascript"> 
                   10574: // <![CDATA[
                   10575: function LCtoggleDisplay(id,hidetext,showtext) {
                   10576:    link = document.getElementById(id + "link").childNodes[0];
                   10577:    with (document.getElementById(id).style) {
                   10578:       if (display == "none" ) {
                   10579:           display = "inline";
                   10580:           link.nodeValue = hidetext;
                   10581:         } else {
                   10582:           display = "none";
                   10583:           link.nodeValue = showtext;
                   10584:        }
                   10585:    }
                   10586: }
                   10587: // ]]>
                   10588: </script>
                   10589: ENDTOGGLE
                   10590: }
                   10591: 
1.1039    www      10592: sub start_togglebox {
                   10593:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10594:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10595:     unless ($showtext) { $showtext=&mt('show'); }
                   10596:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10597:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10598:     return &start_data_table().
                   10599:            &start_data_table_header_row().
                   10600:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10601:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10602:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10603:            &end_data_table_header_row().
                   10604:            '<tr id="'.$id.'" style="display:none""><td>';
                   10605: }
                   10606: 
                   10607: sub end_togglebox {
                   10608:     return '</td></tr>'.&end_data_table();
                   10609: }
                   10610: 
1.1041    www      10611: sub LCprogressbar_script {
1.1302    raeburn  10612:    my ($id,$number_to_do)=@_;
                   10613:    if ($number_to_do) {
                   10614:        return(<<ENDPROGRESS);
1.1041    www      10615: <script type="text/javascript">
                   10616: // <![CDATA[
1.1045    www      10617: \$('#progressbar$id').progressbar({
1.1041    www      10618:   value: 0,
                   10619:   change: function(event, ui) {
                   10620:     var newVal = \$(this).progressbar('option', 'value');
                   10621:     \$('.pblabel', this).text(LCprogressTxt);
                   10622:   }
                   10623: });
                   10624: // ]]>
                   10625: </script>
                   10626: ENDPROGRESS
1.1302    raeburn  10627:    } else {
                   10628:        return(<<ENDPROGRESS);
                   10629: <script type="text/javascript">
                   10630: // <![CDATA[
                   10631: \$('#progressbar$id').progressbar({
                   10632:   value: false,
                   10633:   create: function(event, ui) {
                   10634:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10635:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10636:   }
                   10637: });
                   10638: // ]]>
                   10639: </script>
                   10640: ENDPROGRESS
                   10641:    }
1.1041    www      10642: }
                   10643: 
                   10644: sub LCprogressbarUpdate_script {
                   10645:    return(<<ENDPROGRESSUPDATE);
                   10646: <style type="text/css">
                   10647: .ui-progressbar { position:relative; }
1.1302    raeburn  10648: .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      10649: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10650: </style>
                   10651: <script type="text/javascript">
                   10652: // <![CDATA[
1.1045    www      10653: var LCprogressTxt='---';
                   10654: 
1.1302    raeburn  10655: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10656:    LCprogressTxt=progresstext;
1.1302    raeburn  10657:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10658:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10659:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10660:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10661:    } else {
                   10662:        \$('#progressbar'+id).progressbar('value',percent);
                   10663:    }
1.1041    www      10664: }
                   10665: // ]]>
                   10666: </script>
                   10667: ENDPROGRESSUPDATE
                   10668: }
                   10669: 
1.1042    www      10670: my $LClastpercent;
1.1045    www      10671: my $LCidcnt;
                   10672: my $LCcurrentid;
1.1042    www      10673: 
1.1041    www      10674: sub LCprogressbar {
1.1302    raeburn  10675:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10676:     $LClastpercent=0;
1.1045    www      10677:     $LCidcnt++;
                   10678:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10679:     my ($starting,$content);
                   10680:     if ($number_to_do) {
                   10681:         $starting=&mt('Starting');
                   10682:         $content=(<<ENDPROGBAR);
                   10683: $preamble
1.1045    www      10684:   <div id="progressbar$LCcurrentid">
1.1041    www      10685:     <span class="pblabel">$starting</span>
                   10686:   </div>
                   10687: ENDPROGBAR
1.1302    raeburn  10688:     } else {
                   10689:         $starting=&mt('Loading...');
                   10690:         $LClastpercent='false';
                   10691:         $content=(<<ENDPROGBAR);
                   10692: $preamble
                   10693:   <div id="progressbar$LCcurrentid">
                   10694:       <div class="progress-label">$starting</div>
                   10695:   </div>
                   10696: ENDPROGBAR
                   10697:     }
                   10698:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10699: }
                   10700: 
                   10701: sub LCprogressbarUpdate {
1.1302    raeburn  10702:     my ($r,$val,$text,$number_to_do)=@_;
                   10703:     if ($number_to_do) {
                   10704:         unless ($val) { 
                   10705:             if ($LClastpercent) {
                   10706:                 $val=$LClastpercent;
                   10707:             } else {
                   10708:                 $val=0;
                   10709:             }
                   10710:         }
                   10711:         if ($val<0) { $val=0; }
                   10712:         if ($val>100) { $val=0; }
                   10713:         $LClastpercent=$val;
                   10714:         unless ($text) { $text=$val.'%'; }
                   10715:     } else {
                   10716:         $val = 'false';
1.1042    www      10717:     }
1.1041    www      10718:     $text=&js_ready($text);
1.1044    www      10719:     &r_print($r,<<ENDUPDATE);
1.1041    www      10720: <script type="text/javascript">
                   10721: // <![CDATA[
1.1302    raeburn  10722: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10723: // ]]>
                   10724: </script>
                   10725: ENDUPDATE
1.1035    www      10726: }
                   10727: 
1.1042    www      10728: sub LCprogressbarClose {
                   10729:     my ($r)=@_;
                   10730:     $LClastpercent=0;
1.1044    www      10731:     &r_print($r,<<ENDCLOSE);
1.1042    www      10732: <script type="text/javascript">
                   10733: // <![CDATA[
1.1045    www      10734: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10735: // ]]>
                   10736: </script>
                   10737: ENDCLOSE
1.1044    www      10738: }
                   10739: 
                   10740: sub r_print {
                   10741:     my ($r,$to_print)=@_;
                   10742:     if ($r) {
                   10743:       $r->print($to_print);
                   10744:       $r->rflush();
                   10745:     } else {
                   10746:       print($to_print);
                   10747:     }
1.1042    www      10748: }
                   10749: 
1.320     albertel 10750: sub html_encode {
                   10751:     my ($result) = @_;
                   10752: 
1.322     albertel 10753:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10754:     
                   10755:     return $result;
                   10756: }
1.1044    www      10757: 
1.317     albertel 10758: sub js_ready {
                   10759:     my ($result) = @_;
                   10760: 
1.323     albertel 10761:     $result =~ s/[\n\r]/ /xmsg;
                   10762:     $result =~ s/\\/\\\\/xmsg;
                   10763:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10764:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10765:     
                   10766:     return $result;
                   10767: }
                   10768: 
1.315     albertel 10769: sub validate_page {
                   10770:     if (  exists($env{'internal.start_page'})
1.316     albertel 10771: 	  &&     $env{'internal.start_page'} > 1) {
                   10772: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10773: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10774: 				 $ENV{'request.filename'});
1.315     albertel 10775:     }
                   10776:     if (  exists($env{'internal.end_page'})
1.316     albertel 10777: 	  &&     $env{'internal.end_page'} > 1) {
                   10778: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10779: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10780: 				 $env{'request.filename'});
1.315     albertel 10781:     }
                   10782:     if (     exists($env{'internal.start_page'})
                   10783: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10784: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10785: 				 $env{'request.filename'});
1.315     albertel 10786:     }
                   10787:     if (   ! exists($env{'internal.start_page'})
                   10788: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10789: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10790: 				 $env{'request.filename'});
1.315     albertel 10791:     }
1.306     albertel 10792: }
1.315     albertel 10793: 
1.996     www      10794: 
                   10795: sub start_scrollbox {
1.1140    raeburn  10796:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10797:     unless ($outerwidth) { $outerwidth='520px'; }
                   10798:     unless ($width) { $width='500px'; }
                   10799:     unless ($height) { $height='200px'; }
1.1075    raeburn  10800:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10801:     if ($id ne '') {
1.1140    raeburn  10802:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10803:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10804:     }
1.1075    raeburn  10805:     if ($bgcolor ne '') {
                   10806:         $tdcol = "background-color: $bgcolor;";
                   10807:     }
1.1137    raeburn  10808:     my $nicescroll_js;
                   10809:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10810:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10811:     }
                   10812:     return <<"END";
                   10813: $nicescroll_js
                   10814: 
                   10815: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10816: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10817: END
                   10818: }
                   10819: 
                   10820: sub end_scrollbox {
                   10821:     return '</div></td></tr></table>';
                   10822: }
                   10823: 
                   10824: sub nicescroll_javascript {
                   10825:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10826:     my %options;
                   10827:     if (ref($cursor) eq 'HASH') {
                   10828:         %options = %{$cursor};
                   10829:     }
                   10830:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10831:         $options{'railalign'} = 'left';
                   10832:     }
                   10833:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10834:         my $function  = &get_users_function();
                   10835:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10836:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10837:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10838:         }
1.1140    raeburn  10839:     }
                   10840:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10841:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10842:             $options{'cursoropacity'}='1.0';
                   10843:         }
1.1140    raeburn  10844:     } else {
                   10845:         $options{'cursoropacity'}='1.0';
                   10846:     }
                   10847:     if ($options{'cursorfixedheight'} eq 'none') {
                   10848:         delete($options{'cursorfixedheight'});
                   10849:     } else {
                   10850:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10851:     }
                   10852:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10853:         delete($options{'railoffset'});
                   10854:     }
                   10855:     my @niceoptions;
                   10856:     while (my($key,$value) = each(%options)) {
                   10857:         if ($value =~ /^\{.+\}$/) {
                   10858:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10859:         } else {
1.1140    raeburn  10860:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10861:         }
1.1140    raeburn  10862:     }
                   10863:     my $nicescroll_js = '
1.1137    raeburn  10864: $(document).ready(
1.1140    raeburn  10865:       function() {
                   10866:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10867:       }
1.1137    raeburn  10868: );
                   10869: ';
1.1140    raeburn  10870:     if ($framecheck) {
                   10871:         $nicescroll_js .= '
                   10872: function expand_div(caller) {
                   10873:     if (top === self) {
                   10874:         document.getElementById("'.$id.'").style.width = "auto";
                   10875:         document.getElementById("'.$id.'").style.height = "auto";
                   10876:     } else {
                   10877:         try {
                   10878:             if (parent.frames) {
                   10879:                 if (parent.frames.length > 1) {
                   10880:                     var framesrc = parent.frames[1].location.href;
                   10881:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10882:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10883:                         document.getElementById("'.$id.'").style.width = "auto";
                   10884:                         document.getElementById("'.$id.'").style.height = "auto";
                   10885:                     }
                   10886:                 }
                   10887:             }
                   10888:         } catch (e) {
                   10889:             return;
                   10890:         }
1.1137    raeburn  10891:     }
1.1140    raeburn  10892:     return;
1.996     www      10893: }
1.1140    raeburn  10894: ';
                   10895:     }
                   10896:     if ($needjsready) {
                   10897:         $nicescroll_js = '
                   10898: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10899:     } else {
                   10900:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10901:     }
                   10902:     return $nicescroll_js;
1.996     www      10903: }
                   10904: 
1.318     albertel 10905: sub simple_error_page {
1.1150    bisitz   10906:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10907:     my %displayargs;
1.1151    raeburn  10908:     if (ref($args) eq 'HASH') {
                   10909:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10910:         if ($args->{'only_body'}) {
                   10911:             $displayargs{'only_body'} = 1;
                   10912:         }
                   10913:         if ($args->{'no_nav_bar'}) {
                   10914:             $displayargs{'no_nav_bar'} = 1;
                   10915:         }
1.1151    raeburn  10916:     } else {
                   10917:         $msg = &mt($msg);
                   10918:     }
1.1150    bisitz   10919: 
1.318     albertel 10920:     my $page =
1.1459    raeburn  10921: 	&Apache::loncommon::start_page($title,'',\%displayargs)."\n".
1.1460    raeburn  10922:         '<div class="LC_landmark" style="clear:both" role="main">'.
1.1150    bisitz   10923: 	'<p class="LC_error">'.$msg.'</p>'.
1.1459    raeburn  10924:         '</div>'.
1.318     albertel 10925: 	&Apache::loncommon::end_page();
                   10926:     if (ref($r)) {
                   10927: 	$r->print($page);
1.327     albertel 10928: 	return;
1.318     albertel 10929:     }
                   10930:     return $page;
                   10931: }
1.347     albertel 10932: 
                   10933: {
1.610     albertel 10934:     my @row_count;
1.961     onken    10935: 
                   10936:     sub start_data_table_count {
                   10937:         unshift(@row_count, 0);
                   10938:         return;
                   10939:     }
                   10940: 
                   10941:     sub end_data_table_count {
                   10942:         shift(@row_count);
                   10943:         return;
                   10944:     }
                   10945: 
1.1466    raeburn  10946:     sub set_data_table_count {
                   10947:         my ($count) = @_;
                   10948:         unshift(@row_count,$count);
                   10949:     }
                   10950: 
1.347     albertel 10951:     sub start_data_table {
1.1018    raeburn  10952: 	my ($add_class,$id) = @_;
1.422     albertel 10953: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10954:         my $table_id;
                   10955:         if (defined($id)) {
                   10956:             $table_id = ' id="'.$id.'"';
                   10957:         }
1.961     onken    10958: 	&start_data_table_count();
1.1018    raeburn  10959: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10960:     }
                   10961: 
                   10962:     sub end_data_table {
1.961     onken    10963: 	&end_data_table_count();
1.389     albertel 10964: 	return '</table>'."\n";;
1.347     albertel 10965:     }
                   10966: 
                   10967:     sub start_data_table_row {
1.974     wenzelju 10968: 	my ($add_class, $id) = @_;
1.610     albertel 10969: 	$row_count[0]++;
                   10970: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10971: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10972:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10973:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10974:     }
1.471     banghart 10975:     
                   10976:     sub continue_data_table_row {
1.974     wenzelju 10977: 	my ($add_class, $id) = @_;
1.610     albertel 10978: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10979: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10980:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10981:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10982:     }
1.347     albertel 10983: 
                   10984:     sub end_data_table_row {
1.389     albertel 10985: 	return '</tr>'."\n";;
1.347     albertel 10986:     }
1.367     www      10987: 
1.421     albertel 10988:     sub start_data_table_empty_row {
1.707     bisitz   10989: #	$row_count[0]++;
1.421     albertel 10990: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10991:     }
                   10992: 
                   10993:     sub end_data_table_empty_row {
                   10994: 	return '</tr>'."\n";;
                   10995:     }
                   10996: 
1.367     www      10997:     sub start_data_table_header_row {
1.1465    raeburn  10998: 	my ($add_class,$id) = @_;
                   10999: 	my $css_class = 'LC_header_row';
                   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.367     www      11003:     }
                   11004: 
                   11005:     sub end_data_table_header_row {
1.389     albertel 11006: 	return '</tr>'."\n";;
1.367     www      11007:     }
1.890     droeschl 11008: 
                   11009:     sub data_table_caption {
1.1468    raeburn  11010:         my ($caption,$css_class) = @_;
                   11011:         return "<caption class=\"LC_caption $css_class\">$caption</caption>";
1.890     droeschl 11012:     }
1.347     albertel 11013: }
                   11014: 
1.548     albertel 11015: =pod
                   11016: 
                   11017: =item * &inhibit_menu_check($arg)
                   11018: 
                   11019: Checks for a inhibitmenu state and generates output to preserve it
                   11020: 
                   11021: Inputs:         $arg - can be any of
                   11022:                      - undef - in which case the return value is a string 
                   11023:                                to add  into arguments list of a uri
                   11024:                      - 'input' - in which case the return value is a HTML
                   11025:                                  <form> <input> field of type hidden to
                   11026:                                  preserve the value
                   11027:                      - a url - in which case the return value is the url with
                   11028:                                the neccesary cgi args added to preserve the
                   11029:                                inhibitmenu state
                   11030:                      - a ref to a url - no return value, but the string is
                   11031:                                         updated to include the neccessary cgi
                   11032:                                         args to preserve the inhibitmenu state
                   11033: 
                   11034: =cut
                   11035: 
                   11036: sub inhibit_menu_check {
                   11037:     my ($arg) = @_;
                   11038:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   11039:     if ($arg eq 'input') {
                   11040: 	if ($env{'form.inhibitmenu'}) {
                   11041: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   11042: 	} else {
                   11043: 	    return
                   11044: 	}
                   11045:     }
                   11046:     if ($env{'form.inhibitmenu'}) {
                   11047: 	if (ref($arg)) {
                   11048: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   11049: 	} elsif ($arg eq '') {
                   11050: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   11051: 	} else {
                   11052: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   11053: 	}
                   11054:     }
                   11055:     if (!ref($arg)) {
                   11056: 	return $arg;
                   11057:     }
                   11058: }
                   11059: 
1.251     albertel 11060: ###############################################
1.182     matthew  11061: 
                   11062: =pod
                   11063: 
1.549     albertel 11064: =back
                   11065: 
                   11066: =head1 User Information Routines
                   11067: 
                   11068: =over 4
                   11069: 
1.405     albertel 11070: =item * &get_users_function()
1.182     matthew  11071: 
                   11072: Used by &bodytag to determine the current users primary role.
                   11073: Returns either 'student','coordinator','admin', or 'author'.
                   11074: 
                   11075: =cut
                   11076: 
                   11077: ###############################################
                   11078: sub get_users_function {
1.815     tempelho 11079:     my $function = 'norole';
1.818     tempelho 11080:     if ($env{'request.role'}=~/^(st)/) {
                   11081:         $function='student';
                   11082:     }
1.907     raeburn  11083:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  11084:         $function='coordinator';
                   11085:     }
1.258     albertel 11086:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  11087:         $function='admin';
                   11088:     }
1.826     bisitz   11089:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  11090:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  11091:         $function='author';
                   11092:     }
                   11093:     return $function;
1.54      www      11094: }
1.99      www      11095: 
                   11096: ###############################################
                   11097: 
1.233     raeburn  11098: =pod
                   11099: 
1.821     raeburn  11100: =item * &show_course()
                   11101: 
                   11102: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   11103: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   11104: 
                   11105: Inputs:
                   11106: None
                   11107: 
                   11108: Outputs:
                   11109: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   11110: 
                   11111: =cut
                   11112: 
                   11113: ###############################################
                   11114: sub show_course {
1.1408    raeburn  11115:     my ($udom,$uname) = @_;
                   11116:     if (($udom ne '') && ($uname ne '')) {
                   11117:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  11118:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  11119:                 return 0;
                   11120:             } else {
                   11121:                 return 1;
                   11122:             }
                   11123:         }
                   11124:     }
1.821     raeburn  11125:     my $course = !$env{'user.adv'};
                   11126:     if (!$env{'user.adv'}) {
                   11127:         foreach my $env (keys(%env)) {
                   11128:             next if ($env !~ m/^user\.priv\./);
                   11129:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   11130:                 $course = 0;
                   11131:                 last;
                   11132:             }
                   11133:         }
                   11134:     }
                   11135:     return $course;
                   11136: }
                   11137: 
                   11138: ###############################################
                   11139: 
                   11140: =pod
                   11141: 
1.542     raeburn  11142: =item * &check_user_status()
1.274     raeburn  11143: 
                   11144: Determines current status of supplied role for a
                   11145: specific user. Roles can be active, previous or future.
                   11146: 
                   11147: Inputs: 
                   11148: user's domain, user's username, course's domain,
1.375     raeburn  11149: course's number, optional section ID.
1.274     raeburn  11150: 
                   11151: Outputs:
                   11152: role status: active, previous or future. 
                   11153: 
                   11154: =cut
                   11155: 
                   11156: sub check_user_status {
1.412     raeburn  11157:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  11158:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  11159:     my @uroles = keys(%userinfo);
1.274     raeburn  11160:     my $srchstr;
                   11161:     my $active_chk = 'none';
1.412     raeburn  11162:     my $now = time;
1.274     raeburn  11163:     if (@uroles > 0) {
1.908     raeburn  11164:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  11165:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   11166:         } else {
1.412     raeburn  11167:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   11168:         }
                   11169:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  11170:             my $role_end = 0;
                   11171:             my $role_start = 0;
                   11172:             $active_chk = 'active';
1.412     raeburn  11173:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11174:                 $role_end = $1;
                   11175:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11176:                     $role_start = $1;
1.274     raeburn  11177:                 }
                   11178:             }
                   11179:             if ($role_start > 0) {
1.412     raeburn  11180:                 if ($now < $role_start) {
1.274     raeburn  11181:                     $active_chk = 'future';
                   11182:                 }
                   11183:             }
                   11184:             if ($role_end > 0) {
1.412     raeburn  11185:                 if ($now > $role_end) {
1.274     raeburn  11186:                     $active_chk = 'previous';
                   11187:                 }
                   11188:             }
                   11189:         }
                   11190:     }
                   11191:     return $active_chk;
                   11192: }
                   11193: 
                   11194: ###############################################
                   11195: 
                   11196: =pod
                   11197: 
1.405     albertel 11198: =item * &get_sections()
1.233     raeburn  11199: 
                   11200: Determines all the sections for a course including
                   11201: sections with students and sections containing other roles.
1.419     raeburn  11202: Incoming parameters: 
                   11203: 
                   11204: 1. domain
                   11205: 2. course number 
                   11206: 3. reference to array containing roles for which sections should 
                   11207: be gathered (optional).
                   11208: 4. reference to array containing status types for which sections 
                   11209: should be gathered (optional).
                   11210: 
                   11211: If the third argument is undefined, sections are gathered for any role. 
                   11212: If the fourth argument is undefined, sections are gathered for any status.
                   11213: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11214:  
1.374     raeburn  11215: Returns section hash (keys are section IDs, values are
                   11216: number of users in each section), subject to the
1.419     raeburn  11217: optional roles filter, optional status filter 
1.233     raeburn  11218: 
                   11219: =cut
                   11220: 
                   11221: ###############################################
                   11222: sub get_sections {
1.419     raeburn  11223:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11224:     if (!defined($cdom) || !defined($cnum)) {
                   11225:         my $cid =  $env{'request.course.id'};
                   11226: 
                   11227: 	return if (!defined($cid));
                   11228: 
                   11229:         $cdom = $env{'course.'.$cid.'.domain'};
                   11230:         $cnum = $env{'course.'.$cid.'.num'};
                   11231:     }
                   11232: 
                   11233:     my %sectioncount;
1.419     raeburn  11234:     my $now = time;
1.240     albertel 11235: 
1.1118    raeburn  11236:     my $check_students = 1;
                   11237:     my $only_students = 0;
                   11238:     if (ref($possible_roles) eq 'ARRAY') {
                   11239:         if (grep(/^st$/,@{$possible_roles})) {
                   11240:             if (@{$possible_roles} == 1) {
                   11241:                 $only_students = 1;
                   11242:             }
                   11243:         } else {
                   11244:             $check_students = 0;
                   11245:         }
                   11246:     }
                   11247: 
                   11248:     if ($check_students) { 
1.276     albertel 11249: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11250: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11251: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11252:         my $start_index = &Apache::loncoursedata::CL_START();
                   11253:         my $end_index = &Apache::loncoursedata::CL_END();
                   11254:         my $status;
1.366     albertel 11255: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11256: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11257: 				                     $data->[$status_index],
                   11258:                                                      $data->[$start_index],
                   11259:                                                      $data->[$end_index]);
                   11260:             if ($stu_status eq 'Active') {
                   11261:                 $status = 'active';
                   11262:             } elsif ($end < $now) {
                   11263:                 $status = 'previous';
                   11264:             } elsif ($start > $now) {
                   11265:                 $status = 'future';
                   11266:             } 
                   11267: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11268:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11269:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11270: 		    $sectioncount{$section}++;
                   11271:                 }
1.240     albertel 11272: 	    }
                   11273: 	}
                   11274:     }
1.1118    raeburn  11275:     if ($only_students) {
                   11276:         return %sectioncount;
                   11277:     }
1.240     albertel 11278:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11279:     foreach my $user (sort(keys(%courseroles))) {
                   11280: 	if ($user !~ /^(\w{2})/) { next; }
                   11281: 	my ($role) = ($user =~ /^(\w{2})/);
                   11282: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11283: 	my ($section,$status);
1.240     albertel 11284: 	if ($role eq 'cr' &&
                   11285: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11286: 	    $section=$1;
                   11287: 	}
                   11288: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11289: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11290:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11291:         if ($end == -1 && $start == -1) {
                   11292:             next; #deleted role
                   11293:         }
                   11294:         if (!defined($possible_status)) { 
                   11295:             $sectioncount{$section}++;
                   11296:         } else {
                   11297:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11298:                 $status = 'active';
                   11299:             } elsif ($end < $now) {
                   11300:                 $status = 'future';
                   11301:             } elsif ($start > $now) {
                   11302:                 $status = 'previous';
                   11303:             }
                   11304:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11305:                 $sectioncount{$section}++;
                   11306:             }
                   11307:         }
1.233     raeburn  11308:     }
1.366     albertel 11309:     return %sectioncount;
1.233     raeburn  11310: }
                   11311: 
1.274     raeburn  11312: ###############################################
1.294     raeburn  11313: 
                   11314: =pod
1.405     albertel 11315: 
                   11316: =item * &get_course_users()
                   11317: 
1.275     raeburn  11318: Retrieves usernames:domains for users in the specified course
                   11319: with specific role(s), and access status. 
                   11320: 
                   11321: Incoming parameters:
1.277     albertel 11322: 1. course domain
                   11323: 2. course number
                   11324: 3. access status: users must have - either active, 
1.275     raeburn  11325: previous, future, or all.
1.277     albertel 11326: 4. reference to array of permissible roles
1.288     raeburn  11327: 5. reference to array of section restrictions (optional)
                   11328: 6. reference to results object (hash of hashes).
                   11329: 7. reference to optional userdata hash
1.609     raeburn  11330: 8. reference to optional statushash
1.630     raeburn  11331: 9. flag if privileged users (except those set to unhide in
                   11332:    course settings) should be excluded    
1.609     raeburn  11333: Keys of top level results hash are roles.
1.275     raeburn  11334: Keys of inner hashes are username:domain, with 
                   11335: values set to access type.
1.288     raeburn  11336: Optional userdata hash returns an array with arguments in the 
                   11337: same order as loncoursedata::get_classlist() for student data.
                   11338: 
1.609     raeburn  11339: Optional statushash returns
                   11340: 
1.288     raeburn  11341: Entries for end, start, section and status are blank because
                   11342: of the possibility of multiple values for non-student roles.
                   11343: 
1.275     raeburn  11344: =cut
1.405     albertel 11345: 
1.275     raeburn  11346: ###############################################
1.405     albertel 11347: 
1.275     raeburn  11348: sub get_course_users {
1.630     raeburn  11349:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11350:     my %idx = ();
1.419     raeburn  11351:     my %seclists;
1.288     raeburn  11352: 
                   11353:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11354:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11355:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11356:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11357:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11358:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11359:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11360:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11361: 
1.290     albertel 11362:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11363:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11364:         my $now = time;
1.277     albertel 11365:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11366:             my $match = 0;
1.412     raeburn  11367:             my $secmatch = 0;
1.419     raeburn  11368:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11369:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11370:             if ($section eq '') {
                   11371:                 $section = 'none';
                   11372:             }
1.291     albertel 11373:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11374:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11375:                     $secmatch = 1;
                   11376:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11377:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11378:                         $secmatch = 1;
                   11379:                     }
                   11380:                 } else {  
1.419     raeburn  11381: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11382: 		        $secmatch = 1;
                   11383:                     }
1.290     albertel 11384: 		}
1.412     raeburn  11385:                 if (!$secmatch) {
                   11386:                     next;
                   11387:                 }
1.419     raeburn  11388:             }
1.275     raeburn  11389:             if (defined($$types{'active'})) {
1.288     raeburn  11390:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11391:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11392:                     $match = 1;
1.275     raeburn  11393:                 }
                   11394:             }
                   11395:             if (defined($$types{'previous'})) {
1.609     raeburn  11396:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11397:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11398:                     $match = 1;
1.275     raeburn  11399:                 }
                   11400:             }
                   11401:             if (defined($$types{'future'})) {
1.609     raeburn  11402:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11403:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11404:                     $match = 1;
1.275     raeburn  11405:                 }
                   11406:             }
1.609     raeburn  11407:             if ($match) {
                   11408:                 push(@{$seclists{$student}},$section);
                   11409:                 if (ref($userdata) eq 'HASH') {
                   11410:                     $$userdata{$student} = $$classlist{$student};
                   11411:                 }
                   11412:                 if (ref($statushash) eq 'HASH') {
                   11413:                     $statushash->{$student}{'st'}{$section} = $status;
                   11414:                 }
1.288     raeburn  11415:             }
1.275     raeburn  11416:         }
                   11417:     }
1.412     raeburn  11418:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11419:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11420:         my $now = time;
1.609     raeburn  11421:         my %displaystatus = ( previous => 'Expired',
                   11422:                               active   => 'Active',
                   11423:                               future   => 'Future',
                   11424:                             );
1.1121    raeburn  11425:         my (%nothide,@possdoms);
1.630     raeburn  11426:         if ($hidepriv) {
                   11427:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11428:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11429:                 if ($user !~ /:/) {
                   11430:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11431:                 } else {
                   11432:                     $nothide{$user} = 1;
                   11433:                 }
                   11434:             }
1.1121    raeburn  11435:             my @possdoms = ($cdom);
                   11436:             if ($coursehash{'checkforpriv'}) {
                   11437:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11438:             }
1.630     raeburn  11439:         }
1.439     raeburn  11440:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11441:             my $match = 0;
1.412     raeburn  11442:             my $secmatch = 0;
1.439     raeburn  11443:             my $status;
1.412     raeburn  11444:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11445:             $user =~ s/:$//;
1.439     raeburn  11446:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11447:             if ($end == -1 || $start == -1) {
                   11448:                 next;
                   11449:             }
                   11450:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11451:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11452:                 my ($uname,$udom) = split(/:/,$user);
                   11453:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11454:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11455:                         $secmatch = 1;
                   11456:                     } elsif ($usec eq '') {
1.420     albertel 11457:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11458:                             $secmatch = 1;
                   11459:                         }
                   11460:                     } else {
                   11461:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11462:                             $secmatch = 1;
                   11463:                         }
                   11464:                     }
                   11465:                     if (!$secmatch) {
                   11466:                         next;
                   11467:                     }
1.288     raeburn  11468:                 }
1.419     raeburn  11469:                 if ($usec eq '') {
                   11470:                     $usec = 'none';
                   11471:                 }
1.275     raeburn  11472:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11473:                     if ($hidepriv) {
1.1121    raeburn  11474:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11475:                             (!$nothide{$uname.':'.$udom})) {
                   11476:                             next;
                   11477:                         }
                   11478:                     }
1.503     raeburn  11479:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11480:                         $status = 'previous';
                   11481:                     } elsif ($start > $now) {
                   11482:                         $status = 'future';
                   11483:                     } else {
                   11484:                         $status = 'active';
                   11485:                     }
1.277     albertel 11486:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11487:                         if ($status eq $type) {
1.420     albertel 11488:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11489:                                 push(@{$$users{$role}{$user}},$type);
                   11490:                             }
1.288     raeburn  11491:                             $match = 1;
                   11492:                         }
                   11493:                     }
1.419     raeburn  11494:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11495:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11496: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11497:                         }
1.420     albertel 11498:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11499:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11500:                         }
1.609     raeburn  11501:                         if (ref($statushash) eq 'HASH') {
                   11502:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11503:                         }
1.275     raeburn  11504:                     }
                   11505:                 }
                   11506:             }
                   11507:         }
1.290     albertel 11508:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11509:             if ((defined($cdom)) && (defined($cnum))) {
                   11510:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11511:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11512:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11513:                     next if ($owner eq '');
                   11514:                     my ($ownername,$ownerdom);
                   11515:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11516:                         $ownername = $1;
                   11517:                         $ownerdom = $2;
                   11518:                     } else {
                   11519:                         $ownername = $owner;
                   11520:                         $ownerdom = $cdom;
                   11521:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11522:                     }
                   11523:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11524:                     if (defined($userdata) && 
1.609     raeburn  11525: 			!exists($$userdata{$owner})) {
                   11526: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11527:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11528:                             push(@{$seclists{$owner}},'none');
                   11529:                         }
                   11530:                         if (ref($statushash) eq 'HASH') {
                   11531:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11532:                         }
1.290     albertel 11533: 		    }
1.279     raeburn  11534:                 }
                   11535:             }
                   11536:         }
1.419     raeburn  11537:         foreach my $user (keys(%seclists)) {
                   11538:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11539:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11540:         }
1.275     raeburn  11541:     }
                   11542:     return;
                   11543: }
                   11544: 
1.288     raeburn  11545: sub get_user_info {
                   11546:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11547:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11548: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11549:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11550:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11551:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11552:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11553:     return;
                   11554: }
1.275     raeburn  11555: 
1.472     raeburn  11556: ###############################################
                   11557: 
                   11558: =pod
                   11559: 
                   11560: =item * &get_user_quota()
                   11561: 
1.1134    raeburn  11562: Retrieves quota assigned for storage of user files.
                   11563: Default is to report quota for portfolio files.
1.472     raeburn  11564: 
                   11565: Incoming parameters:
                   11566: 1. user's username
                   11567: 2. user's domain
1.1134    raeburn  11568: 3. quota name - portfolio, author, or course
1.1136    raeburn  11569:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11570: 4. crstype - official, unofficial, textbook, placement or community, 
                   11571:    if quota name is course
1.472     raeburn  11572: 
                   11573: Returns:
1.1163    raeburn  11574: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11575: 2. (Optional) Type of setting: custom or default
                   11576:    (individually assigned or default for user's 
                   11577:    institutional status).
                   11578: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11579:    or student - types as defined in localenroll::inst_usertypes 
                   11580:    for user's domain, which determines default quota for user.
                   11581: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11582: 
                   11583: If a value has been stored in the user's environment, 
1.536     raeburn  11584: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11585: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11586: 
                   11587: =cut
                   11588: 
                   11589: ###############################################
                   11590: 
                   11591: 
                   11592: sub get_user_quota {
1.1136    raeburn  11593:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11594:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11595:     if (!defined($udom)) {
                   11596:         $udom = $env{'user.domain'};
                   11597:     }
                   11598:     if (!defined($uname)) {
                   11599:         $uname = $env{'user.name'};
                   11600:     }
                   11601:     if (($udom eq '' || $uname eq '') ||
                   11602:         ($udom eq 'public') && ($uname eq 'public')) {
                   11603:         $quota = 0;
1.536     raeburn  11604:         $quotatype = 'default';
                   11605:         $defquota = 0; 
1.472     raeburn  11606:     } else {
1.536     raeburn  11607:         my $inststatus;
1.1134    raeburn  11608:         if ($quotaname eq 'course') {
                   11609:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11610:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11611:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11612:             } else {
                   11613:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11614:                 $quota = $cenv{'internal.uploadquota'};
                   11615:             }
1.536     raeburn  11616:         } else {
1.1134    raeburn  11617:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11618:                 if ($quotaname eq 'author') {
                   11619:                     $quota = $env{'environment.authorquota'};
                   11620:                 } else {
                   11621:                     $quota = $env{'environment.portfolioquota'};
                   11622:                 }
                   11623:                 $inststatus = $env{'environment.inststatus'};
                   11624:             } else {
                   11625:                 my %userenv = 
                   11626:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11627:                                          'authorquota','inststatus'],$udom,$uname);
                   11628:                 my ($tmp) = keys(%userenv);
                   11629:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11630:                     if ($quotaname eq 'author') {
                   11631:                         $quota = $userenv{'authorquota'};
                   11632:                     } else {
                   11633:                         $quota = $userenv{'portfolioquota'};
                   11634:                     }
                   11635:                     $inststatus = $userenv{'inststatus'};
                   11636:                 } else {
                   11637:                     undef(%userenv);
                   11638:                 }
                   11639:             }
                   11640:         }
                   11641:         if ($quota eq '' || wantarray) {
                   11642:             if ($quotaname eq 'course') {
                   11643:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11644:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11645:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11646:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11647:                     $defquota = $domdefs{$crstype.'quota'};
                   11648:                 }
                   11649:                 if ($defquota eq '') {
                   11650:                     $defquota = 500;
                   11651:                 }
1.1134    raeburn  11652:             } else {
                   11653:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11654:             }
                   11655:             if ($quota eq '') {
                   11656:                 $quota = $defquota;
                   11657:                 $quotatype = 'default';
                   11658:             } else {
                   11659:                 $quotatype = 'custom';
                   11660:             }
1.472     raeburn  11661:         }
                   11662:     }
1.536     raeburn  11663:     if (wantarray) {
                   11664:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11665:     } else {
                   11666:         return $quota;
                   11667:     }
1.472     raeburn  11668: }
                   11669: 
                   11670: ###############################################
                   11671: 
                   11672: =pod
                   11673: 
                   11674: =item * &default_quota()
                   11675: 
1.536     raeburn  11676: Retrieves default quota assigned for storage of user portfolio files,
                   11677: given an (optional) user's institutional status.
1.472     raeburn  11678: 
                   11679: Incoming parameters:
1.1142    raeburn  11680: 
1.472     raeburn  11681: 1. domain
1.536     raeburn  11682: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11683:    status types (e.g., faculty, staff, student etc.)
                   11684:    which apply to the user for whom the default is being retrieved.
                   11685:    If the institutional status string in undefined, the domain
1.1134    raeburn  11686:    default quota will be returned.
                   11687: 3.  quota name - portfolio, author, or course
                   11688:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11689: 
                   11690: Returns:
1.1142    raeburn  11691: 
1.1163    raeburn  11692: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11693: 2. (Optional) institutional type which determined the value of the
                   11694:    default quota.
1.472     raeburn  11695: 
                   11696: If a value has been stored in the domain's configuration db,
                   11697: it will return that, otherwise it returns 20 (for backwards 
                   11698: compatibility with domains which have not set up a configuration
1.1163    raeburn  11699: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11700: 
1.536     raeburn  11701: If the user's status includes multiple types (e.g., staff and student),
                   11702: the largest default quota which applies to the user determines the
                   11703: default quota returned.
                   11704: 
1.472     raeburn  11705: =cut
                   11706: 
                   11707: ###############################################
                   11708: 
                   11709: 
                   11710: sub default_quota {
1.1134    raeburn  11711:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11712:     my ($defquota,$settingstatus);
                   11713:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11714:                                             ['quotas'],$udom);
1.1134    raeburn  11715:     my $key = 'defaultquota';
                   11716:     if ($quotaname eq 'author') {
                   11717:         $key = 'authorquota';
                   11718:     }
1.622     raeburn  11719:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11720:         if ($inststatus ne '') {
1.765     raeburn  11721:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11722:             foreach my $item (@statuses) {
1.1134    raeburn  11723:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11724:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11725:                         if ($defquota eq '') {
1.1134    raeburn  11726:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11727:                             $settingstatus = $item;
1.1134    raeburn  11728:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11729:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11730:                             $settingstatus = $item;
                   11731:                         }
                   11732:                     }
1.1134    raeburn  11733:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11734:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11735:                         if ($defquota eq '') {
                   11736:                             $defquota = $quotahash{'quotas'}{$item};
                   11737:                             $settingstatus = $item;
                   11738:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11739:                             $defquota = $quotahash{'quotas'}{$item};
                   11740:                             $settingstatus = $item;
                   11741:                         }
1.536     raeburn  11742:                     }
                   11743:                 }
                   11744:             }
                   11745:         }
                   11746:         if ($defquota eq '') {
1.1134    raeburn  11747:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11748:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11749:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11750:                 $defquota = $quotahash{'quotas'}{'default'};
                   11751:             }
1.536     raeburn  11752:             $settingstatus = 'default';
1.1139    raeburn  11753:             if ($defquota eq '') {
                   11754:                 if ($quotaname eq 'author') {
                   11755:                     $defquota = 500;
                   11756:                 }
                   11757:             }
1.536     raeburn  11758:         }
                   11759:     } else {
                   11760:         $settingstatus = 'default';
1.1134    raeburn  11761:         if ($quotaname eq 'author') {
                   11762:             $defquota = 500;
                   11763:         } else {
                   11764:             $defquota = 20;
                   11765:         }
1.536     raeburn  11766:     }
                   11767:     if (wantarray) {
                   11768:         return ($defquota,$settingstatus);
1.472     raeburn  11769:     } else {
1.536     raeburn  11770:         return $defquota;
1.472     raeburn  11771:     }
                   11772: }
                   11773: 
1.1135    raeburn  11774: ###############################################
                   11775: 
                   11776: =pod
                   11777: 
1.1136    raeburn  11778: =item * &excess_filesize_warning()
1.1135    raeburn  11779: 
                   11780: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11781: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11782: space to be exceeded.
1.1136    raeburn  11783: 
                   11784: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11785: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11786: 
1.1165    raeburn  11787: Inputs: 7 
1.1136    raeburn  11788: 1. username or coursenum
1.1135    raeburn  11789: 2. domain
1.1136    raeburn  11790: 3. context ('author' or 'course')
1.1135    raeburn  11791: 4. filename of file for which action is being requested
                   11792: 5. filesize (kB) of file
                   11793: 6. action being taken: copy or upload.
1.1237    raeburn  11794: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11795: 
                   11796: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11797:          otherwise return null.
                   11798: 
                   11799: =back
1.1135    raeburn  11800: 
                   11801: =cut
                   11802: 
1.1136    raeburn  11803: sub excess_filesize_warning {
1.1165    raeburn  11804:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11805:     my $current_disk_usage = 0;
1.1165    raeburn  11806:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11807:     if ($context eq 'author') {
                   11808:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11809:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11810:     } else {
                   11811:         foreach my $subdir ('docs','supplemental') {
                   11812:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11813:         }
                   11814:     }
1.1135    raeburn  11815:     $disk_quota = int($disk_quota * 1000);
                   11816:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11817:         return '<p class="LC_warning">'.
1.1135    raeburn  11818:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11819:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11820:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11821:                             $disk_quota,$current_disk_usage).
                   11822:                '</p>';
                   11823:     }
                   11824:     return;
                   11825: }
                   11826: 
                   11827: ###############################################
                   11828: 
                   11829: 
1.1136    raeburn  11830: 
                   11831: 
1.384     raeburn  11832: sub get_secgrprole_info {
                   11833:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11834:     my %sections_count = &get_sections($cdom,$cnum);
                   11835:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11836:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11837:     my @groups = sort(keys(%curr_groups));
                   11838:     my $allroles = [];
                   11839:     my $rolehash;
                   11840:     my $accesshash = {
                   11841:                      active => 'Currently has access',
                   11842:                      future => 'Will have future access',
                   11843:                      previous => 'Previously had access',
                   11844:                   };
                   11845:     if ($needroles) {
                   11846:         $rolehash = {'all' => 'all'};
1.385     albertel 11847:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11848: 	if (&Apache::lonnet::error(%user_roles)) {
                   11849: 	    undef(%user_roles);
                   11850: 	}
                   11851:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11852:             my ($role)=split(/\:/,$item,2);
                   11853:             if ($role eq 'cr') { next; }
                   11854:             if ($role =~ /^cr/) {
                   11855:                 $$rolehash{$role} = (split('/',$role))[3];
                   11856:             } else {
                   11857:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11858:             }
                   11859:         }
                   11860:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11861:             push(@{$allroles},$key);
                   11862:         }
                   11863:         push (@{$allroles},'st');
                   11864:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11865:     }
                   11866:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11867: }
                   11868: 
1.555     raeburn  11869: sub user_picker {
1.1279    raeburn  11870:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11871:     my $currdom = $dom;
1.1253    raeburn  11872:     my @alldoms = &Apache::lonnet::all_domains();
                   11873:     if (@alldoms == 1) {
                   11874:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11875:                                                ['directorysrch'],$alldoms[0]);
                   11876:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11877:         my $showdom = $domdesc;
                   11878:         if ($showdom eq '') {
                   11879:             $showdom = $dom;
                   11880:         }
                   11881:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11882:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11883:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11884:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11885:             }
                   11886:         }
                   11887:     }
1.555     raeburn  11888:     my %curr_selected = (
                   11889:                         srchin => 'dom',
1.580     raeburn  11890:                         srchby => 'lastname',
1.555     raeburn  11891:                       );
                   11892:     my $srchterm;
1.625     raeburn  11893:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11894:         if ($srch->{'srchby'} ne '') {
                   11895:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11896:         }
                   11897:         if ($srch->{'srchin'} ne '') {
                   11898:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11899:         }
                   11900:         if ($srch->{'srchtype'} ne '') {
                   11901:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11902:         }
                   11903:         if ($srch->{'srchdomain'} ne '') {
                   11904:             $currdom = $srch->{'srchdomain'};
                   11905:         }
                   11906:         $srchterm = $srch->{'srchterm'};
                   11907:     }
1.1222    damieng  11908:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11909:                     'usr'       => 'Search criteria',
1.563     raeburn  11910:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11911:                     'uname'     => 'username',
                   11912:                     'lastname'  => 'last name',
1.555     raeburn  11913:                     'lastfirst' => 'last name, first name',
1.558     albertel 11914:                     'crs'       => 'in this course',
1.576     raeburn  11915:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11916:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11917:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11918:                     'exact'     => 'is',
                   11919:                     'contains'  => 'contains',
1.569     raeburn  11920:                     'begins'    => 'begins with',
1.1222    damieng  11921:                                        );
                   11922:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11923:                     'youm'      => "You must include some text to search for.",
                   11924:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11925:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11926:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11927:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11928:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11929:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11930:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11931:                                        );
1.1222    damieng  11932:     &html_escape(\%html_lt);
                   11933:     &js_escape(\%js_lt);
1.1255    raeburn  11934:     my $domform;
1.1277    raeburn  11935:     my $allow_blank = 1;
1.1255    raeburn  11936:     if ($fixeddom) {
1.1277    raeburn  11937:         $allow_blank = 0;
                   11938:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11939:     } else {
1.1287    raeburn  11940:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11941:         my ($trusted,$untrusted);
1.1287    raeburn  11942:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11943:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11944:         } elsif ($context eq 'author') {
1.1288    raeburn  11945:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11946:         } elsif ($context eq 'domain') {
1.1288    raeburn  11947:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11948:         }
1.1288    raeburn  11949:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11950:     }
1.563     raeburn  11951:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11952: 
                   11953:     my @srchins = ('crs','dom','alc','instd');
                   11954: 
                   11955:     foreach my $option (@srchins) {
                   11956:         # FIXME 'alc' option unavailable until 
                   11957:         #       loncreateuser::print_user_query_page()
                   11958:         #       has been completed.
                   11959:         next if ($option eq 'alc');
1.880     raeburn  11960:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11961:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11962:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11963:         if ($curr_selected{'srchin'} eq $option) {
                   11964:             $srchinsel .= ' 
1.1222    damieng  11965:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11966:         } else {
                   11967:             $srchinsel .= '
1.1222    damieng  11968:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11969:         }
1.555     raeburn  11970:     }
1.563     raeburn  11971:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11972: 
                   11973:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11974:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11975:         if ($curr_selected{'srchby'} eq $option) {
                   11976:             $srchbysel .= '
1.1222    damieng  11977:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11978:         } else {
                   11979:             $srchbysel .= '
1.1222    damieng  11980:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11981:          }
                   11982:     }
                   11983:     $srchbysel .= "\n  </select>\n";
                   11984: 
                   11985:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11986:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11987:         if ($curr_selected{'srchtype'} eq $option) {
                   11988:             $srchtypesel .= '
1.1222    damieng  11989:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11990:         } else {
                   11991:             $srchtypesel .= '
1.1222    damieng  11992:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11993:         }
                   11994:     }
                   11995:     $srchtypesel .= "\n  </select>\n";
                   11996: 
1.558     albertel 11997:     my ($newuserscript,$new_user_create);
1.994     raeburn  11998:     my $context_dom = $env{'request.role.domain'};
                   11999:     if ($context eq 'requestcrs') {
                   12000:         if ($env{'form.coursedom'} ne '') { 
                   12001:             $context_dom = $env{'form.coursedom'};
                   12002:         }
                   12003:     }
1.556     raeburn  12004:     if ($forcenewuser) {
1.576     raeburn  12005:         if (ref($srch) eq 'HASH') {
1.994     raeburn  12006:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  12007:                 if ($cancreate) {
                   12008:                     $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>';
                   12009:                 } else {
1.799     bisitz   12010:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  12011:                     my %usertypetext = (
                   12012:                         official   => 'institutional',
                   12013:                         unofficial => 'non-institutional',
                   12014:                     );
1.799     bisitz   12015:                     $new_user_create = '<p class="LC_warning">'
                   12016:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   12017:                                       .' '
                   12018:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   12019:                                           ,'<a href="'.$helplink.'">','</a>')
                   12020:                                       .'</p><br />';
1.627     raeburn  12021:                 }
1.576     raeburn  12022:             }
                   12023:         }
                   12024: 
1.556     raeburn  12025:         $newuserscript = <<"ENDSCRIPT";
                   12026: 
1.570     raeburn  12027: function setSearch(createnew,callingForm) {
1.556     raeburn  12028:     if (createnew == 1) {
1.570     raeburn  12029:         for (var i=0; i<callingForm.srchby.length; i++) {
                   12030:             if (callingForm.srchby.options[i].value == 'uname') {
                   12031:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  12032:             }
                   12033:         }
1.570     raeburn  12034:         for (var i=0; i<callingForm.srchin.length; i++) {
                   12035:             if ( callingForm.srchin.options[i].value == 'dom') {
                   12036: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  12037:             }
                   12038:         }
1.570     raeburn  12039:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   12040:             if (callingForm.srchtype.options[i].value == 'exact') {
                   12041:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  12042:             }
                   12043:         }
1.570     raeburn  12044:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  12045:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  12046:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  12047:             }
                   12048:         }
                   12049:     }
                   12050: }
                   12051: ENDSCRIPT
1.558     albertel 12052: 
1.556     raeburn  12053:     }
                   12054: 
1.555     raeburn  12055:     my $output = <<"END_BLOCK";
1.556     raeburn  12056: <script type="text/javascript">
1.824     bisitz   12057: // <![CDATA[
1.570     raeburn  12058: function validateEntry(callingForm) {
1.558     albertel 12059: 
1.556     raeburn  12060:     var checkok = 1;
1.558     albertel 12061:     var srchin;
1.570     raeburn  12062:     for (var i=0; i<callingForm.srchin.length; i++) {
                   12063: 	if ( callingForm.srchin[i].checked ) {
                   12064: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 12065: 	}
                   12066:     }
                   12067: 
1.570     raeburn  12068:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   12069:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   12070:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   12071:     var srchterm =  callingForm.srchterm.value;
                   12072:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  12073:     var msg = "";
                   12074: 
                   12075:     if (srchterm == "") {
                   12076:         checkok = 0;
1.1222    damieng  12077:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  12078:     }
                   12079: 
1.569     raeburn  12080:     if (srchtype== 'begins') {
                   12081:         if (srchterm.length < 2) {
                   12082:             checkok = 0;
1.1222    damieng  12083:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  12084:         }
                   12085:     }
                   12086: 
1.556     raeburn  12087:     if (srchtype== 'contains') {
                   12088:         if (srchterm.length < 3) {
                   12089:             checkok = 0;
1.1222    damieng  12090:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  12091:         }
                   12092:     }
                   12093:     if (srchin == 'instd') {
                   12094:         if (srchdomain == '') {
                   12095:             checkok = 0;
1.1222    damieng  12096:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  12097:         }
                   12098:     }
                   12099:     if (srchin == 'dom') {
                   12100:         if (srchdomain == '') {
                   12101:             checkok = 0;
1.1222    damieng  12102:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  12103:         }
                   12104:     }
                   12105:     if (srchby == 'lastfirst') {
                   12106:         if (srchterm.indexOf(",") == -1) {
                   12107:             checkok = 0;
1.1222    damieng  12108:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  12109:         }
                   12110:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   12111:             checkok = 0;
1.1222    damieng  12112:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  12113:         }
                   12114:     }
                   12115:     if (checkok == 0) {
1.1222    damieng  12116:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  12117:         return;
                   12118:     }
                   12119:     if (checkok == 1) {
1.570     raeburn  12120:         callingForm.submit();
1.556     raeburn  12121:     }
                   12122: }
                   12123: 
                   12124: $newuserscript
                   12125: 
1.824     bisitz   12126: // ]]>
1.556     raeburn  12127: </script>
1.558     albertel 12128: 
                   12129: $new_user_create
                   12130: 
1.555     raeburn  12131: END_BLOCK
1.558     albertel 12132: 
1.876     raeburn  12133:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  12134:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  12135:                $domform.
                   12136:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  12137:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  12138:                $srchbysel.
                   12139:                $srchtypesel. 
                   12140:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   12141:                $srchinsel.
                   12142:                &Apache::lonhtmlcommon::row_closure(1). 
                   12143:                &Apache::lonhtmlcommon::end_pick_box().
                   12144:                '<br />';
1.1253    raeburn  12145:     return ($output,1);
1.555     raeburn  12146: }
                   12147: 
1.612     raeburn  12148: sub user_rule_check {
1.615     raeburn  12149:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  12150:     my ($response,%inst_response);
1.612     raeburn  12151:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  12152:         if (keys(%{$usershash}) > 1) {
                   12153:             my (%by_username,%by_id,%userdoms);
                   12154:             my $checkid; 
                   12155:             if (ref($checks) eq 'HASH') {
                   12156:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   12157:                     $checkid = 1;
                   12158:                 }
                   12159:             }
                   12160:             foreach my $user (keys(%{$usershash})) {
                   12161:                 my ($uname,$udom) = split(/:/,$user);
                   12162:                 if ($checkid) {
                   12163:                     if (ref($usershash->{$user}) eq 'HASH') {
                   12164:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  12165:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  12166:                             $userdoms{$udom} = 1;
1.1227    raeburn  12167:                             if (ref($inst_results) eq 'HASH') {
                   12168:                                 $inst_results->{$uname.':'.$udom} = {};
                   12169:                             }
1.1226    raeburn  12170:                         }
                   12171:                     }
                   12172:                 } else {
                   12173:                     $by_username{$udom}{$uname} = 1;
                   12174:                     $userdoms{$udom} = 1;
1.1227    raeburn  12175:                     if (ref($inst_results) eq 'HASH') {
                   12176:                         $inst_results->{$uname.':'.$udom} = {};
                   12177:                     }
1.1226    raeburn  12178:                 }
                   12179:             }
                   12180:             foreach my $udom (keys(%userdoms)) {
                   12181:                 if (!$got_rules->{$udom}) {
                   12182:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12183:                                                              ['usercreation'],$udom);
                   12184:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12185:                         foreach my $item ('username','id') {
                   12186:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12187:                                 $$curr_rules{$udom}{$item} =
                   12188:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12189:                             }
                   12190:                         }
                   12191:                     }
                   12192:                     $got_rules->{$udom} = 1;
                   12193:                 }
1.612     raeburn  12194:             }
1.1226    raeburn  12195:             if ($checkid) {
                   12196:                 foreach my $udom (keys(%by_id)) {
                   12197:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12198:                     if ($outcome eq 'ok') {
1.1227    raeburn  12199:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12200:                             my $uname = $by_id{$udom}{$id};
                   12201:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12202:                         }
1.1226    raeburn  12203:                         if (ref($results) eq 'HASH') {
                   12204:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12205:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12206:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12207:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12208:                                 }
1.1226    raeburn  12209:                             }
                   12210:                         }
                   12211:                     }
1.612     raeburn  12212:                 }
1.615     raeburn  12213:             } else {
1.1226    raeburn  12214:                 foreach my $udom (keys(%by_username)) {
                   12215:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12216:                     if ($outcome eq 'ok') {
1.1227    raeburn  12217:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12218:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12219:                         }
1.1226    raeburn  12220:                         if (ref($results) eq 'HASH') {
                   12221:                             foreach my $uname (keys(%{$results})) {
                   12222:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12223:                             }
                   12224:                         }
                   12225:                     }
                   12226:                 }
1.612     raeburn  12227:             }
1.1226    raeburn  12228:         } elsif (keys(%{$usershash}) == 1) {
                   12229:             my $user = (keys(%{$usershash}))[0];
                   12230:             my ($uname,$udom) = split(/:/,$user);
                   12231:             if (($udom ne '') && ($uname ne '')) {
                   12232:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12233:                     if (ref($checks) eq 'HASH') {
                   12234:                         if (defined($checks->{'username'})) {
                   12235:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12236:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12237:                         } elsif (defined($checks->{'id'})) {
                   12238:                             if ($usershash->{$user}->{'id'} ne '') {
                   12239:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12240:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12241:                                                                   $usershash->{$user}->{'id'});
                   12242:                             } else {
                   12243:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12244:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12245:                             }
1.585     raeburn  12246:                         }
1.1226    raeburn  12247:                     } else {
                   12248:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12249:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12250:                        return;
                   12251:                     }
                   12252:                     if (!$got_rules->{$udom}) {
                   12253:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12254:                                                                  ['usercreation'],$udom);
                   12255:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12256:                             foreach my $item ('username','id') {
                   12257:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12258:                                    $$curr_rules{$udom}{$item} = 
                   12259:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12260:                                 }
                   12261:                             }
                   12262:                         }
                   12263:                         $got_rules->{$udom} = 1;
1.585     raeburn  12264:                     }
                   12265:                 }
1.1226    raeburn  12266:             } else {
                   12267:                 return;
                   12268:             }
                   12269:         } else {
                   12270:             return;
                   12271:         }
                   12272:         foreach my $user (keys(%{$usershash})) {
                   12273:             my ($uname,$udom) = split(/:/,$user);
                   12274:             next if (($udom eq '') || ($uname eq ''));
                   12275:             my $id;
1.1227    raeburn  12276:             if (ref($inst_results) eq 'HASH') {
                   12277:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12278:                     $id = $inst_results->{$user}->{'id'};
                   12279:                 }
                   12280:             }
                   12281:             if ($id eq '') { 
                   12282:                 if (ref($usershash->{$user})) {
                   12283:                     $id = $usershash->{$user}->{'id'};
                   12284:                 }
1.585     raeburn  12285:             }
1.612     raeburn  12286:             foreach my $item (keys(%{$checks})) {
                   12287:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12288:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12289:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12290:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12291:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12292:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12293:                                 if ($rule_check{$rule}) {
                   12294:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12295:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12296:                                         if (ref($inst_results) eq 'HASH') {
                   12297:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12298:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12299:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12300:                                                 } elsif ($item eq 'id') {
                   12301:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12302:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12303:                                                     }
1.615     raeburn  12304:                                                 }
1.612     raeburn  12305:                                             }
                   12306:                                         }
1.615     raeburn  12307:                                     }
                   12308:                                     last;
1.585     raeburn  12309:                                 }
                   12310:                             }
                   12311:                         }
                   12312:                     }
                   12313:                 }
                   12314:             }
                   12315:         }
                   12316:     }
1.612     raeburn  12317:     return;
                   12318: }
                   12319: 
                   12320: sub user_rule_formats {
                   12321:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12322:     my %text = ( 
                   12323:                  'username' => 'Usernames',
                   12324:                  'id'       => 'IDs',
                   12325:                );
                   12326:     my $output;
                   12327:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12328:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12329:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12330:             $output = '<br />'.
                   12331:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12332:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12333:                       ' <ul>';
1.612     raeburn  12334:             foreach my $rule (@{$ruleorder}) {
                   12335:                 if (ref($curr_rules) eq 'ARRAY') {
                   12336:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12337:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12338:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12339:                                         $rules->{$rule}{'desc'}.'</li>';
                   12340:                         }
                   12341:                     }
                   12342:                 }
                   12343:             }
                   12344:             $output .= '</ul>';
                   12345:         }
                   12346:     }
                   12347:     return $output;
                   12348: }
                   12349: 
                   12350: sub instrule_disallow_msg {
1.615     raeburn  12351:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12352:     my $response;
                   12353:     my %text = (
                   12354:                   item   => 'username',
                   12355:                   items  => 'usernames',
                   12356:                   match  => 'matches',
                   12357:                   do     => 'does',
                   12358:                   action => 'a username',
                   12359:                   one    => 'one',
                   12360:                );
                   12361:     if ($count > 1) {
                   12362:         $text{'item'} = 'usernames';
                   12363:         $text{'match'} ='match';
                   12364:         $text{'do'} = 'do';
                   12365:         $text{'action'} = 'usernames',
                   12366:         $text{'one'} = 'ones';
                   12367:     }
                   12368:     if ($checkitem eq 'id') {
                   12369:         $text{'items'} = 'IDs';
                   12370:         $text{'item'} = 'ID';
                   12371:         $text{'action'} = 'an ID';
1.615     raeburn  12372:         if ($count > 1) {
                   12373:             $text{'item'} = 'IDs';
                   12374:             $text{'action'} = 'IDs';
                   12375:         }
1.612     raeburn  12376:     }
1.674     bisitz   12377:     $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  12378:     if ($mode eq 'upload') {
                   12379:         if ($checkitem eq 'username') {
                   12380:             $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'}.");
                   12381:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12382:             $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  12383:         }
1.669     raeburn  12384:     } elsif ($mode eq 'selfcreate') {
                   12385:         if ($checkitem eq 'id') {
                   12386:             $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.");
                   12387:         }
1.615     raeburn  12388:     } else {
                   12389:         if ($checkitem eq 'username') {
                   12390:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12391:         } elsif ($checkitem eq 'id') {
                   12392:             $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.");
                   12393:         }
1.612     raeburn  12394:     }
                   12395:     return $response;
1.585     raeburn  12396: }
                   12397: 
1.624     raeburn  12398: sub personal_data_fieldtitles {
                   12399:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12400:                         id => 'Student/Employee ID',
                   12401:                         permanentemail => 'E-mail address',
                   12402:                         lastname => 'Last Name',
                   12403:                         firstname => 'First Name',
                   12404:                         middlename => 'Middle Name',
                   12405:                         generation => 'Generation',
                   12406:                         gen => 'Generation',
1.765     raeburn  12407:                         inststatus => 'Affiliation',
1.624     raeburn  12408:                    );
                   12409:     return %fieldtitles;
                   12410: }
                   12411: 
1.642     raeburn  12412: sub sorted_inst_types {
                   12413:     my ($dom) = @_;
1.1185    raeburn  12414:     my ($usertypes,$order);
                   12415:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12416:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12417:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12418:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12419:     } else {
                   12420:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12421:     }
1.642     raeburn  12422:     my $othertitle = &mt('All users');
                   12423:     if ($env{'request.course.id'}) {
1.668     raeburn  12424:         $othertitle  = &mt('Any users');
1.642     raeburn  12425:     }
                   12426:     my @types;
                   12427:     if (ref($order) eq 'ARRAY') {
                   12428:         @types = @{$order};
                   12429:     }
                   12430:     if (@types == 0) {
                   12431:         if (ref($usertypes) eq 'HASH') {
                   12432:             @types = sort(keys(%{$usertypes}));
                   12433:         }
                   12434:     }
                   12435:     if (keys(%{$usertypes}) > 0) {
                   12436:         $othertitle = &mt('Other users');
                   12437:     }
                   12438:     return ($othertitle,$usertypes,\@types);
                   12439: }
                   12440: 
1.645     raeburn  12441: sub get_institutional_codes {
1.1361    raeburn  12442:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12443: # Get complete list of course sections to update
                   12444:     my @currsections = ();
                   12445:     my @currxlists = ();
1.1361    raeburn  12446:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12447:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12448:     my $crskey = $crs.':'.$coursecode;
                   12449:     @{$unclutteredsec{$crskey}} = ();
                   12450:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12451: 
                   12452:     if ($$settings{'internal.sectionnums'} ne '') {
                   12453:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12454:     }
                   12455: 
                   12456:     if ($$settings{'internal.crosslistings'} ne '') {
                   12457:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12458:     }
                   12459: 
                   12460:     if (@currxlists > 0) {
1.1361    raeburn  12461:         foreach my $xl (@currxlists) {
                   12462:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12463:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12464:                     push(@{$allcourses},$1);
1.645     raeburn  12465:                     $$LC_code{$1} = $2;
                   12466:                 }
                   12467:             }
                   12468:         }
                   12469:     }
1.1361    raeburn  12470: 
1.645     raeburn  12471:     if (@currsections > 0) {
1.1361    raeburn  12472:         foreach my $sec (@currsections) {
                   12473:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12474:                 my $instsec = $1;
1.645     raeburn  12475:                 my $lc_sec = $2;
1.1361    raeburn  12476:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12477:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12478:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12479:                 }
                   12480:             }
                   12481:         }
                   12482:     }
                   12483: 
                   12484:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12485:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12486:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12487:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12488:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12489:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12490:                     push(@{$allcourses},$sec);
1.1361    raeburn  12491:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12492:                 }
                   12493:             }
                   12494:         }
                   12495:     }
                   12496:     return;
                   12497: }
                   12498: 
1.971     raeburn  12499: sub get_standard_codeitems {
                   12500:     return ('Year','Semester','Department','Number','Section');
                   12501: }
                   12502: 
1.112     bowersj2 12503: =pod
                   12504: 
1.780     raeburn  12505: =head1 Slot Helpers
                   12506: 
                   12507: =over 4
                   12508: 
                   12509: =item * sorted_slots()
                   12510: 
1.1040    raeburn  12511: Sorts an array of slot names in order of an optional sort key,
                   12512: default sort is by slot start time (earliest first). 
1.780     raeburn  12513: 
                   12514: Inputs:
                   12515: 
                   12516: =over 4
                   12517: 
                   12518: slotsarr  - Reference to array of unsorted slot names.
                   12519: 
                   12520: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12521: 
1.1040    raeburn  12522: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12523: 
1.549     albertel 12524: =back
                   12525: 
1.780     raeburn  12526: Returns:
                   12527: 
                   12528: =over 4
                   12529: 
1.1040    raeburn  12530: sorted   - An array of slot names sorted by a specified sort key 
                   12531:            (default sort key is start time of the slot).
1.780     raeburn  12532: 
                   12533: =back
                   12534: 
                   12535: =cut
                   12536: 
                   12537: 
                   12538: sub sorted_slots {
1.1040    raeburn  12539:     my ($slotsarr,$slots,$sortkey) = @_;
                   12540:     if ($sortkey eq '') {
                   12541:         $sortkey = 'starttime';
                   12542:     }
1.780     raeburn  12543:     my @sorted;
                   12544:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12545:         @sorted =
                   12546:             sort {
                   12547:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12548:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12549:                      }
                   12550:                      if (ref($slots->{$a})) { return -1;}
                   12551:                      if (ref($slots->{$b})) { return 1;}
                   12552:                      return 0;
                   12553:                  } @{$slotsarr};
                   12554:     }
                   12555:     return @sorted;
                   12556: }
                   12557: 
1.1040    raeburn  12558: =pod
                   12559: 
                   12560: =item * get_future_slots()
                   12561: 
                   12562: Inputs:
                   12563: 
                   12564: =over 4
                   12565: 
                   12566: cnum - course number
                   12567: 
                   12568: cdom - course domain
                   12569: 
                   12570: now - current UNIX time
                   12571: 
                   12572: symb - optional symb
                   12573: 
                   12574: =back
                   12575: 
                   12576: Returns:
                   12577: 
                   12578: =over 4
                   12579: 
                   12580: sorted_reservable - ref to array of student_schedulable slots currently 
                   12581:                     reservable, ordered by end date of reservation period.
                   12582: 
                   12583: reservable_now - ref to hash of student_schedulable slots currently
                   12584:                  reservable.
                   12585: 
                   12586:     Keys in inner hash are:
                   12587:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12588:     (b) endreserve: end date of reservation period.
                   12589:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12590:         selected.
1.1040    raeburn  12591: 
                   12592: sorted_future - ref to array of student_schedulable slots reservable in
                   12593:                 the future, ordered by start date of reservation period.
                   12594: 
                   12595: future_reservable - ref to hash of student_schedulable slots reservable
                   12596:                     in the future.
                   12597: 
                   12598:     Keys in inner hash are:
                   12599:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12600:     (b) startreserve: start date of reservation period.
                   12601:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12602:         selected.
1.1040    raeburn  12603: 
                   12604: =back
                   12605: 
                   12606: =cut
                   12607: 
                   12608: sub get_future_slots {
                   12609:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12610:     my $map;
                   12611:     if ($symb) {
                   12612:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12613:     }
1.1040    raeburn  12614:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12615:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12616:     foreach my $slot (keys(%slots)) {
                   12617:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12618:         if ($symb) {
1.1229    raeburn  12619:             if ($slots{$slot}->{'symb'} ne '') {
                   12620:                 my $canuse;
                   12621:                 my %oksymbs;
                   12622:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12623:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12624:                 if ($oksymbs{$symb}) {
                   12625:                     $canuse = 1;
                   12626:                 } else {
                   12627:                     foreach my $item (@slotsymbs) {
                   12628:                         if ($item =~ /\.(page|sequence)$/) {
                   12629:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12630:                             if (($map ne '') && ($map eq $sloturl)) {
                   12631:                                 $canuse = 1;
                   12632:                                 last;
                   12633:                             }
                   12634:                         }
                   12635:                     }
                   12636:                 }
                   12637:                 next unless ($canuse);
                   12638:             }
1.1040    raeburn  12639:         }
                   12640:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12641:             ($slots{$slot}->{'endtime'} > $now)) {
                   12642:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12643:                 my $userallowed = 0;
                   12644:                 if ($slots{$slot}->{'allowedsections'}) {
                   12645:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12646:                     if (!defined($env{'request.role.sec'})
                   12647:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12648:                         $userallowed=1;
                   12649:                     } else {
                   12650:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12651:                             $userallowed=1;
                   12652:                         }
                   12653:                     }
                   12654:                     unless ($userallowed) {
                   12655:                         if (defined($env{'request.course.groups'})) {
                   12656:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12657:                             foreach my $group (@groups) {
                   12658:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12659:                                     $userallowed=1;
                   12660:                                     last;
                   12661:                                 }
                   12662:                             }
                   12663:                         }
                   12664:                     }
                   12665:                 }
                   12666:                 if ($slots{$slot}->{'allowedusers'}) {
                   12667:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12668:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12669:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12670:                         $userallowed = 1;
                   12671:                     }
                   12672:                 }
                   12673:                 next unless($userallowed);
                   12674:             }
                   12675:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12676:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12677:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12678:             my $uniqueperiod;
                   12679:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12680:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12681:             }
1.1040    raeburn  12682:             if (($startreserve < $now) &&
                   12683:                 (!$endreserve || $endreserve > $now)) {
                   12684:                 my $lastres = $endreserve;
                   12685:                 if (!$lastres) {
                   12686:                     $lastres = $slots{$slot}->{'starttime'};
                   12687:                 }
                   12688:                 $reservable_now{$slot} = {
                   12689:                                            symb       => $symb,
1.1250    raeburn  12690:                                            endreserve => $lastres,
                   12691:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12692:                                          };
                   12693:             } elsif (($startreserve > $now) &&
                   12694:                      (!$endreserve || $endreserve > $startreserve)) {
                   12695:                 $future_reservable{$slot} = {
                   12696:                                               symb         => $symb,
1.1250    raeburn  12697:                                               startreserve => $startreserve,
                   12698:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12699:                                             };
                   12700:             }
                   12701:         }
                   12702:     }
                   12703:     my @unsorted_reservable = keys(%reservable_now);
                   12704:     if (@unsorted_reservable > 0) {
                   12705:         @sorted_reservable = 
                   12706:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12707:     }
                   12708:     my @unsorted_future = keys(%future_reservable);
                   12709:     if (@unsorted_future > 0) {
                   12710:         @sorted_future =
                   12711:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12712:     }
                   12713:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12714: }
1.780     raeburn  12715: 
                   12716: =pod
                   12717: 
1.1057    foxr     12718: =back
                   12719: 
1.549     albertel 12720: =head1 HTTP Helpers
                   12721: 
                   12722: =over 4
                   12723: 
1.648     raeburn  12724: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12725: 
1.258     albertel 12726: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12727: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12728: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12729: 
                   12730: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12731: $possible_names is an ref to an array of form element names.  As an example:
                   12732: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12733: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12734: 
                   12735: =cut
1.1       albertel 12736: 
1.6       albertel 12737: sub get_unprocessed_cgi {
1.25      albertel 12738:   my ($query,$possible_names)= @_;
1.26      matthew  12739:   # $Apache::lonxml::debug=1;
1.356     albertel 12740:   foreach my $pair (split(/&/,$query)) {
                   12741:     my ($name, $value) = split(/=/,$pair);
1.369     www      12742:     $name = &unescape($name);
1.25      albertel 12743:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12744:       $value =~ tr/+/ /;
                   12745:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12746:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12747:     }
1.16      harris41 12748:   }
1.6       albertel 12749: }
                   12750: 
1.112     bowersj2 12751: =pod
                   12752: 
1.648     raeburn  12753: =item * &cacheheader() 
1.112     bowersj2 12754: 
                   12755: returns cache-controlling header code
                   12756: 
                   12757: =cut
                   12758: 
1.7       albertel 12759: sub cacheheader {
1.258     albertel 12760:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12761:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12762:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12763:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12764:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12765:     return $output;
1.7       albertel 12766: }
                   12767: 
1.112     bowersj2 12768: =pod
                   12769: 
1.648     raeburn  12770: =item * &no_cache($r) 
1.112     bowersj2 12771: 
                   12772: specifies header code to not have cache
                   12773: 
                   12774: =cut
                   12775: 
1.9       albertel 12776: sub no_cache {
1.216     albertel 12777:     my ($r) = @_;
                   12778:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12779: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12780:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12781:     $r->no_cache(1);
                   12782:     $r->header_out("Expires" => $date);
                   12783:     $r->header_out("Pragma" => "no-cache");
1.123     www      12784: }
                   12785: 
                   12786: sub content_type {
1.181     albertel 12787:     my ($r,$type,$charset) = @_;
1.299     foxr     12788:     if ($r) {
                   12789: 	#  Note that printout.pl calls this with undef for $r.
                   12790: 	&no_cache($r);
                   12791:     }
1.258     albertel 12792:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12793:     unless ($charset) {
                   12794: 	$charset=&Apache::lonlocal::current_encoding;
                   12795:     }
                   12796:     if ($charset) { $type.='; charset='.$charset; }
                   12797:     if ($r) {
                   12798: 	$r->content_type($type);
                   12799:     } else {
                   12800: 	print("Content-type: $type\n\n");
                   12801:     }
1.9       albertel 12802: }
1.25      albertel 12803: 
1.112     bowersj2 12804: =pod
                   12805: 
1.648     raeburn  12806: =item * &add_to_env($name,$value) 
1.112     bowersj2 12807: 
1.258     albertel 12808: adds $name to the %env hash with value
1.112     bowersj2 12809: $value, if $name already exists, the entry is converted to an array
                   12810: reference and $value is added to the array.
                   12811: 
                   12812: =cut
                   12813: 
1.25      albertel 12814: sub add_to_env {
                   12815:   my ($name,$value)=@_;
1.258     albertel 12816:   if (defined($env{$name})) {
                   12817:     if (ref($env{$name})) {
1.25      albertel 12818:       #already have multiple values
1.258     albertel 12819:       push(@{ $env{$name} },$value);
1.25      albertel 12820:     } else {
                   12821:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12822:       my $first=$env{$name};
                   12823:       undef($env{$name});
                   12824:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12825:     }
                   12826:   } else {
1.258     albertel 12827:     $env{$name}=$value;
1.25      albertel 12828:   }
1.31      albertel 12829: }
1.149     albertel 12830: 
                   12831: =pod
                   12832: 
1.648     raeburn  12833: =item * &get_env_multiple($name) 
1.149     albertel 12834: 
1.258     albertel 12835: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12836: values may be defined and end up as an array ref.
                   12837: 
                   12838: returns an array of values
                   12839: 
                   12840: =cut
                   12841: 
                   12842: sub get_env_multiple {
                   12843:     my ($name) = @_;
                   12844:     my @values;
1.258     albertel 12845:     if (defined($env{$name})) {
1.149     albertel 12846:         # exists is it an array
1.258     albertel 12847:         if (ref($env{$name})) {
                   12848:             @values=@{ $env{$name} };
1.149     albertel 12849:         } else {
1.258     albertel 12850:             $values[0]=$env{$name};
1.149     albertel 12851:         }
                   12852:     }
                   12853:     return(@values);
                   12854: }
                   12855: 
1.1249    damieng  12856: # Looks at given dependencies, and returns something depending on the context.
                   12857: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12858: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12859: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12860: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12861: # $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.
                   12862: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12863: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12864: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12865: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12866: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12867: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12868: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12869: # @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)
                   12870: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12871: sub ask_for_embedded_content {
1.1249    damieng  12872:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12873:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12874:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12875:         %currsubfile,%unused,$rem);
1.1071    raeburn  12876:     my $counter = 0;
                   12877:     my $numnew = 0;
1.987     raeburn  12878:     my $numremref = 0;
                   12879:     my $numinvalid = 0;
                   12880:     my $numpathchg = 0;
                   12881:     my $numexisting = 0;
1.1071    raeburn  12882:     my $numunused = 0;
                   12883:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12884:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12885:     my $heading = &mt('Upload embedded files');
                   12886:     my $buttontext = &mt('Upload');
                   12887: 
1.1249    damieng  12888:     # fills these variables based on the context:
                   12889:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12890:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12891:     if ($env{'request.course.id'}) {
1.1123    raeburn  12892:         if ($actionurl eq '/adm/dependencies') {
                   12893:             $navmap = Apache::lonnavmaps::navmap->new();
                   12894:         }
                   12895:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12896:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12897:     }
1.1123    raeburn  12898:     if (($actionurl eq '/adm/portfolio') || 
                   12899:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12900:         my $current_path='/';
                   12901:         if ($env{'form.currentpath'}) {
                   12902:             $current_path = $env{'form.currentpath'};
                   12903:         }
                   12904:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12905:             $udom = $cdom;
                   12906:             $uname = $cnum;
1.984     raeburn  12907:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12908:         } else {
                   12909:             $udom = $env{'user.domain'};
                   12910:             $uname = $env{'user.name'};
                   12911:             $url = '/userfiles/portfolio';
                   12912:         }
1.987     raeburn  12913:         $toplevel = $url.'/';
1.984     raeburn  12914:         $url .= $current_path;
                   12915:         $getpropath = 1;
1.987     raeburn  12916:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12917:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12918:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12919:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12920:         $toplevel = $url;
1.984     raeburn  12921:         if ($rest ne '') {
1.987     raeburn  12922:             $url .= $rest;
                   12923:         }
                   12924:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12925:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12926:             $url = $args->{'docs_url'};
                   12927:             $toplevel = $url;
1.1084    raeburn  12928:             if ($args->{'context'} eq 'paste') {
                   12929:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12930:                 ($path) = 
                   12931:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12932:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12933:                 $fileloc =~ s{^/}{};
                   12934:             }
1.1071    raeburn  12935:         }
1.1084    raeburn  12936:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12937:         if ($env{'request.course.id'} ne '') {
                   12938:             if (ref($args) eq 'HASH') {
                   12939:                 $url = $args->{'docs_url'};
                   12940:                 $title = $args->{'docs_title'};
1.1126    raeburn  12941:                 $toplevel = $url; 
                   12942:                 unless ($toplevel =~ m{^/}) {
                   12943:                     $toplevel = "/$url";
                   12944:                 }
1.1085    raeburn  12945:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12946:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12947:                     $path = $1;
                   12948:                 } else {
                   12949:                     ($path) =
                   12950:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12951:                 }
1.1195    raeburn  12952:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12953:                     $fileloc = $toplevel;
                   12954:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12955:                     my ($udom,$uname,$fname) =
                   12956:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12957:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12958:                 } else {
                   12959:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12960:                 }
1.1071    raeburn  12961:                 $fileloc =~ s{^/}{};
                   12962:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12963:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12964:             }
1.987     raeburn  12965:         }
1.1123    raeburn  12966:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12967:         $udom = $cdom;
                   12968:         $uname = $cnum;
                   12969:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12970:         $toplevel = $url;
                   12971:         $path = $url;
                   12972:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12973:         $fileloc =~ s{^/}{};
1.987     raeburn  12974:     }
1.1249    damieng  12975:     
                   12976:     # parses the dependency paths to get some info
                   12977:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12978:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12979:     # (will be completed later)
                   12980:     # $mapping:
                   12981:     #   for external URLs: external URL -> external URL
                   12982:     #   for relative paths: clean path -> original path
                   12983:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12984:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12985:     foreach my $file (keys(%{$allfiles})) {
                   12986:         my $embed_file;
                   12987:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12988:             $embed_file = $1;
                   12989:         } else {
                   12990:             $embed_file = $file;
                   12991:         }
1.1158    raeburn  12992:         my ($absolutepath,$cleaned_file);
                   12993:         if ($embed_file =~ m{^\w+://}) {
                   12994:             $cleaned_file = $embed_file;
1.1147    raeburn  12995:             $newfiles{$cleaned_file} = 1;
                   12996:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12997:         } else {
1.1158    raeburn  12998:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12999:             if ($embed_file =~ m{^/}) {
                   13000:                 $absolutepath = $embed_file;
                   13001:             }
1.1147    raeburn  13002:             if ($cleaned_file =~ m{/}) {
                   13003:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  13004:                 $path = &check_for_traversal($path,$url,$toplevel);
                   13005:                 my $item = $fname;
                   13006:                 if ($path ne '') {
                   13007:                     $item = $path.'/'.$fname;
                   13008:                     $subdependencies{$path}{$fname} = 1;
                   13009:                 } else {
                   13010:                     $dependencies{$item} = 1;
                   13011:                 }
                   13012:                 if ($absolutepath) {
                   13013:                     $mapping{$item} = $absolutepath;
                   13014:                 } else {
                   13015:                     $mapping{$item} = $embed_file;
                   13016:                 }
                   13017:             } else {
                   13018:                 $dependencies{$embed_file} = 1;
                   13019:                 if ($absolutepath) {
1.1147    raeburn  13020:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  13021:                 } else {
1.1147    raeburn  13022:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  13023:                 }
                   13024:             }
1.984     raeburn  13025:         }
                   13026:     }
1.1249    damieng  13027:     
                   13028:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   13029:     # and lists
                   13030:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   13031:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   13032:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   13033:     #                                    the path had to be cleaned up
                   13034:     # $existing: hash clean path -> 1 if the file exists
                   13035:     # $numexisting: number of keys in $existing
                   13036:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   13037:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   13038:     #                                      dependency subdirectories that are
                   13039:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  13040:     my $dirptr = 16384;
1.984     raeburn  13041:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  13042:         $currsubfile{$path} = {};
1.1123    raeburn  13043:         if (($actionurl eq '/adm/portfolio') || 
                   13044:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13045:             my ($sublistref,$listerror) =
                   13046:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   13047:             if (ref($sublistref) eq 'ARRAY') {
                   13048:                 foreach my $line (@{$sublistref}) {
                   13049:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  13050:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  13051:                 }
1.984     raeburn  13052:             }
1.987     raeburn  13053:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13054:             if (opendir(my $dir,$url.'/'.$path)) {
                   13055:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  13056:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   13057:             }
1.1084    raeburn  13058:         } elsif (($actionurl eq '/adm/dependencies') ||
                   13059:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13060:                   ($args->{'context'} eq 'paste')) ||
                   13061:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13062:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  13063:                 my $dir;
                   13064:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   13065:                     $dir = $fileloc;
                   13066:                 } else {
                   13067:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13068:                 }
1.1071    raeburn  13069:                 if ($dir ne '') {
                   13070:                     my ($sublistref,$listerror) =
                   13071:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   13072:                     if (ref($sublistref) eq 'ARRAY') {
                   13073:                         foreach my $line (@{$sublistref}) {
                   13074:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   13075:                                 undef,$mtime)=split(/\&/,$line,12);
                   13076:                             unless (($testdir&$dirptr) ||
                   13077:                                     ($file_name =~ /^\.\.?$/)) {
                   13078:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   13079:                             }
                   13080:                         }
                   13081:                     }
                   13082:                 }
1.984     raeburn  13083:             }
                   13084:         }
                   13085:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  13086:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  13087:                 my $item = $path.'/'.$file;
                   13088:                 unless ($mapping{$item} eq $item) {
                   13089:                     $pathchanges{$item} = 1;
                   13090:                 }
                   13091:                 $existing{$item} = 1;
                   13092:                 $numexisting ++;
                   13093:             } else {
                   13094:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  13095:             }
                   13096:         }
1.1071    raeburn  13097:         if ($actionurl eq '/adm/dependencies') {
                   13098:             foreach my $path (keys(%currsubfile)) {
                   13099:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   13100:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   13101:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  13102:                              next if (($rem ne '') &&
                   13103:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   13104:                                        (ref($navmap) &&
                   13105:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   13106:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13107:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  13108:                              $unused{$path.'/'.$file} = 1; 
                   13109:                          }
                   13110:                     }
                   13111:                 }
                   13112:             }
                   13113:         }
1.984     raeburn  13114:     }
1.1249    damieng  13115:     
                   13116:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   13117:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  13118:     my %currfile;
1.1123    raeburn  13119:     if (($actionurl eq '/adm/portfolio') ||
                   13120:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  13121:         my ($dirlistref,$listerror) =
                   13122:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   13123:         if (ref($dirlistref) eq 'ARRAY') {
                   13124:             foreach my $line (@{$dirlistref}) {
                   13125:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   13126:                 $currfile{$file_name} = 1;
                   13127:             }
1.984     raeburn  13128:         }
1.987     raeburn  13129:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  13130:         if (opendir(my $dir,$url)) {
1.987     raeburn  13131:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  13132:             map {$currfile{$_} = 1;} @dir_list;
                   13133:         }
1.1084    raeburn  13134:     } elsif (($actionurl eq '/adm/dependencies') ||
                   13135:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  13136:               ($args->{'context'} eq 'paste')) ||
                   13137:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  13138:         if ($env{'request.course.id'} ne '') {
                   13139:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   13140:             if ($dir ne '') {
                   13141:                 my ($dirlistref,$listerror) =
                   13142:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   13143:                 if (ref($dirlistref) eq 'ARRAY') {
                   13144:                     foreach my $line (@{$dirlistref}) {
                   13145:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   13146:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   13147:                         unless (($testdir&$dirptr) ||
                   13148:                                 ($file_name =~ /^\.\.?$/)) {
                   13149:                             $currfile{$file_name} = [$size,$mtime];
                   13150:                         }
                   13151:                     }
                   13152:                 }
                   13153:             }
                   13154:         }
1.984     raeburn  13155:     }
1.1249    damieng  13156:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   13157:     # are not in subdirectories, using $currfile
1.984     raeburn  13158:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  13159:         if (exists($currfile{$file})) {
1.987     raeburn  13160:             unless ($mapping{$file} eq $file) {
                   13161:                 $pathchanges{$file} = 1;
                   13162:             }
                   13163:             $existing{$file} = 1;
                   13164:             $numexisting ++;
                   13165:         } else {
1.984     raeburn  13166:             $newfiles{$file} = 1;
                   13167:         }
                   13168:     }
1.1071    raeburn  13169:     foreach my $file (keys(%currfile)) {
                   13170:         unless (($file eq $filename) ||
                   13171:                 ($file eq $filename.'.bak') ||
                   13172:                 ($dependencies{$file})) {
1.1085    raeburn  13173:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13174:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13175:                     next if (($rem ne '') &&
                   13176:                              (($env{"httpref.$rem".$file} ne '') ||
                   13177:                               (ref($navmap) &&
                   13178:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13179:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13180:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13181:                 }
1.1085    raeburn  13182:             }
1.1071    raeburn  13183:             $unused{$file} = 1;
                   13184:         }
                   13185:     }
1.1249    damieng  13186:     
                   13187:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13188:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13189:         ($args->{'context'} eq 'paste')) {
                   13190:         $counter = scalar(keys(%existing));
                   13191:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13192:         return ($output,$counter,$numpathchg,\%existing);
                   13193:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13194:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13195:         $counter = scalar(keys(%existing));
                   13196:         $numpathchg = scalar(keys(%pathchanges));
                   13197:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13198:     }
1.1249    damieng  13199:     
                   13200:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13201:     
                   13202:     # $upload_output: missing dependencies (with upload form)
                   13203:     # $modify_output: uploaded dependencies (in use)
                   13204:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13205:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13206:         if ($actionurl eq '/adm/dependencies') {
                   13207:             next if ($embed_file =~ m{^\w+://});
                   13208:         }
1.660     raeburn  13209:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13210:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13211:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13212:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13213:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13214:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13215:         }
1.1123    raeburn  13216:         $upload_output .= '</td>';
1.1071    raeburn  13217:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13218:             $upload_output.='<td align="right">'.
                   13219:                             '<span class="LC_info LC_fontsize_medium">'.
                   13220:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13221:             $numremref++;
1.660     raeburn  13222:         } elsif ($args->{'error_on_invalid_names'}
                   13223:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13224:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13225:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13226:             $numinvalid++;
1.660     raeburn  13227:         } else {
1.1123    raeburn  13228:             $upload_output .= '<td>'.
                   13229:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13230:                                                      $embed_file,\%mapping,
1.1071    raeburn  13231:                                                      $allfiles,$codebase,'upload');
                   13232:             $counter ++;
                   13233:             $numnew ++;
1.987     raeburn  13234:         }
                   13235:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13236:     }
                   13237:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13238:         if ($actionurl eq '/adm/dependencies') {
                   13239:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13240:             $modify_output .= &start_data_table_row().
                   13241:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13242:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13243:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13244:                               '<td>'.$size.'</td>'.
                   13245:                               '<td>'.$mtime.'</td>'.
                   13246:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13247:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13248:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13249:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13250:                               &embedded_file_element('upload_embedded',$counter,
                   13251:                                                      $embed_file,\%mapping,
                   13252:                                                      $allfiles,$codebase,'modify').
                   13253:                               '</div></td>'.
                   13254:                               &end_data_table_row()."\n";
                   13255:             $counter ++;
                   13256:         } else {
                   13257:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13258:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13259:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13260:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13261:                               &Apache::loncommon::end_data_table_row()."\n";
                   13262:         }
                   13263:     }
                   13264:     my $delidx = $counter;
                   13265:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13266:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13267:         $delete_output .= &start_data_table_row().
                   13268:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13269:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13270:                           '<td>'.$size.'</td>'.
                   13271:                           '<td>'.$mtime.'</td>'.
                   13272:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13273:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13274:                           &embedded_file_element('upload_embedded',$delidx,
                   13275:                                                  $oldfile,\%mapping,$allfiles,
                   13276:                                                  $codebase,'delete').'</td>'.
                   13277:                           &end_data_table_row()."\n"; 
                   13278:         $numunused ++;
                   13279:         $delidx ++;
1.987     raeburn  13280:     }
                   13281:     if ($upload_output) {
                   13282:         $upload_output = &start_data_table().
                   13283:                          $upload_output.
                   13284:                          &end_data_table()."\n";
                   13285:     }
1.1071    raeburn  13286:     if ($modify_output) {
                   13287:         $modify_output = &start_data_table().
                   13288:                          &start_data_table_header_row().
                   13289:                          '<th>'.&mt('File').'</th>'.
                   13290:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13291:                          '<th>'.&mt('Modified').'</th>'.
                   13292:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13293:                          &end_data_table_header_row().
                   13294:                          $modify_output.
                   13295:                          &end_data_table()."\n";
                   13296:     }
                   13297:     if ($delete_output) {
                   13298:         $delete_output = &start_data_table().
                   13299:                          &start_data_table_header_row().
                   13300:                          '<th>'.&mt('File').'</th>'.
                   13301:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13302:                          '<th>'.&mt('Modified').'</th>'.
                   13303:                          '<th>'.&mt('Delete?').'</th>'.
                   13304:                          &end_data_table_header_row().
                   13305:                          $delete_output.
                   13306:                          &end_data_table()."\n";
                   13307:     }
1.987     raeburn  13308:     my $applies = 0;
                   13309:     if ($numremref) {
                   13310:         $applies ++;
                   13311:     }
                   13312:     if ($numinvalid) {
                   13313:         $applies ++;
                   13314:     }
                   13315:     if ($numexisting) {
                   13316:         $applies ++;
                   13317:     }
1.1071    raeburn  13318:     if ($counter || $numunused) {
1.987     raeburn  13319:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13320:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13321:                   $state.'<h3>'.$heading.'</h3>'; 
                   13322:         if ($actionurl eq '/adm/dependencies') {
                   13323:             if ($numnew) {
                   13324:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13325:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13326:                            $upload_output.'<br />'."\n";
                   13327:             }
                   13328:             if ($numexisting) {
                   13329:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13330:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13331:                            $modify_output.'<br />'."\n";
                   13332:                            $buttontext = &mt('Save changes');
                   13333:             }
                   13334:             if ($numunused) {
                   13335:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13336:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13337:                            $delete_output.'<br />'."\n";
                   13338:                            $buttontext = &mt('Save changes');
                   13339:             }
                   13340:         } else {
                   13341:             $output .= $upload_output.'<br />'."\n";
                   13342:         }
                   13343:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13344:                    $counter.'" />'."\n";
                   13345:         if ($actionurl eq '/adm/dependencies') { 
                   13346:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13347:                        $numnew.'" />'."\n";
                   13348:         } elsif ($actionurl eq '') {
1.987     raeburn  13349:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13350:         }
                   13351:     } elsif ($applies) {
                   13352:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13353:         if ($applies > 1) {
                   13354:             $output .=  
1.1123    raeburn  13355:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13356:             if ($numremref) {
                   13357:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13358:             }
                   13359:             if ($numinvalid) {
                   13360:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13361:             }
                   13362:             if ($numexisting) {
                   13363:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13364:             }
                   13365:             $output .= '</ul><br />';
                   13366:         } elsif ($numremref) {
                   13367:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13368:         } elsif ($numinvalid) {
                   13369:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13370:         } elsif ($numexisting) {
                   13371:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13372:         }
                   13373:         $output .= $upload_output.'<br />';
                   13374:     }
                   13375:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13376:     $chgcount = $counter;
1.987     raeburn  13377:     if (keys(%pathchanges) > 0) {
                   13378:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13379:             if ($counter) {
1.987     raeburn  13380:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13381:                                                   $embed_file,\%mapping,
1.1071    raeburn  13382:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13383:             } else {
                   13384:                 $pathchange_output .= 
                   13385:                     &start_data_table_row().
                   13386:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13387:                     $chgcount.'" checked="checked" /></td>'.
                   13388:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13389:                     '<td>'.$embed_file.
                   13390:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13391:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13392:                     '</td>'.&end_data_table_row();
1.660     raeburn  13393:             }
1.987     raeburn  13394:             $numpathchg ++;
                   13395:             $chgcount ++;
1.660     raeburn  13396:         }
                   13397:     }
1.1127    raeburn  13398:     if (($counter) || ($numunused)) {
1.987     raeburn  13399:         if ($numpathchg) {
                   13400:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13401:                        $numpathchg.'" />'."\n";
                   13402:         }
                   13403:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13404:             ($actionurl eq '/adm/imsimport')) {
                   13405:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13406:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13407:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13408:         } elsif ($actionurl eq '/adm/dependencies') {
                   13409:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13410:         }
1.1123    raeburn  13411:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13412:     } elsif ($numpathchg) {
                   13413:         my %pathchange = ();
                   13414:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13415:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13416:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13417:         }
1.987     raeburn  13418:     }
1.1071    raeburn  13419:     return ($output,$counter,$numpathchg);
1.987     raeburn  13420: }
                   13421: 
1.1147    raeburn  13422: =pod
                   13423: 
                   13424: =item * clean_path($name)
                   13425: 
                   13426: Performs clean-up of directories, subdirectories and filename in an
                   13427: embedded object, referenced in an HTML file which is being uploaded
                   13428: to a course or portfolio, where 
                   13429: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13430: checked.
                   13431: 
                   13432: Clean-up is similar to replacements in lonnet::clean_filename()
                   13433: except each / between sub-directory and next level is preserved.
                   13434: 
                   13435: =cut
                   13436: 
                   13437: sub clean_path {
                   13438:     my ($embed_file) = @_;
                   13439:     $embed_file =~s{^/+}{};
                   13440:     my @contents;
                   13441:     if ($embed_file =~ m{/}) {
                   13442:         @contents = split(/\//,$embed_file);
                   13443:     } else {
                   13444:         @contents = ($embed_file);
                   13445:     }
                   13446:     my $lastidx = scalar(@contents)-1;
                   13447:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13448:         $contents[$i]=~s{\\}{/}g;
                   13449:         $contents[$i]=~s/\s+/\_/g;
                   13450:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13451:         if ($i == $lastidx) {
                   13452:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13453:         }
                   13454:     }
                   13455:     if ($lastidx > 0) {
                   13456:         return join('/',@contents);
                   13457:     } else {
                   13458:         return $contents[0];
                   13459:     }
                   13460: }
                   13461: 
1.987     raeburn  13462: sub embedded_file_element {
1.1071    raeburn  13463:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13464:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13465:                    (ref($codebase) eq 'HASH'));
                   13466:     my $output;
1.1071    raeburn  13467:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13468:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13469:     }
                   13470:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13471:                &escape($embed_file).'" />';
                   13472:     unless (($context eq 'upload_embedded') && 
                   13473:             ($mapping->{$embed_file} eq $embed_file)) {
                   13474:         $output .='
                   13475:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13476:     }
                   13477:     my $attrib;
                   13478:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13479:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13480:     }
                   13481:     $output .=
                   13482:         "\n\t\t".
                   13483:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13484:         $attrib.'" />';
                   13485:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13486:         $output .=
                   13487:             "\n\t\t".
                   13488:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13489:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13490:     }
1.987     raeburn  13491:     return $output;
1.660     raeburn  13492: }
                   13493: 
1.1071    raeburn  13494: sub get_dependency_details {
                   13495:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13496:     my ($size,$mtime,$showsize,$showmtime);
                   13497:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13498:         if ($embed_file =~ m{/}) {
                   13499:             my ($path,$fname) = split(/\//,$embed_file);
                   13500:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13501:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13502:             }
                   13503:         } else {
                   13504:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13505:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13506:             }
                   13507:         }
                   13508:         $showsize = $size/1024.0;
                   13509:         $showsize = sprintf("%.1f",$showsize);
                   13510:         if ($mtime > 0) {
                   13511:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13512:         }
                   13513:     }
                   13514:     return ($showsize,$showmtime);
                   13515: }
                   13516: 
                   13517: sub ask_embedded_js {
                   13518:     return <<"END";
                   13519: <script type="text/javascript"">
                   13520: // <![CDATA[
                   13521: function toggleBrowse(counter) {
                   13522:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13523:     var fileid = document.getElementById('embedded_item_'+counter);
                   13524:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13525:     if (chkboxid.checked == true) {
                   13526:         uploaddivid.style.display='block';
                   13527:     } else {
                   13528:         uploaddivid.style.display='none';
                   13529:         fileid.value = '';
                   13530:     }
                   13531: }
                   13532: // ]]>
                   13533: </script>
                   13534: 
                   13535: END
                   13536: }
                   13537: 
1.661     raeburn  13538: sub upload_embedded {
                   13539:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13540:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13541:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13542:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13543:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13544:         my $orig_uploaded_filename =
                   13545:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13546:         foreach my $type ('orig','ref','attrib','codebase') {
                   13547:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13548:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13549:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13550:             }
                   13551:         }
1.661     raeburn  13552:         my ($path,$fname) =
                   13553:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13554:         # no path, whole string is fname
                   13555:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13556:         $fname = &Apache::lonnet::clean_filename($fname);
                   13557:         # See if there is anything left
                   13558:         next if ($fname eq '');
                   13559: 
                   13560:         # Check if file already exists as a file or directory.
                   13561:         my ($state,$msg);
                   13562:         if ($context eq 'portfolio') {
                   13563:             my $port_path = $dirpath;
                   13564:             if ($group ne '') {
                   13565:                 $port_path = "groups/$group/$port_path";
                   13566:             }
1.987     raeburn  13567:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13568:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13569:                                               $dir_root,$port_path,$disk_quota,
                   13570:                                               $current_disk_usage,$uname,$udom);
                   13571:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13572:                 || $state eq 'file_locked') {
1.661     raeburn  13573:                 $output .= $msg;
                   13574:                 next;
                   13575:             }
                   13576:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13577:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13578:             if ($state eq 'exists') {
                   13579:                 $output .= $msg;
                   13580:                 next;
                   13581:             }
                   13582:         }
                   13583:         # Check if extension is valid
                   13584:         if (($fname =~ /\.(\w+)$/) &&
                   13585:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13586:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13587:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13588:             next;
                   13589:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13590:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13591:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13592:             next;
                   13593:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13594:             $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  13595:             next;
                   13596:         }
                   13597:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13598:         my $subdir = $path;
                   13599:         $subdir =~ s{/+$}{};
1.661     raeburn  13600:         if ($context eq 'portfolio') {
1.984     raeburn  13601:             my $result;
                   13602:             if ($state eq 'existingfile') {
                   13603:                 $result=
                   13604:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13605:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13606:             } else {
1.984     raeburn  13607:                 $result=
                   13608:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13609:                                                     $dirpath.
1.1123    raeburn  13610:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13611:                 if ($result !~ m|^/uploaded/|) {
                   13612:                     $output .= '<span class="LC_error">'
                   13613:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13614:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13615:                                .'</span><br />';
                   13616:                     next;
                   13617:                 } else {
1.987     raeburn  13618:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13619:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13620:                 }
1.661     raeburn  13621:             }
1.1123    raeburn  13622:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13623:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13624:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13625:             my $result =
1.1126    raeburn  13626:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13627:             if ($result !~ m|^/uploaded/|) {
                   13628:                 $output .= '<span class="LC_error">'
                   13629:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13630:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13631:                            .'</span><br />';
                   13632:                     next;
                   13633:             } else {
                   13634:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13635:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13636:                 if ($context eq 'syllabus') {
                   13637:                     &Apache::lonnet::make_public_indefinitely($result);
                   13638:                 }
1.987     raeburn  13639:             }
1.661     raeburn  13640:         } else {
                   13641: # Save the file
                   13642:             my $target = $env{'form.embedded_item_'.$i};
                   13643:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13644:             my $dest = $fullpath.$fname;
                   13645:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13646:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13647:             my $count;
                   13648:             my $filepath = $dir_root;
1.1027    raeburn  13649:             foreach my $subdir (@parts) {
                   13650:                 $filepath .= "/$subdir";
                   13651:                 if (!-e $filepath) {
1.661     raeburn  13652:                     mkdir($filepath,0770);
                   13653:                 }
                   13654:             }
                   13655:             my $fh;
                   13656:             if (!open($fh,'>'.$dest)) {
                   13657:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13658:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13659:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13660:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13661:                            '</span><br />';
                   13662:             } else {
                   13663:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13664:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13665:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13666:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13667:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13668:                               '</span><br />';
                   13669:                 } else {
1.987     raeburn  13670:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13671:                                $url.'</span>').'<br />';
                   13672:                     unless ($context eq 'testbank') {
                   13673:                         $footer .= &mt('View embedded file: [_1]',
                   13674:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13675:                     }
                   13676:                 }
                   13677:                 close($fh);
                   13678:             }
                   13679:         }
                   13680:         if ($env{'form.embedded_ref_'.$i}) {
                   13681:             $pathchange{$i} = 1;
                   13682:         }
                   13683:     }
                   13684:     if ($output) {
                   13685:         $output = '<p>'.$output.'</p>';
                   13686:     }
                   13687:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13688:     $returnflag = 'ok';
1.1071    raeburn  13689:     my $numpathchgs = scalar(keys(%pathchange));
                   13690:     if ($numpathchgs > 0) {
1.987     raeburn  13691:         if ($context eq 'portfolio') {
                   13692:             $output .= '<p>'.&mt('or').'</p>';
                   13693:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13694:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13695:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13696:             $returnflag = 'modify_orightml';
                   13697:         }
                   13698:     }
1.1071    raeburn  13699:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13700: }
                   13701: 
                   13702: sub modify_html_form {
                   13703:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13704:     my $end = 0;
                   13705:     my $modifyform;
                   13706:     if ($context eq 'upload_embedded') {
                   13707:         return unless (ref($pathchange) eq 'HASH');
                   13708:         if ($env{'form.number_embedded_items'}) {
                   13709:             $end += $env{'form.number_embedded_items'};
                   13710:         }
                   13711:         if ($env{'form.number_pathchange_items'}) {
                   13712:             $end += $env{'form.number_pathchange_items'};
                   13713:         }
                   13714:         if ($end) {
                   13715:             for (my $i=0; $i<$end; $i++) {
                   13716:                 if ($i < $env{'form.number_embedded_items'}) {
                   13717:                     next unless($pathchange->{$i});
                   13718:                 }
                   13719:                 $modifyform .=
                   13720:                     &start_data_table_row().
                   13721:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13722:                     'checked="checked" /></td>'.
                   13723:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13724:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13725:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13726:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13727:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13728:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13729:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13730:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13731:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13732:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13733:                     &end_data_table_row();
1.1071    raeburn  13734:             }
1.987     raeburn  13735:         }
                   13736:     } else {
                   13737:         $modifyform = $pathchgtable;
                   13738:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13739:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13740:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13741:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13742:         }
                   13743:     }
                   13744:     if ($modifyform) {
1.1071    raeburn  13745:         if ($actionurl eq '/adm/dependencies') {
                   13746:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13747:         }
1.987     raeburn  13748:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13749:                '<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".
                   13750:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13751:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13752:                '</ol></p>'."\n".'<p>'.
                   13753:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13754:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13755:                &start_data_table()."\n".
                   13756:                &start_data_table_header_row().
                   13757:                '<th>'.&mt('Change?').'</th>'.
                   13758:                '<th>'.&mt('Current reference').'</th>'.
                   13759:                '<th>'.&mt('Required reference').'</th>'.
                   13760:                &end_data_table_header_row()."\n".
                   13761:                $modifyform.
                   13762:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13763:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13764:                '</form>'."\n";
                   13765:     }
                   13766:     return;
                   13767: }
                   13768: 
                   13769: sub modify_html_refs {
1.1123    raeburn  13770:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13771:     my $container;
                   13772:     if ($context eq 'portfolio') {
                   13773:         $container = $env{'form.container'};
                   13774:     } elsif ($context eq 'coursedoc') {
                   13775:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13776:     } elsif ($context eq 'manage_dependencies') {
                   13777:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13778:         $container = "/$container";
1.1123    raeburn  13779:     } elsif ($context eq 'syllabus') {
                   13780:         $container = $url;
1.987     raeburn  13781:     } else {
1.1027    raeburn  13782:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13783:     }
                   13784:     my (%allfiles,%codebase,$output,$content);
                   13785:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13786:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13787:         if (wantarray) {
                   13788:             return ('',0,0); 
                   13789:         } else {
                   13790:             return;
                   13791:         }
                   13792:     }
                   13793:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13794:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13795:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13796:             if (wantarray) {
                   13797:                 return ('',0,0);
                   13798:             } else {
                   13799:                 return;
                   13800:             }
                   13801:         } 
1.987     raeburn  13802:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13803:         if ($content eq '-1') {
                   13804:             if (wantarray) {
                   13805:                 return ('',0,0);
                   13806:             } else {
                   13807:                 return;
                   13808:             }
                   13809:         }
1.987     raeburn  13810:     } else {
1.1071    raeburn  13811:         unless ($container =~ /^\Q$dir_root\E/) {
                   13812:             if (wantarray) {
                   13813:                 return ('',0,0);
                   13814:             } else {
                   13815:                 return;
                   13816:             }
                   13817:         } 
1.1317    raeburn  13818:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13819:             $content = join('', <$fh>);
                   13820:             close($fh);
                   13821:         } else {
1.1071    raeburn  13822:             if (wantarray) {
                   13823:                 return ('',0,0);
                   13824:             } else {
                   13825:                 return;
                   13826:             }
1.987     raeburn  13827:         }
                   13828:     }
                   13829:     my ($count,$codebasecount) = (0,0);
                   13830:     my $mm = new File::MMagic;
                   13831:     my $mime_type = $mm->checktype_contents($content);
                   13832:     if ($mime_type eq 'text/html') {
                   13833:         my $parse_result = 
                   13834:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13835:                                                     \%codebase,\$content);
                   13836:         if ($parse_result eq 'ok') {
                   13837:             foreach my $i (@changes) {
                   13838:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13839:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13840:                 if ($allfiles{$ref}) {
                   13841:                     my $newname =  $orig;
                   13842:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13843:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13844:                     if ($attrib_regexp =~ /:/) {
                   13845:                         $attrib_regexp =~ s/\:/|/g;
                   13846:                     }
                   13847:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13848:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13849:                         $count += $numchg;
1.1123    raeburn  13850:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13851:                         delete($allfiles{$ref});
1.987     raeburn  13852:                     }
                   13853:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13854:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13855:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13856:                         $codebasecount ++;
                   13857:                     }
                   13858:                 }
                   13859:             }
1.1123    raeburn  13860:             my $skiprewrites;
1.987     raeburn  13861:             if ($count || $codebasecount) {
                   13862:                 my $saveresult;
1.1071    raeburn  13863:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13864:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13865:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13866:                     if ($url eq $container) {
                   13867:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13868:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13869:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13870:                                             $fname.'</span>').'</p>';
1.987     raeburn  13871:                     } else {
                   13872:                          $output = '<p class="LC_error">'.
                   13873:                                    &mt('Error: update failed for: [_1].',
                   13874:                                    '<span class="LC_filename">'.
                   13875:                                    $container.'</span>').'</p>';
                   13876:                     }
1.1123    raeburn  13877:                     if ($context eq 'syllabus') {
                   13878:                         unless ($saveresult eq 'ok') {
                   13879:                             $skiprewrites = 1;
                   13880:                         }
                   13881:                     }
1.987     raeburn  13882:                 } else {
1.1317    raeburn  13883:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13884:                         print $fh $content;
                   13885:                         close($fh);
                   13886:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13887:                                   $count,'<span class="LC_filename">'.
                   13888:                                   $container.'</span>').'</p>';
1.661     raeburn  13889:                     } else {
1.987     raeburn  13890:                          $output = '<p class="LC_error">'.
                   13891:                                    &mt('Error: could not update [_1].',
                   13892:                                    '<span class="LC_filename">'.
                   13893:                                    $container.'</span>').'</p>';
1.661     raeburn  13894:                     }
                   13895:                 }
                   13896:             }
1.1123    raeburn  13897:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13898:                 my ($actionurl,$state);
                   13899:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13900:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13901:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13902:                                               \%codebase,
                   13903:                                               {'context' => 'rewrites',
                   13904:                                                'ignore_remote_references' => 1,});
                   13905:                 if (ref($mapping) eq 'HASH') {
                   13906:                     my $rewrites = 0;
                   13907:                     foreach my $key (keys(%{$mapping})) {
                   13908:                         next if ($key =~ m{^https?://});
                   13909:                         my $ref = $mapping->{$key};
                   13910:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13911:                         my $attrib;
                   13912:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13913:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13914:                         }
                   13915:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13916:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13917:                             $rewrites += $numchg;
                   13918:                         }
                   13919:                     }
                   13920:                     if ($rewrites) {
                   13921:                         my $saveresult; 
                   13922:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13923:                         if ($url eq $container) {
                   13924:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13925:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13926:                                             $count,'<span class="LC_filename">'.
                   13927:                                             $fname.'</span>').'</p>';
                   13928:                         } else {
                   13929:                             $output .= '<p class="LC_error">'.
                   13930:                                        &mt('Error: could not update links in [_1].',
                   13931:                                        '<span class="LC_filename">'.
                   13932:                                        $container.'</span>').'</p>';
                   13933: 
                   13934:                         }
                   13935:                     }
                   13936:                 }
                   13937:             }
1.987     raeburn  13938:         } else {
                   13939:             &logthis('Failed to parse '.$container.
                   13940:                      ' to modify references: '.$parse_result);
1.661     raeburn  13941:         }
                   13942:     }
1.1071    raeburn  13943:     if (wantarray) {
                   13944:         return ($output,$count,$codebasecount);
                   13945:     } else {
                   13946:         return $output;
                   13947:     }
1.661     raeburn  13948: }
                   13949: 
                   13950: sub check_for_existing {
                   13951:     my ($path,$fname,$element) = @_;
                   13952:     my ($state,$msg);
                   13953:     if (-d $path.'/'.$fname) {
                   13954:         $state = 'exists';
                   13955:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13956:     } elsif (-e $path.'/'.$fname) {
                   13957:         $state = 'exists';
                   13958:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13959:     }
                   13960:     if ($state eq 'exists') {
                   13961:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13962:     }
                   13963:     return ($state,$msg);
                   13964: }
                   13965: 
                   13966: sub check_for_upload {
                   13967:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13968:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13969:     my $filesize = length($env{'form.'.$element});
                   13970:     if (!$filesize) {
                   13971:         my $msg = '<span class="LC_error">'.
                   13972:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13973:                       '<span class="LC_filename">'.$fname.'</span>',
                   13974:                       $filesize).'<br />'.
1.1007    raeburn  13975:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13976:                   '</span>';
                   13977:         return ('zero_bytes',$msg);
                   13978:     }
                   13979:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13980:     my $getpropath = 1;
1.1021    raeburn  13981:     my ($dirlistref,$listerror) =
                   13982:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13983:     my $found_file = 0;
                   13984:     my $locked_file = 0;
1.991     raeburn  13985:     my @lockers;
                   13986:     my $navmap;
                   13987:     if ($env{'request.course.id'}) {
                   13988:         $navmap = Apache::lonnavmaps::navmap->new();
                   13989:     }
1.1021    raeburn  13990:     if (ref($dirlistref) eq 'ARRAY') {
                   13991:         foreach my $line (@{$dirlistref}) {
                   13992:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13993:             if ($file_name eq $fname){
                   13994:                 $file_name = $path.$file_name;
                   13995:                 if ($group ne '') {
                   13996:                     $file_name = $group.$file_name;
                   13997:                 }
                   13998:                 $found_file = 1;
                   13999:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   14000:                     foreach my $lock (@lockers) {
                   14001:                         if (ref($lock) eq 'ARRAY') {
                   14002:                             my ($symb,$crsid) = @{$lock};
                   14003:                             if ($crsid eq $env{'request.course.id'}) {
                   14004:                                 if (ref($navmap)) {
                   14005:                                     my $res = $navmap->getBySymb($symb);
                   14006:                                     foreach my $part (@{$res->parts()}) { 
                   14007:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   14008:                                         unless (($slot_status == $res->RESERVED) ||
                   14009:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   14010:                                             $locked_file = 1;
                   14011:                                         }
1.991     raeburn  14012:                                     }
1.1021    raeburn  14013:                                 } else {
                   14014:                                     $locked_file = 1;
1.991     raeburn  14015:                                 }
                   14016:                             } else {
                   14017:                                 $locked_file = 1;
                   14018:                             }
                   14019:                         }
1.1021    raeburn  14020:                    }
                   14021:                 } else {
                   14022:                     my @info = split(/\&/,$rest);
                   14023:                     my $currsize = $info[6]/1000;
                   14024:                     if ($currsize < $filesize) {
                   14025:                         my $extra = $filesize - $currsize;
                   14026:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   14027:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  14028:                                       &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   14029:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   14030:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   14031:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  14032:                             return ('will_exceed_quota',$msg);
                   14033:                         }
1.984     raeburn  14034:                     }
                   14035:                 }
1.661     raeburn  14036:             }
                   14037:         }
                   14038:     }
                   14039:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   14040:         my $msg = '<p class="LC_warning">'.
                   14041:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  14042:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  14043:         return ('will_exceed_quota',$msg);
                   14044:     } elsif ($found_file) {
                   14045:         if ($locked_file) {
1.1179    bisitz   14046:             my $msg = '<p class="LC_warning">';
1.661     raeburn  14047:             $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   14048:             $msg .= '</p>';
1.661     raeburn  14049:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   14050:             return ('file_locked',$msg);
                   14051:         } else {
1.1179    bisitz   14052:             my $msg = '<p class="LC_error">';
1.984     raeburn  14053:             $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   14054:             $msg .= '</p>';
1.984     raeburn  14055:             return ('existingfile',$msg);
1.661     raeburn  14056:         }
                   14057:     }
                   14058: }
                   14059: 
1.987     raeburn  14060: sub check_for_traversal {
                   14061:     my ($path,$url,$toplevel) = @_;
                   14062:     my @parts=split(/\//,$path);
                   14063:     my $cleanpath;
                   14064:     my $fullpath = $url;
                   14065:     for (my $i=0;$i<@parts;$i++) {
                   14066:         next if ($parts[$i] eq '.');
                   14067:         if ($parts[$i] eq '..') {
                   14068:             $fullpath =~ s{([^/]+/)$}{};
                   14069:         } else {
                   14070:             $fullpath .= $parts[$i].'/';
                   14071:         }
                   14072:     }
                   14073:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   14074:         $cleanpath = $1;
                   14075:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   14076:         my $curr_toprel = $1;
                   14077:         my @parts = split(/\//,$curr_toprel);
                   14078:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   14079:         my @urlparts = split(/\//,$url_toprel);
                   14080:         my $doubledots;
                   14081:         my $startdiff = -1;
                   14082:         for (my $i=0; $i<@urlparts; $i++) {
                   14083:             if ($startdiff == -1) {
                   14084:                 unless ($urlparts[$i] eq $parts[$i]) {
                   14085:                     $startdiff = $i;
                   14086:                     $doubledots .= '../';
                   14087:                 }
                   14088:             } else {
                   14089:                 $doubledots .= '../';
                   14090:             }
                   14091:         }
                   14092:         if ($startdiff > -1) {
                   14093:             $cleanpath = $doubledots;
                   14094:             for (my $i=$startdiff; $i<@parts; $i++) {
                   14095:                 $cleanpath .= $parts[$i].'/';
                   14096:             }
                   14097:         }
                   14098:     }
                   14099:     $cleanpath =~ s{(/)$}{};
                   14100:     return $cleanpath;
                   14101: }
1.31      albertel 14102: 
1.1053    raeburn  14103: sub is_archive_file {
                   14104:     my ($mimetype) = @_;
                   14105:     if (($mimetype eq 'application/octet-stream') ||
                   14106:         ($mimetype eq 'application/x-stuffit') ||
                   14107:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   14108:         return 1;
                   14109:     }
                   14110:     return;
                   14111: }
                   14112: 
                   14113: sub decompress_form {
1.1065    raeburn  14114:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  14115:     my %lt = &Apache::lonlocal::texthash (
                   14116:         this => 'This file is an archive file.',
1.1067    raeburn  14117:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  14118:         itsc => 'Its contents are as follows:',
1.1053    raeburn  14119:         youm => 'You may wish to extract its contents.',
                   14120:         extr => 'Extract contents',
1.1067    raeburn  14121:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   14122:         proa => 'Process automatically?',
1.1053    raeburn  14123:         yes  => 'Yes',
                   14124:         no   => 'No',
1.1067    raeburn  14125:         fold => 'Title for folder containing movie',
                   14126:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  14127:     );
1.1065    raeburn  14128:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  14129:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  14130:     my $info = &list_archive_contents($fileloc,\@paths);
                   14131:     if (@paths) {
                   14132:         foreach my $path (@paths) {
                   14133:             $path =~ s{^/}{};
1.1067    raeburn  14134:             if ($path =~ m{^([^/]+)/$}) {
                   14135:                 $topdir = $1;
                   14136:             }
1.1065    raeburn  14137:             if ($path =~ m{^([^/]+)/}) {
                   14138:                 $toplevel{$1} = $path;
                   14139:             } else {
                   14140:                 $toplevel{$path} = $path;
                   14141:             }
                   14142:         }
                   14143:     }
1.1067    raeburn  14144:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  14145:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  14146:                         "$topdir/media/",
                   14147:                         "$topdir/media/$topdir.mp4",
                   14148:                         "$topdir/media/FirstFrame.png",
                   14149:                         "$topdir/media/player.swf",
                   14150:                         "$topdir/media/swfobject.js",
                   14151:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  14152:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  14153:                          "$topdir/$topdir.mp4",
                   14154:                          "$topdir/$topdir\_config.xml",
                   14155:                          "$topdir/$topdir\_controller.swf",
                   14156:                          "$topdir/$topdir\_embed.css",
                   14157:                          "$topdir/$topdir\_First_Frame.png",
                   14158:                          "$topdir/$topdir\_player.html",
                   14159:                          "$topdir/$topdir\_Thumbnails.png",
                   14160:                          "$topdir/playerProductInstall.swf",
                   14161:                          "$topdir/scripts/",
                   14162:                          "$topdir/scripts/config_xml.js",
                   14163:                          "$topdir/scripts/handlebars.js",
                   14164:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   14165:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   14166:                          "$topdir/scripts/modernizr.js",
                   14167:                          "$topdir/scripts/player-min.js",
                   14168:                          "$topdir/scripts/swfobject.js",
                   14169:                          "$topdir/skins/",
                   14170:                          "$topdir/skins/configuration_express.xml",
                   14171:                          "$topdir/skins/express_show/",
                   14172:                          "$topdir/skins/express_show/player-min.css",
                   14173:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14174:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14175:                          "$topdir/$topdir.mp4",
                   14176:                          "$topdir/$topdir\_config.xml",
                   14177:                          "$topdir/$topdir\_controller.swf",
                   14178:                          "$topdir/$topdir\_embed.css",
                   14179:                          "$topdir/$topdir\_First_Frame.png",
                   14180:                          "$topdir/$topdir\_player.html",
                   14181:                          "$topdir/$topdir\_Thumbnails.png",
                   14182:                          "$topdir/playerProductInstall.swf",
                   14183:                          "$topdir/scripts/",
                   14184:                          "$topdir/scripts/config_xml.js",
                   14185:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14186:                          "$topdir/skins/",
                   14187:                          "$topdir/skins/configuration_express.xml",
                   14188:                          "$topdir/skins/express_show/",
                   14189:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14190:                          "$topdir/skins/express_show/spritesheet.png",
                   14191:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14192:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14193:         if (@diffs == 0) {
1.1164    raeburn  14194:             $is_camtasia = 6;
                   14195:         } else {
1.1197    raeburn  14196:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14197:             if (@diffs == 0) {
                   14198:                 $is_camtasia = 8;
1.1197    raeburn  14199:             } else {
                   14200:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14201:                 if (@diffs == 0) {
                   14202:                     $is_camtasia = 8;
                   14203:                 }
1.1164    raeburn  14204:             }
1.1067    raeburn  14205:         }
                   14206:     }
                   14207:     my $output;
                   14208:     if ($is_camtasia) {
                   14209:         $output = <<"ENDCAM";
                   14210: <script type="text/javascript" language="Javascript">
                   14211: // <![CDATA[
                   14212: 
                   14213: function camtasiaToggle() {
                   14214:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14215:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14216:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14217:                 document.getElementById('camtasia_titles').style.display='block';
                   14218:             } else {
                   14219:                 document.getElementById('camtasia_titles').style.display='none';
                   14220:             }
                   14221:         }
                   14222:     }
                   14223:     return;
                   14224: }
                   14225: 
                   14226: // ]]>
                   14227: </script>
                   14228: <p>$lt{'camt'}</p>
                   14229: ENDCAM
1.1065    raeburn  14230:     } else {
1.1067    raeburn  14231:         $output = '<p>'.$lt{'this'};
                   14232:         if ($info eq '') {
                   14233:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14234:         } else {
                   14235:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14236:                        '<div><pre>'.$info.'</pre></div>';
                   14237:         }
1.1065    raeburn  14238:     }
1.1067    raeburn  14239:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14240:     my $duplicates;
                   14241:     my $num = 0;
                   14242:     if (ref($dirlist) eq 'ARRAY') {
                   14243:         foreach my $item (@{$dirlist}) {
                   14244:             if (ref($item) eq 'ARRAY') {
                   14245:                 if (exists($toplevel{$item->[0]})) {
                   14246:                     $duplicates .= 
                   14247:                         &start_data_table_row().
                   14248:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14249:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14250:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14251:                         'value="1" />'.&mt('Yes').'</label>'.
                   14252:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14253:                         '<td>'.$item->[0].'</td>';
                   14254:                     if ($item->[2]) {
                   14255:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14256:                     } else {
                   14257:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14258:                     }
                   14259:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14260:                                    '<td>'.
                   14261:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14262:                                    '</td>'.
                   14263:                                    &end_data_table_row();
                   14264:                     $num ++;
                   14265:                 }
                   14266:             }
                   14267:         }
                   14268:     }
                   14269:     my $itemcount;
                   14270:     if (@paths > 0) {
                   14271:         $itemcount = scalar(@paths);
                   14272:     } else {
                   14273:         $itemcount = 1;
                   14274:     }
1.1067    raeburn  14275:     if ($is_camtasia) {
                   14276:         $output .= $lt{'auto'}.'<br />'.
                   14277:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14278:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14279:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14280:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14281:                    $lt{'no'}.'</label></span><br />'.
                   14282:                    '<div id="camtasia_titles" style="display:block">'.
                   14283:                    &Apache::lonhtmlcommon::start_pick_box().
                   14284:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14285:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14286:                    &Apache::lonhtmlcommon::row_closure().
                   14287:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14288:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14289:                    &Apache::lonhtmlcommon::row_closure(1).
                   14290:                    &Apache::lonhtmlcommon::end_pick_box().
                   14291:                    '</div>';
                   14292:     }
1.1065    raeburn  14293:     $output .= 
                   14294:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14295:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14296:         "\n";
1.1065    raeburn  14297:     if ($duplicates ne '') {
                   14298:         $output .= '<p><span class="LC_warning">'.
                   14299:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14300:                    &start_data_table().
                   14301:                    &start_data_table_header_row().
                   14302:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14303:                    '<th>'.&mt('Name').'</th>'.
                   14304:                    '<th>'.&mt('Type').'</th>'.
                   14305:                    '<th>'.&mt('Size').'</th>'.
                   14306:                    '<th>'.&mt('Last modified').'</th>'.
                   14307:                    &end_data_table_header_row().
                   14308:                    $duplicates.
                   14309:                    &end_data_table().
                   14310:                    '</p>';
                   14311:     }
1.1067    raeburn  14312:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14313:     if (ref($hiddenelements) eq 'HASH') {
                   14314:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14315:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14316:         }
                   14317:     }
                   14318:     $output .= <<"END";
1.1067    raeburn  14319: <br />
1.1053    raeburn  14320: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14321: </form>
                   14322: $noextract
                   14323: END
                   14324:     return $output;
                   14325: }
                   14326: 
1.1065    raeburn  14327: sub decompression_utility {
                   14328:     my ($program) = @_;
                   14329:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14330:     my $location;
                   14331:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14332:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14333:                          '/usr/sbin/') {
                   14334:             if (-x $dir.$program) {
                   14335:                 $location = $dir.$program;
                   14336:                 last;
                   14337:             }
                   14338:         }
                   14339:     }
                   14340:     return $location;
                   14341: }
                   14342: 
                   14343: sub list_archive_contents {
                   14344:     my ($file,$pathsref) = @_;
                   14345:     my (@cmd,$output);
                   14346:     my $needsregexp;
                   14347:     if ($file =~ /\.zip$/) {
                   14348:         @cmd = (&decompression_utility('unzip'),"-l");
                   14349:         $needsregexp = 1;
                   14350:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14351:              ($file =~ /\.tgz$/)) {
                   14352:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14353:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14354:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14355:     } elsif ($file =~ m|\.tar$|) {
                   14356:         @cmd = (&decompression_utility('tar'),"-tf");
                   14357:     }
                   14358:     if (@cmd) {
                   14359:         undef($!);
                   14360:         undef($@);
                   14361:         if (open(my $fh,"-|", @cmd, $file)) {
                   14362:             while (my $line = <$fh>) {
                   14363:                 $output .= $line;
                   14364:                 chomp($line);
                   14365:                 my $item;
                   14366:                 if ($needsregexp) {
                   14367:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14368:                 } else {
                   14369:                     $item = $line;
                   14370:                 }
                   14371:                 if ($item ne '') {
                   14372:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14373:                         push(@{$pathsref},$item);
                   14374:                     } 
                   14375:                 }
                   14376:             }
                   14377:             close($fh);
                   14378:         }
                   14379:     }
                   14380:     return $output;
                   14381: }
                   14382: 
1.1053    raeburn  14383: sub decompress_uploaded_file {
                   14384:     my ($file,$dir) = @_;
                   14385:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14386:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14387:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14388:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14389:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14390:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14391:     my $decompressed = $env{'cgi.decompressed'};
                   14392:     &Apache::lonnet::delenv('cgi.file');
                   14393:     &Apache::lonnet::delenv('cgi.dir');
                   14394:     &Apache::lonnet::delenv('cgi.decompressed');
                   14395:     return ($decompressed,$result);
                   14396: }
                   14397: 
1.1055    raeburn  14398: sub process_decompression {
                   14399:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14400:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14401:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14402:                &mt('Unexpected file path.').'</p>'."\n";
                   14403:     }
                   14404:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14405:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14406:                &mt('Unexpected course context.').'</p>'."\n";
                   14407:     }
1.1293    raeburn  14408:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14409:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14410:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14411:     }
1.1055    raeburn  14412:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14413:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14414:         $error = &mt('Filename not a supported archive file type.').
                   14415:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14416:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14417:     } else {
                   14418:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14419:         if ($docuhome eq 'no_host') {
                   14420:             $error = &mt('Could not determine home server for course.');
                   14421:         } else {
                   14422:             my @ids=&Apache::lonnet::current_machine_ids();
                   14423:             my $currdir = "$dir_root/$destination";
                   14424:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14425:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14426:                        "$dir_root/$destination";
                   14427:             } else {
                   14428:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14429:                        "$dir_root/$docudom/$docuname/$destination";
                   14430:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14431:                     $error = &mt('Archive file not found.');
                   14432:                 }
                   14433:             }
1.1065    raeburn  14434:             my (@to_overwrite,@to_skip);
                   14435:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14436:                 my $total = $env{'form.archive_overwrite_total'};
                   14437:                 for (my $i=0; $i<$total; $i++) {
                   14438:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14439:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14440:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14441:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14442:                     }
                   14443:                 }
                   14444:             }
                   14445:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14446:             my $numoverwrite = scalar(@to_overwrite);
                   14447:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14448:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14449:             } elsif ($dir eq '') {
1.1055    raeburn  14450:                 $error = &mt('Directory containing archive file unavailable.');
                   14451:             } elsif (!$error) {
1.1065    raeburn  14452:                 my ($decompressed,$display);
1.1292    raeburn  14453:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14454:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14455:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14456:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14457:                         ($decompressed,$display) = 
                   14458:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14459:                         foreach my $item (@to_skip) {
                   14460:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14461:                                 if (-f "$dir/$tempdir/$item") { 
                   14462:                                     unlink("$dir/$tempdir/$item");
                   14463:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14464:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14465:                                 }
                   14466:                             }
                   14467:                         }
                   14468:                         foreach my $item (@to_overwrite) {
                   14469:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14470:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14471:                                     if (-f "$dir/$item") {
                   14472:                                         unlink("$dir/$item");
                   14473:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14474:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14475:                                     }
                   14476:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14477:                                 }
1.1065    raeburn  14478:                             }
                   14479:                         }
1.1292    raeburn  14480:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14481:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14482:                         }
1.1065    raeburn  14483:                     }
                   14484:                 } else {
                   14485:                     ($decompressed,$display) = 
                   14486:                         &decompress_uploaded_file($file,$dir);
                   14487:                 }
1.1055    raeburn  14488:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14489:                     $output = '<p class="LC_info">'.
                   14490:                               &mt('Files extracted successfully from archive.').
                   14491:                               '</p>'."\n";
1.1055    raeburn  14492:                     my ($warning,$result,@contents);
                   14493:                     my ($newdirlistref,$newlisterror) =
                   14494:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14495:                                                  $docuname,1);
                   14496:                     my (%is_dir,%changes,@newitems);
                   14497:                     my $dirptr = 16384;
1.1065    raeburn  14498:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14499:                         foreach my $dir_line (@{$newdirlistref}) {
                   14500:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14501:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14502:                                 push(@newitems,$item);
                   14503:                                 if ($dirptr&$testdir) {
                   14504:                                     $is_dir{$item} = 1;
                   14505:                                 }
                   14506:                                 $changes{$item} = 1;
                   14507:                             }
                   14508:                         }
                   14509:                     }
                   14510:                     if (keys(%changes) > 0) {
                   14511:                         foreach my $item (sort(@newitems)) {
                   14512:                             if ($changes{$item}) {
                   14513:                                 push(@contents,$item);
                   14514:                             }
                   14515:                         }
                   14516:                     }
                   14517:                     if (@contents > 0) {
1.1067    raeburn  14518:                         my $wantform;
                   14519:                         unless ($env{'form.autoextract_camtasia'}) {
                   14520:                             $wantform = 1;
                   14521:                         }
1.1056    raeburn  14522:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14523:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14524:                                                                 $currdir,\%is_dir,
                   14525:                                                                 \%children,\%parent,
1.1056    raeburn  14526:                                                                 \@contents,\%dirorder,
                   14527:                                                                 \%titles,$wantform);
1.1055    raeburn  14528:                         if ($datatable ne '') {
                   14529:                             $output .= &archive_options_form('decompressed',$datatable,
                   14530:                                                              $count,$hiddenelem);
1.1065    raeburn  14531:                             my $startcount = 6;
1.1055    raeburn  14532:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14533:                                                            \%titles,\%children);
1.1055    raeburn  14534:                         }
1.1067    raeburn  14535:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14536:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14537:                             my %displayed;
                   14538:                             my $total = 1;
                   14539:                             $env{'form.archive_directory'} = [];
                   14540:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14541:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14542:                                 $path =~ s{/$}{};
                   14543:                                 my $item;
                   14544:                                 if ($path ne '') {
                   14545:                                     $item = "$path/$titles{$i}";
                   14546:                                 } else {
                   14547:                                     $item = $titles{$i};
                   14548:                                 }
                   14549:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14550:                                 if ($item eq $contents[0]) {
                   14551:                                     push(@{$env{'form.archive_directory'}},$i);
                   14552:                                     $env{'form.archive_'.$i} = 'display';
                   14553:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14554:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14555:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14556:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14557:                                     $env{'form.archive_'.$i} = 'display';
                   14558:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14559:                                     $displayed{'web'} = $i;
                   14560:                                 } else {
1.1164    raeburn  14561:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14562:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14563:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14564:                                         push(@{$env{'form.archive_directory'}},$i);
                   14565:                                     }
                   14566:                                     $env{'form.archive_'.$i} = 'dependency';
                   14567:                                 }
                   14568:                                 $total ++;
                   14569:                             }
                   14570:                             for (my $i=1; $i<$total; $i++) {
                   14571:                                 next if ($i == $displayed{'web'});
                   14572:                                 next if ($i == $displayed{'folder'});
                   14573:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14574:                             }
                   14575:                             $env{'form.phase'} = 'decompress_cleanup';
                   14576:                             $env{'form.archivedelete'} = 1;
                   14577:                             $env{'form.archive_count'} = $total-1;
                   14578:                             $output .=
                   14579:                                 &process_extracted_files('coursedocs',$docudom,
                   14580:                                                          $docuname,$destination,
                   14581:                                                          $dir_root,$hiddenelem);
                   14582:                         }
1.1055    raeburn  14583:                     } else {
                   14584:                         $warning = &mt('No new items extracted from archive file.');
                   14585:                     }
                   14586:                 } else {
                   14587:                     $output = $display;
                   14588:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14589:                 }
                   14590:             }
                   14591:         }
                   14592:     }
                   14593:     if ($error) {
                   14594:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14595:                    $error.'</p>'."\n";
                   14596:     }
                   14597:     if ($warning) {
                   14598:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14599:     }
                   14600:     return $output;
                   14601: }
                   14602: 
                   14603: sub get_extracted {
1.1056    raeburn  14604:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14605:         $titles,$wantform) = @_;
1.1055    raeburn  14606:     my $count = 0;
                   14607:     my $depth = 0;
                   14608:     my $datatable;
1.1056    raeburn  14609:     my @hierarchy;
1.1055    raeburn  14610:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14611:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14612:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14613:     foreach my $item (@{$contents}) {
                   14614:         $count ++;
1.1056    raeburn  14615:         @{$dirorder->{$count}} = @hierarchy;
                   14616:         $titles->{$count} = $item;
1.1055    raeburn  14617:         &archive_hierarchy($depth,$count,$parent,$children);
                   14618:         if ($wantform) {
                   14619:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14620:                                        $currdir,$depth,$count);
                   14621:         }
                   14622:         if ($is_dir->{$item}) {
                   14623:             $depth ++;
1.1056    raeburn  14624:             push(@hierarchy,$count);
                   14625:             $parent->{$depth} = $count;
1.1055    raeburn  14626:             $datatable .=
                   14627:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14628:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14629:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14630:             $depth --;
1.1056    raeburn  14631:             pop(@hierarchy);
1.1055    raeburn  14632:         }
                   14633:     }
                   14634:     return ($count,$datatable);
                   14635: }
                   14636: 
                   14637: sub recurse_extracted_archive {
1.1056    raeburn  14638:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14639:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14640:     my $result='';
1.1056    raeburn  14641:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14642:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14643:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14644:         return $result;
                   14645:     }
                   14646:     my $dirptr = 16384;
                   14647:     my ($newdirlistref,$newlisterror) =
                   14648:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14649:     if (ref($newdirlistref) eq 'ARRAY') {
                   14650:         foreach my $dir_line (@{$newdirlistref}) {
                   14651:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14652:             unless ($item =~ /^\.+$/) {
                   14653:                 $$count ++;
1.1056    raeburn  14654:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14655:                 $titles->{$$count} = $item;
1.1055    raeburn  14656:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14657: 
1.1055    raeburn  14658:                 my $is_dir;
                   14659:                 if ($dirptr&$testdir) {
                   14660:                     $is_dir = 1;
                   14661:                 }
                   14662:                 if ($wantform) {
                   14663:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14664:                 }
                   14665:                 if ($is_dir) {
                   14666:                     $$depth ++;
1.1056    raeburn  14667:                     push(@{$hierarchy},$$count);
                   14668:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14669:                     $result .=
                   14670:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14671:                                                    $docuname,$depth,$count,
1.1056    raeburn  14672:                                                    $hierarchy,$dirorder,$children,
                   14673:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14674:                     $$depth --;
1.1056    raeburn  14675:                     pop(@{$hierarchy});
1.1055    raeburn  14676:                 }
                   14677:             }
                   14678:         }
                   14679:     }
                   14680:     return $result;
                   14681: }
                   14682: 
                   14683: sub archive_hierarchy {
                   14684:     my ($depth,$count,$parent,$children) =@_;
                   14685:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14686:         if (exists($parent->{$depth})) {
                   14687:              $children->{$parent->{$depth}} .= $count.':';
                   14688:         }
                   14689:     }
                   14690:     return;
                   14691: }
                   14692: 
                   14693: sub archive_row {
                   14694:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14695:     my ($name) = ($item =~ m{([^/]+)$});
                   14696:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14697:                                        'display'    => 'Add as file',
1.1055    raeburn  14698:                                        'dependency' => 'Include as dependency',
                   14699:                                        'discard'    => 'Discard',
                   14700:                                       );
                   14701:     if ($is_dir) {
1.1059    raeburn  14702:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14703:     }
1.1056    raeburn  14704:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14705:     my $offset = 0;
1.1055    raeburn  14706:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14707:         $offset ++;
1.1065    raeburn  14708:         if ($action ne 'display') {
                   14709:             $offset ++;
                   14710:         }  
1.1055    raeburn  14711:         $output .= '<td><span class="LC_nobreak">'.
                   14712:                    '<label><input type="radio" name="archive_'.$count.
                   14713:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14714:         my $text = $choices{$action};
                   14715:         if ($is_dir) {
                   14716:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14717:             if ($action eq 'display') {
1.1059    raeburn  14718:                 $text = &mt('Add as folder');
1.1055    raeburn  14719:             }
1.1056    raeburn  14720:         } else {
                   14721:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14722: 
                   14723:         }
                   14724:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14725:         if ($action eq 'dependency') {
                   14726:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14727:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14728:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14729:                        '<option value=""></option>'."\n".
                   14730:                        '</select>'."\n".
                   14731:                        '</div>';
1.1059    raeburn  14732:         } elsif ($action eq 'display') {
                   14733:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14734:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14735:                        '</div>';
1.1055    raeburn  14736:         }
1.1056    raeburn  14737:         $output .= '</td>';
1.1055    raeburn  14738:     }
                   14739:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14740:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14741:     for (my $i=0; $i<$depth; $i++) {
                   14742:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14743:     }
                   14744:     if ($is_dir) {
                   14745:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14746:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14747:     } else {
                   14748:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14749:     }
                   14750:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14751:                &end_data_table_row();
                   14752:     return $output;
                   14753: }
                   14754: 
                   14755: sub archive_options_form {
1.1065    raeburn  14756:     my ($form,$display,$count,$hiddenelem) = @_;
                   14757:     my %lt = &Apache::lonlocal::texthash(
                   14758:                perm => 'Permanently remove archive file?',
                   14759:                hows => 'How should each extracted item be incorporated in the course?',
                   14760:                cont => 'Content actions for all',
                   14761:                addf => 'Add as folder/file',
                   14762:                incd => 'Include as dependency for a displayed file',
                   14763:                disc => 'Discard',
                   14764:                no   => 'No',
                   14765:                yes  => 'Yes',
                   14766:                save => 'Save',
                   14767:     );
                   14768:     my $output = <<"END";
                   14769: <form name="$form" method="post" action="">
                   14770: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14771: <label>
                   14772:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14773: </label>
                   14774: &nbsp;
                   14775: <label>
                   14776:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14777: </span>
                   14778: </p>
                   14779: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14780: <br />$lt{'hows'}
                   14781: <div class="LC_columnSection">
                   14782:   <fieldset>
                   14783:     <legend>$lt{'cont'}</legend>
                   14784:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14785:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14786:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14787:   </fieldset>
                   14788: </div>
                   14789: END
                   14790:     return $output.
1.1055    raeburn  14791:            &start_data_table()."\n".
1.1065    raeburn  14792:            $display."\n".
1.1055    raeburn  14793:            &end_data_table()."\n".
                   14794:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14795:            $hiddenelem.
1.1065    raeburn  14796:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14797:            '</form>';
                   14798: }
                   14799: 
                   14800: sub archive_javascript {
1.1056    raeburn  14801:     my ($startcount,$numitems,$titles,$children) = @_;
                   14802:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14803:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14804:     my $scripttag = <<START;
                   14805: <script type="text/javascript">
                   14806: // <![CDATA[
                   14807: 
                   14808: function checkAll(form,prefix) {
                   14809:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14810:     for (var i=0; i < form.elements.length; i++) {
                   14811:         var id = form.elements[i].id;
                   14812:         if ((id != '') && (id != undefined)) {
                   14813:             if (idstr.test(id)) {
                   14814:                 if (form.elements[i].type == 'radio') {
                   14815:                     form.elements[i].checked = true;
1.1056    raeburn  14816:                     var nostart = i-$startcount;
1.1059    raeburn  14817:                     var offset = nostart%7;
                   14818:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14819:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14820:                 }
                   14821:             }
                   14822:         }
                   14823:     }
                   14824: }
                   14825: 
                   14826: function propagateCheck(form,count) {
                   14827:     if (count > 0) {
1.1059    raeburn  14828:         var startelement = $startcount + ((count-1) * 7);
                   14829:         for (var j=1; j<6; j++) {
                   14830:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14831:                 var item = startelement + j; 
                   14832:                 if (form.elements[item].type == 'radio') {
                   14833:                     if (form.elements[item].checked) {
                   14834:                         containerCheck(form,count,j);
                   14835:                         break;
                   14836:                     }
1.1055    raeburn  14837:                 }
                   14838:             }
                   14839:         }
                   14840:     }
                   14841: }
                   14842: 
                   14843: numitems = $numitems
1.1056    raeburn  14844: var titles = new Array(numitems);
                   14845: var parents = new Array(numitems);
1.1055    raeburn  14846: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14847:     parents[i] = new Array;
1.1055    raeburn  14848: }
1.1059    raeburn  14849: var maintitle = '$maintitle';
1.1055    raeburn  14850: 
                   14851: START
                   14852: 
1.1056    raeburn  14853:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14854:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14855:         for (my $i=0; $i<@contents; $i ++) {
                   14856:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14857:         }
                   14858:     }
                   14859: 
1.1056    raeburn  14860:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14861:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14862:     }
                   14863: 
1.1055    raeburn  14864:     $scripttag .= <<END;
                   14865: 
                   14866: function containerCheck(form,count,offset) {
                   14867:     if (count > 0) {
1.1056    raeburn  14868:         dependencyCheck(form,count,offset);
1.1059    raeburn  14869:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14870:         form.elements[item].checked = true;
                   14871:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14872:             if (parents[count].length > 0) {
                   14873:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14874:                     containerCheck(form,parents[count][j],offset);
                   14875:                 }
                   14876:             }
                   14877:         }
                   14878:     }
                   14879: }
                   14880: 
                   14881: function dependencyCheck(form,count,offset) {
                   14882:     if (count > 0) {
1.1059    raeburn  14883:         var chosen = (offset+$startcount)+7*(count-1);
                   14884:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14885:         var currtype = form.elements[depitem].type;
                   14886:         if (form.elements[chosen].value == 'dependency') {
                   14887:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14888:             form.elements[depitem].options.length = 0;
                   14889:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14890:             for (var i=1; i<=numitems; i++) {
                   14891:                 if (i == count) {
                   14892:                     continue;
                   14893:                 }
1.1059    raeburn  14894:                 var startelement = $startcount + (i-1) * 7;
                   14895:                 for (var j=1; j<6; j++) {
                   14896:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14897:                         var item = startelement + j;
                   14898:                         if (form.elements[item].type == 'radio') {
                   14899:                             if (form.elements[item].checked) {
                   14900:                                 if (form.elements[item].value == 'display') {
                   14901:                                     var n = form.elements[depitem].options.length;
                   14902:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14903:                                 }
                   14904:                             }
                   14905:                         }
                   14906:                     }
                   14907:                 }
                   14908:             }
                   14909:         } else {
                   14910:             document.getElementById('arc_depon_'+count).style.display='none';
                   14911:             form.elements[depitem].options.length = 0;
                   14912:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14913:         }
1.1059    raeburn  14914:         titleCheck(form,count,offset);
1.1056    raeburn  14915:     }
                   14916: }
                   14917: 
                   14918: function propagateSelect(form,count,offset) {
                   14919:     if (count > 0) {
1.1065    raeburn  14920:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14921:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14922:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14923:             if (parents[count].length > 0) {
                   14924:                 for (var j=0; j<parents[count].length; j++) {
                   14925:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14926:                 }
                   14927:             }
                   14928:         }
                   14929:     }
                   14930: }
1.1056    raeburn  14931: 
                   14932: function containerSelect(form,count,offset,picked) {
                   14933:     if (count > 0) {
1.1065    raeburn  14934:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14935:         if (form.elements[item].type == 'radio') {
                   14936:             if (form.elements[item].value == 'dependency') {
                   14937:                 if (form.elements[item+1].type == 'select-one') {
                   14938:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14939:                         if (form.elements[item+1].options[i].value == picked) {
                   14940:                             form.elements[item+1].selectedIndex = i;
                   14941:                             break;
                   14942:                         }
                   14943:                     }
                   14944:                 }
                   14945:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14946:                     if (parents[count].length > 0) {
                   14947:                         for (var j=0; j<parents[count].length; j++) {
                   14948:                             containerSelect(form,parents[count][j],offset,picked);
                   14949:                         }
                   14950:                     }
                   14951:                 }
                   14952:             }
                   14953:         }
                   14954:     }
                   14955: }
                   14956: 
1.1059    raeburn  14957: function titleCheck(form,count,offset) {
                   14958:     if (count > 0) {
                   14959:         var chosen = (offset+$startcount)+7*(count-1);
                   14960:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14961:         var currtype = form.elements[depitem].type;
                   14962:         if (form.elements[chosen].value == 'display') {
                   14963:             document.getElementById('arc_title_'+count).style.display='block';
                   14964:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14965:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14966:             }
                   14967:         } else {
                   14968:             document.getElementById('arc_title_'+count).style.display='none';
                   14969:             if (currtype == 'text') { 
                   14970:                 document.getElementById('archive_title_'+count).value='';
                   14971:             }
                   14972:         }
                   14973:     }
                   14974:     return;
                   14975: }
                   14976: 
1.1055    raeburn  14977: // ]]>
                   14978: </script>
                   14979: END
                   14980:     return $scripttag;
                   14981: }
                   14982: 
                   14983: sub process_extracted_files {
1.1067    raeburn  14984:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14985:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14986:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14987:     my @ids=&Apache::lonnet::current_machine_ids();
                   14988:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14989:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14990:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14991:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14992:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14993:         $pathtocheck = "$dir_root/$destination";
                   14994:         $dir = $dir_root;
                   14995:         $ishome = 1;
                   14996:     } else {
                   14997:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14998:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14999:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  15000:     }
                   15001:     my $currdir = "$dir_root/$destination";
                   15002:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   15003:     if ($env{'form.folderpath'}) {
                   15004:         my @items = split('&',$env{'form.folderpath'});
                   15005:         $folders{'0'} = $items[-2];
1.1099    raeburn  15006:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   15007:             $containers{'0'}='page';
                   15008:         } else {  
                   15009:             $containers{'0'}='sequence';
                   15010:         }
1.1055    raeburn  15011:     }
                   15012:     my @archdirs = &get_env_multiple('form.archive_directory');
                   15013:     if ($numitems) {
                   15014:         for (my $i=1; $i<=$numitems; $i++) {
                   15015:             my $path = $env{'form.archive_content_'.$i};
                   15016:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   15017:                 my $item = $1;
                   15018:                 $toplevelitems{$item} = $i;
                   15019:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   15020:                     $is_dir{$item} = 1;
                   15021:                 }
                   15022:             }
                   15023:         }
                   15024:     }
1.1067    raeburn  15025:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  15026:     if (keys(%toplevelitems) > 0) {
                   15027:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  15028:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   15029:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  15030:     }
1.1066    raeburn  15031:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  15032:     if ($numitems) {
                   15033:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  15034:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  15035:             my $path = $env{'form.archive_content_'.$i};
                   15036:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15037:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   15038:                     if ($prefix ne '' && $path ne '') {
                   15039:                         if (-e $prefix.$path) {
1.1066    raeburn  15040:                             if ((@archdirs > 0) && 
                   15041:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   15042:                                 $todeletedir{$prefix.$path} = 1;
                   15043:                             } else {
                   15044:                                 $todelete{$prefix.$path} = 1;
                   15045:                             }
1.1055    raeburn  15046:                         }
                   15047:                     }
                   15048:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  15049:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  15050:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  15051:                     $docstitle = $env{'form.archive_title_'.$i};
                   15052:                     if ($docstitle eq '') {
                   15053:                         $docstitle = $title;
                   15054:                     }
1.1055    raeburn  15055:                     $outer = 0;
1.1056    raeburn  15056:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15057:                         if (@{$dirorder{$i}} > 0) {
                   15058:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  15059:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   15060:                                     $outer = $item;
                   15061:                                     last;
                   15062:                                 }
                   15063:                             }
                   15064:                         }
                   15065:                     }
                   15066:                     my ($errtext,$fatal) = 
                   15067:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   15068:                                                '/'.$folders{$outer}.'.'.
                   15069:                                                $containers{$outer});
                   15070:                     next if ($fatal);
                   15071:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   15072:                         if ($context eq 'coursedocs') {
1.1056    raeburn  15073:                             $mapinner{$i} = time;
1.1055    raeburn  15074:                             $folders{$i} = 'default_'.$mapinner{$i};
                   15075:                             $containers{$i} = 'sequence';
                   15076:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15077:                                       $folders{$i}.'.'.$containers{$i};
                   15078:                             my $newidx = &LONCAPA::map::getresidx();
                   15079:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  15080:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  15081:                             push(@LONCAPA::map::order,$newidx);
                   15082:                             my ($outtext,$errtext) =
                   15083:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15084:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  15085:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  15086:                             $newseqid{$i} = $newidx;
1.1067    raeburn  15087:                             unless ($errtext) {
1.1294    raeburn  15088:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   15089:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   15090:                                             '</li>'."\n";
1.1067    raeburn  15091:                             }
1.1055    raeburn  15092:                         }
                   15093:                     } else {
                   15094:                         if ($context eq 'coursedocs') {
                   15095:                             my $newidx=&LONCAPA::map::getresidx();
                   15096:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   15097:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   15098:                                       $title;
1.1392    raeburn  15099:                             if (($outer !~ /\D/) &&
                   15100:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   15101:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  15102:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   15103:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   15104:                                 }
                   15105:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15106:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   15107:                                 }
                   15108:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   15109:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   15110:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   15111:                                         unless ($ishome) {
                   15112:                                             my $fetch = "$newdest{$i}/$title";
                   15113:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   15114:                                             $prompttofetch{$fetch} = 1;
                   15115:                                         }
1.1292    raeburn  15116:                                     }
1.1067    raeburn  15117:                                 }
1.1294    raeburn  15118:                                 $LONCAPA::map::resources[$newidx]=
                   15119:                                     $docstitle.':'.$url.':false:normal:res';
                   15120:                                 push(@LONCAPA::map::order, $newidx);
                   15121:                                 my ($outtext,$errtext)=
                   15122:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   15123:                                                             $docuname.'/'.$folders{$outer}.
                   15124:                                                             '.'.$containers{$outer},1,1);
                   15125:                                 unless ($errtext) {
                   15126:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   15127:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   15128:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   15129:                                                    '</li>'."\n";
                   15130:                                     }
1.1067    raeburn  15131:                                 }
1.1294    raeburn  15132:                             } else {
                   15133:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15134:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  15135:                             }
1.1055    raeburn  15136:                         }
                   15137:                     }
1.1086    raeburn  15138:                 }
                   15139:             } else {
1.1294    raeburn  15140:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   15141:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  15142:             }
                   15143:         }
                   15144:         for (my $i=1; $i<=$numitems; $i++) {
                   15145:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   15146:             my $path = $env{'form.archive_content_'.$i};
                   15147:             if ($path =~ /^\Q$pathtocheck\E/) {
                   15148:                 my ($title) = ($path =~ m{/([^/]+)$});
                   15149:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   15150:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   15151:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   15152:                         my ($itemidx,$fullpath,$relpath);
                   15153:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   15154:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  15155:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  15156:                                 if ($dirorder{$i}->[$j] eq $container) {
                   15157:                                     $itemidx = $j;
1.1056    raeburn  15158:                                 }
                   15159:                             }
1.1086    raeburn  15160:                         }
                   15161:                         if ($itemidx eq '') {
                   15162:                             $itemidx =  0;
                   15163:                         } 
                   15164:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   15165:                             if ($mapinner{$referrer{$i}}) {
                   15166:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   15167:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15168:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15169:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15170:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15171:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15172:                                             if (!-e $fullpath) {
                   15173:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15174:                                             }
                   15175:                                         }
1.1086    raeburn  15176:                                     } else {
                   15177:                                         last;
1.1056    raeburn  15178:                                     }
1.1086    raeburn  15179:                                 }
                   15180:                             }
                   15181:                         } elsif ($newdest{$referrer{$i}}) {
                   15182:                             $fullpath = $newdest{$referrer{$i}};
                   15183:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15184:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15185:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15186:                                     last;
                   15187:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15188:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15189:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15190:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15191:                                         if (!-e $fullpath) {
                   15192:                                             mkdir($fullpath,0755);
1.1056    raeburn  15193:                                         }
                   15194:                                     }
1.1086    raeburn  15195:                                 } else {
                   15196:                                     last;
1.1056    raeburn  15197:                                 }
1.1055    raeburn  15198:                             }
                   15199:                         }
1.1086    raeburn  15200:                         if ($fullpath ne '') {
                   15201:                             if (-e "$prefix$path") {
1.1292    raeburn  15202:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15203:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15204:                                 }
1.1086    raeburn  15205:                             }
                   15206:                             if (-e "$fullpath/$title") {
                   15207:                                 my $showpath;
                   15208:                                 if ($relpath ne '') {
                   15209:                                     $showpath = "$relpath/$title";
                   15210:                                 } else {
                   15211:                                     $showpath = "/$title";
                   15212:                                 } 
1.1294    raeburn  15213:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15214:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15215:                                            '</li>'."\n";
1.1292    raeburn  15216:                                 unless ($ishome) {
                   15217:                                     my $fetch = "$fullpath/$title";
                   15218:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15219:                                     $prompttofetch{$fetch} = 1;
                   15220:                                 }
1.1086    raeburn  15221:                             }
                   15222:                         }
1.1055    raeburn  15223:                     }
1.1086    raeburn  15224:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15225:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15226:                                     &HTML::Entities::encode($path,'<>&"'),
                   15227:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15228:                                 '<br />';
1.1055    raeburn  15229:                 }
                   15230:             } else {
1.1294    raeburn  15231:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15232:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15233:             }
                   15234:         }
                   15235:         if (keys(%todelete)) {
                   15236:             foreach my $key (keys(%todelete)) {
                   15237:                 unlink($key);
1.1066    raeburn  15238:             }
                   15239:         }
                   15240:         if (keys(%todeletedir)) {
                   15241:             foreach my $key (keys(%todeletedir)) {
                   15242:                 rmdir($key);
                   15243:             }
                   15244:         }
                   15245:         foreach my $dir (sort(keys(%is_dir))) {
                   15246:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15247:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15248:             }
                   15249:         }
1.1067    raeburn  15250:         if ($result ne '') {
                   15251:             $output .= '<ul>'."\n".
                   15252:                        $result."\n".
                   15253:                        '</ul>';
                   15254:         }
                   15255:         unless ($ishome) {
                   15256:             my $replicationfail;
                   15257:             foreach my $item (keys(%prompttofetch)) {
                   15258:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15259:                 unless ($fetchresult eq 'ok') {
                   15260:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15261:                 }
                   15262:             }
                   15263:             if ($replicationfail) {
                   15264:                 $output .= '<p class="LC_error">'.
                   15265:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15266:                            $replicationfail.
                   15267:                            '</ul></p>';
                   15268:             }
                   15269:         }
1.1055    raeburn  15270:     } else {
                   15271:         $warning = &mt('No items found in archive.');
                   15272:     }
                   15273:     if ($error) {
                   15274:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15275:                    $error.'</p>'."\n";
                   15276:     }
                   15277:     if ($warning) {
                   15278:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15279:     }
                   15280:     return $output;
                   15281: }
                   15282: 
1.1066    raeburn  15283: sub cleanup_empty_dirs {
                   15284:     my ($path) = @_;
                   15285:     if (($path ne '') && (-d $path)) {
                   15286:         if (opendir(my $dirh,$path)) {
                   15287:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15288:             my $numitems = 0;
                   15289:             foreach my $item (@dircontents) {
                   15290:                 if (-d "$path/$item") {
1.1111    raeburn  15291:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15292:                     if (-e "$path/$item") {
                   15293:                         $numitems ++;
                   15294:                     }
                   15295:                 } else {
                   15296:                     $numitems ++;
                   15297:                 }
                   15298:             }
                   15299:             if ($numitems == 0) {
                   15300:                 rmdir($path);
                   15301:             }
                   15302:             closedir($dirh);
                   15303:         }
                   15304:     }
                   15305:     return;
                   15306: }
                   15307: 
1.41      ng       15308: =pod
1.45      matthew  15309: 
1.1162    raeburn  15310: =item * &get_folder_hierarchy()
1.1068    raeburn  15311: 
                   15312: Provides hierarchy of names of folders/sub-folders containing the current
                   15313: item,
                   15314: 
                   15315: Inputs: 3
                   15316:      - $navmap - navmaps object
                   15317: 
                   15318:      - $map - url for map (either the trigger itself, or map containing
                   15319:                            the resource, which is the trigger).
                   15320: 
                   15321:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15322: 
                   15323: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15324: 
                   15325: =cut
                   15326: 
                   15327: sub get_folder_hierarchy {
                   15328:     my ($navmap,$map,$showitem) = @_;
                   15329:     my @pathitems;
                   15330:     if (ref($navmap)) {
                   15331:         my $mapres = $navmap->getResourceByUrl($map);
                   15332:         if (ref($mapres)) {
                   15333:             my $pcslist = $mapres->map_hierarchy();
                   15334:             if ($pcslist ne '') {
                   15335:                 my @pcs = split(/,/,$pcslist);
                   15336:                 foreach my $pc (@pcs) {
                   15337:                     if ($pc == 1) {
1.1129    raeburn  15338:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15339:                     } else {
                   15340:                         my $res = $navmap->getByMapPc($pc);
                   15341:                         if (ref($res)) {
                   15342:                             my $title = $res->compTitle();
                   15343:                             $title =~ s/\W+/_/g;
                   15344:                             if ($title ne '') {
                   15345:                                 push(@pathitems,$title);
                   15346:                             }
                   15347:                         }
                   15348:                     }
                   15349:                 }
                   15350:             }
1.1071    raeburn  15351:             if ($showitem) {
                   15352:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15353:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15354:                 } else {
                   15355:                     my $maptitle = $mapres->compTitle();
                   15356:                     $maptitle =~ s/\W+/_/g;
                   15357:                     if ($maptitle ne '') {
                   15358:                         push(@pathitems,$maptitle);
                   15359:                     }
1.1068    raeburn  15360:                 }
                   15361:             }
                   15362:         }
                   15363:     }
                   15364:     return @pathitems;
                   15365: }
                   15366: 
                   15367: =pod
                   15368: 
1.1015    raeburn  15369: =item * &get_turnedin_filepath()
                   15370: 
                   15371: Determines path in a user's portfolio file for storage of files uploaded
                   15372: to a specific essayresponse or dropbox item.
                   15373: 
                   15374: Inputs: 3 required + 1 optional.
                   15375: $symb is symb for resource, $uname and $udom are for current user (required).
                   15376: $caller is optional (can be "submission", if routine is called when storing
                   15377: an upoaded file when "Submit Answer" button was pressed).
                   15378: 
                   15379: Returns array containing $path and $multiresp. 
                   15380: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15381: than one file upload item.  Callers of routine should append partid as a 
                   15382: subdirectory to $path in cases where $multiresp is 1.
                   15383: 
                   15384: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15385: 
                   15386: =cut
                   15387: 
                   15388: sub get_turnedin_filepath {
                   15389:     my ($symb,$uname,$udom,$caller) = @_;
                   15390:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15391:     my $turnindir;
                   15392:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15393:     $turnindir = $userhash{'turnindir'};
                   15394:     my ($path,$multiresp);
                   15395:     if ($turnindir eq '') {
                   15396:         if ($caller eq 'submission') {
                   15397:             $turnindir = &mt('turned in');
                   15398:             $turnindir =~ s/\W+/_/g;
                   15399:             my %newhash = (
                   15400:                             'turnindir' => $turnindir,
                   15401:                           );
                   15402:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15403:         }
                   15404:     }
                   15405:     if ($turnindir ne '') {
                   15406:         $path = '/'.$turnindir.'/';
                   15407:         my ($multipart,$turnin,@pathitems);
                   15408:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15409:         if (defined($navmap)) {
                   15410:             my $mapres = $navmap->getResourceByUrl($map);
                   15411:             if (ref($mapres)) {
                   15412:                 my $pcslist = $mapres->map_hierarchy();
                   15413:                 if ($pcslist ne '') {
                   15414:                     foreach my $pc (split(/,/,$pcslist)) {
                   15415:                         my $res = $navmap->getByMapPc($pc);
                   15416:                         if (ref($res)) {
                   15417:                             my $title = $res->compTitle();
                   15418:                             $title =~ s/\W+/_/g;
                   15419:                             if ($title ne '') {
1.1149    raeburn  15420:                                 if (($pc > 1) && (length($title) > 12)) {
                   15421:                                     $title = substr($title,0,12);
                   15422:                                 }
1.1015    raeburn  15423:                                 push(@pathitems,$title);
                   15424:                             }
                   15425:                         }
                   15426:                     }
                   15427:                 }
                   15428:                 my $maptitle = $mapres->compTitle();
                   15429:                 $maptitle =~ s/\W+/_/g;
                   15430:                 if ($maptitle ne '') {
1.1149    raeburn  15431:                     if (length($maptitle) > 12) {
                   15432:                         $maptitle = substr($maptitle,0,12);
                   15433:                     }
1.1015    raeburn  15434:                     push(@pathitems,$maptitle);
                   15435:                 }
                   15436:                 unless ($env{'request.state'} eq 'construct') {
                   15437:                     my $res = $navmap->getBySymb($symb);
                   15438:                     if (ref($res)) {
                   15439:                         my $partlist = $res->parts();
                   15440:                         my $totaluploads = 0;
                   15441:                         if (ref($partlist) eq 'ARRAY') {
                   15442:                             foreach my $part (@{$partlist}) {
                   15443:                                 my @types = $res->responseType($part);
                   15444:                                 my @ids = $res->responseIds($part);
                   15445:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15446:                                     if ($types[$i] eq 'essay') {
                   15447:                                         my $partid = $part.'_'.$ids[$i];
                   15448:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15449:                                             $totaluploads ++;
                   15450:                                         }
                   15451:                                     }
                   15452:                                 }
                   15453:                             }
                   15454:                             if ($totaluploads > 1) {
                   15455:                                 $multiresp = 1;
                   15456:                             }
                   15457:                         }
                   15458:                     }
                   15459:                 }
                   15460:             } else {
                   15461:                 return;
                   15462:             }
                   15463:         } else {
                   15464:             return;
                   15465:         }
                   15466:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15467:         $restitle =~ s/\W+/_/g;
                   15468:         if ($restitle eq '') {
                   15469:             $restitle = ($resurl =~ m{/[^/]+$});
                   15470:             if ($restitle eq '') {
                   15471:                 $restitle = time;
                   15472:             }
                   15473:         }
1.1149    raeburn  15474:         if (length($restitle) > 12) {
                   15475:             $restitle = substr($restitle,0,12);
                   15476:         }
1.1015    raeburn  15477:         push(@pathitems,$restitle);
                   15478:         $path .= join('/',@pathitems);
                   15479:     }
                   15480:     return ($path,$multiresp);
                   15481: }
                   15482: 
                   15483: =pod
                   15484: 
1.464     albertel 15485: =back
1.41      ng       15486: 
1.112     bowersj2 15487: =head1 CSV Upload/Handling functions
1.38      albertel 15488: 
1.41      ng       15489: =over 4
                   15490: 
1.648     raeburn  15491: =item * &upfile_store($r)
1.41      ng       15492: 
                   15493: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15494: needs $env{'form.upfile'}
1.41      ng       15495: returns $datatoken to be put into hidden field
                   15496: 
                   15497: =cut
1.31      albertel 15498: 
                   15499: sub upfile_store {
                   15500:     my $r=shift;
1.258     albertel 15501:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15502:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15503:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15504:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15505: 
1.1299    raeburn  15506:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15507:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15508:                                      time.'_'.$$);
                   15509:     return if ($datatoken eq '');
                   15510: 
1.31      albertel 15511:     {
1.158     raeburn  15512:         my $datafile = $r->dir_config('lonDaemons').
                   15513:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15514:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15515:             print $fh $env{'form.upfile'};
1.158     raeburn  15516:             close($fh);
                   15517:         }
1.31      albertel 15518:     }
                   15519:     return $datatoken;
                   15520: }
                   15521: 
1.56      matthew  15522: =pod
                   15523: 
1.1290    raeburn  15524: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15525: 
                   15526: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15527: $datatoken is the name to assign to the temporary file.
1.258     albertel 15528: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15529: 
                   15530: =cut
1.31      albertel 15531: 
                   15532: sub load_tmp_file {
1.1290    raeburn  15533:     my ($r,$datatoken) = @_;
                   15534:     return if ($datatoken eq '');
1.31      albertel 15535:     my @studentdata=();
                   15536:     {
1.158     raeburn  15537:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15538:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15539:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15540:             @studentdata=<$fh>;
                   15541:             close($fh);
                   15542:         }
1.31      albertel 15543:     }
1.258     albertel 15544:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15545: }
                   15546: 
1.1290    raeburn  15547: sub valid_datatoken {
                   15548:     my ($datatoken) = @_;
1.1325    raeburn  15549:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15550:         return $datatoken;
                   15551:     }
                   15552:     return;
                   15553: }
                   15554: 
1.56      matthew  15555: =pod
                   15556: 
1.648     raeburn  15557: =item * &upfile_record_sep()
1.41      ng       15558: 
                   15559: Separate uploaded file into records
                   15560: returns array of records,
1.258     albertel 15561: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15562: 
                   15563: =cut
1.31      albertel 15564: 
                   15565: sub upfile_record_sep {
1.258     albertel 15566:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15567:     } else {
1.248     albertel 15568: 	my @records;
1.258     albertel 15569: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15570: 	    if ($line=~/^\s*$/) { next; }
                   15571: 	    push(@records,$line);
                   15572: 	}
                   15573: 	return @records;
1.31      albertel 15574:     }
                   15575: }
                   15576: 
1.56      matthew  15577: =pod
                   15578: 
1.648     raeburn  15579: =item * &record_sep($record)
1.41      ng       15580: 
1.258     albertel 15581: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15582: 
                   15583: =cut
                   15584: 
1.263     www      15585: sub takeleft {
                   15586:     my $index=shift;
                   15587:     return substr('0000'.$index,-4,4);
                   15588: }
                   15589: 
1.31      albertel 15590: sub record_sep {
                   15591:     my $record=shift;
                   15592:     my %components=();
1.258     albertel 15593:     if ($env{'form.upfiletype'} eq 'xml') {
                   15594:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15595:         my $i=0;
1.356     albertel 15596:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15597:             $field=~s/^(\"|\')//;
                   15598:             $field=~s/(\"|\')$//;
1.263     www      15599:             $components{&takeleft($i)}=$field;
1.31      albertel 15600:             $i++;
                   15601:         }
1.258     albertel 15602:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15603:         my $i=0;
1.356     albertel 15604:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15605:             $field=~s/^(\"|\')//;
                   15606:             $field=~s/(\"|\')$//;
1.263     www      15607:             $components{&takeleft($i)}=$field;
1.31      albertel 15608:             $i++;
                   15609:         }
                   15610:     } else {
1.561     www      15611:         my $separator=',';
1.480     banghart 15612:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15613:             $separator=';';
1.480     banghart 15614:         }
1.31      albertel 15615:         my $i=0;
1.561     www      15616: # the character we are looking for to indicate the end of a quote or a record 
                   15617:         my $looking_for=$separator;
                   15618: # do not add the characters to the fields
                   15619:         my $ignore=0;
                   15620: # we just encountered a separator (or the beginning of the record)
                   15621:         my $just_found_separator=1;
                   15622: # store the field we are working on here
                   15623:         my $field='';
                   15624: # work our way through all characters in record
                   15625:         foreach my $character ($record=~/(.)/g) {
                   15626:             if ($character eq $looking_for) {
                   15627:                if ($character ne $separator) {
                   15628: # Found the end of a quote, again looking for separator
                   15629:                   $looking_for=$separator;
                   15630:                   $ignore=1;
                   15631:                } else {
                   15632: # Found a separator, store away what we got
                   15633:                   $components{&takeleft($i)}=$field;
                   15634: 	          $i++;
                   15635:                   $just_found_separator=1;
                   15636:                   $ignore=0;
                   15637:                   $field='';
                   15638:                }
                   15639:                next;
                   15640:             }
                   15641: # single or double quotation marks after a separator indicate beginning of a quote
                   15642: # we are now looking for the end of the quote and need to ignore separators
                   15643:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15644:                $looking_for=$character;
                   15645:                next;
                   15646:             }
                   15647: # ignore would be true after we reached the end of a quote
                   15648:             if ($ignore) { next; }
                   15649:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15650:             $field.=$character;
                   15651:             $just_found_separator=0; 
1.31      albertel 15652:         }
1.561     www      15653: # catch the very last entry, since we never encountered the separator
                   15654:         $components{&takeleft($i)}=$field;
1.31      albertel 15655:     }
                   15656:     return %components;
                   15657: }
                   15658: 
1.144     matthew  15659: ######################################################
                   15660: ######################################################
                   15661: 
1.56      matthew  15662: =pod
                   15663: 
1.648     raeburn  15664: =item * &upfile_select_html()
1.41      ng       15665: 
1.144     matthew  15666: Return HTML code to select a file from the users machine and specify 
                   15667: the file type.
1.41      ng       15668: 
                   15669: =cut
                   15670: 
1.144     matthew  15671: ######################################################
                   15672: ######################################################
1.31      albertel 15673: sub upfile_select_html {
1.144     matthew  15674:     my %Types = (
                   15675:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15676:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15677:                  space => &mt('Space separated'),
                   15678:                  tab   => &mt('Tabulator separated'),
                   15679: #                 xml   => &mt('HTML/XML'),
                   15680:                  );
                   15681:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15682:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15683:     foreach my $type (sort(keys(%Types))) {
                   15684:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15685:     }
                   15686:     $Str .= "</select>\n";
                   15687:     return $Str;
1.31      albertel 15688: }
                   15689: 
1.301     albertel 15690: sub get_samples {
                   15691:     my ($records,$toget) = @_;
                   15692:     my @samples=({});
                   15693:     my $got=0;
                   15694:     foreach my $rec (@$records) {
                   15695: 	my %temp = &record_sep($rec);
                   15696: 	if (! grep(/\S/, values(%temp))) { next; }
                   15697: 	if (%temp) {
                   15698: 	    $samples[$got]=\%temp;
                   15699: 	    $got++;
                   15700: 	    if ($got == $toget) { last; }
                   15701: 	}
                   15702:     }
                   15703:     return \@samples;
                   15704: }
                   15705: 
1.144     matthew  15706: ######################################################
                   15707: ######################################################
                   15708: 
1.56      matthew  15709: =pod
                   15710: 
1.648     raeburn  15711: =item * &csv_print_samples($r,$records)
1.41      ng       15712: 
                   15713: Prints a table of sample values from each column uploaded $r is an
                   15714: Apache Request ref, $records is an arrayref from
                   15715: &Apache::loncommon::upfile_record_sep
                   15716: 
                   15717: =cut
                   15718: 
1.144     matthew  15719: ######################################################
                   15720: ######################################################
1.31      albertel 15721: sub csv_print_samples {
                   15722:     my ($r,$records) = @_;
1.662     bisitz   15723:     my $samples = &get_samples($records,5);
1.301     albertel 15724: 
1.594     raeburn  15725:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15726:               &start_data_table_header_row());
1.356     albertel 15727:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15728:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15729:     $r->print(&end_data_table_header_row());
1.301     albertel 15730:     foreach my $hash (@$samples) {
1.594     raeburn  15731: 	$r->print(&start_data_table_row());
1.356     albertel 15732: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15733: 	    $r->print('<td>');
1.356     albertel 15734: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15735: 	    $r->print('</td>');
                   15736: 	}
1.594     raeburn  15737: 	$r->print(&end_data_table_row());
1.31      albertel 15738:     }
1.594     raeburn  15739:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15740: }
                   15741: 
1.144     matthew  15742: ######################################################
                   15743: ######################################################
                   15744: 
1.56      matthew  15745: =pod
                   15746: 
1.648     raeburn  15747: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15748: 
                   15749: Prints a table to create associations between values and table columns.
1.144     matthew  15750: 
1.41      ng       15751: $r is an Apache Request ref,
                   15752: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15753: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15754: 
                   15755: =cut
                   15756: 
1.144     matthew  15757: ######################################################
                   15758: ######################################################
1.31      albertel 15759: sub csv_print_select_table {
                   15760:     my ($r,$records,$d) = @_;
1.301     albertel 15761:     my $i=0;
                   15762:     my $samples = &get_samples($records,1);
1.144     matthew  15763:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15764: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15765:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15766:               '<th>'.&mt('Column').'</th>'.
                   15767:               &end_data_table_header_row()."\n");
1.356     albertel 15768:     foreach my $array_ref (@$d) {
                   15769: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15770: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15771: 
1.875     bisitz   15772: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15773: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15774: 	$r->print('<option value="none"></option>');
1.356     albertel 15775: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15776: 	    $r->print('<option value="'.$sample.'"'.
                   15777:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15778:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15779: 	}
1.594     raeburn  15780: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15781: 	$i++;
                   15782:     }
1.594     raeburn  15783:     $r->print(&end_data_table());
1.31      albertel 15784:     $i--;
                   15785:     return $i;
                   15786: }
1.56      matthew  15787: 
1.144     matthew  15788: ######################################################
                   15789: ######################################################
                   15790: 
1.56      matthew  15791: =pod
1.31      albertel 15792: 
1.648     raeburn  15793: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15794: 
                   15795: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15796: 
                   15797: $r is an Apache Request ref,
                   15798: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15799: $d is an array of 2 element arrays (internal name, displayed name)
                   15800: 
                   15801: =cut
                   15802: 
1.144     matthew  15803: ######################################################
                   15804: ######################################################
1.31      albertel 15805: sub csv_samples_select_table {
                   15806:     my ($r,$records,$d) = @_;
                   15807:     my $i=0;
1.144     matthew  15808:     #
1.662     bisitz   15809:     my $max_samples = 5;
                   15810:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15811:     $r->print(&start_data_table().
                   15812:               &start_data_table_header_row().'<th>'.
                   15813:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15814:               &end_data_table_header_row());
1.301     albertel 15815: 
                   15816:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15817: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15818: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15819: 	foreach my $option (@$d) {
                   15820: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15821: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15822:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15823:                       $display.'</option>');
1.31      albertel 15824: 	}
                   15825: 	$r->print('</select></td><td>');
1.662     bisitz   15826: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15827: 	    if (defined($samples->[$line]{$key})) { 
                   15828: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15829: 	    }
                   15830: 	}
1.594     raeburn  15831: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15832: 	$i++;
                   15833:     }
1.594     raeburn  15834:     $r->print(&end_data_table());
1.31      albertel 15835:     $i--;
                   15836:     return($i);
1.115     matthew  15837: }
                   15838: 
1.144     matthew  15839: ######################################################
                   15840: ######################################################
                   15841: 
1.115     matthew  15842: =pod
                   15843: 
1.648     raeburn  15844: =item * &clean_excel_name($name)
1.115     matthew  15845: 
                   15846: Returns a replacement for $name which does not contain any illegal characters.
                   15847: 
                   15848: =cut
                   15849: 
1.144     matthew  15850: ######################################################
                   15851: ######################################################
1.115     matthew  15852: sub clean_excel_name {
                   15853:     my ($name) = @_;
                   15854:     $name =~ s/[:\*\?\/\\]//g;
                   15855:     if (length($name) > 31) {
                   15856:         $name = substr($name,0,31);
                   15857:     }
                   15858:     return $name;
1.25      albertel 15859: }
1.84      albertel 15860: 
1.85      albertel 15861: =pod
                   15862: 
1.648     raeburn  15863: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15864: 
                   15865: Returns either 1 or undef
                   15866: 
                   15867: 1 if the part is to be hidden, undef if it is to be shown
                   15868: 
                   15869: Arguments are:
                   15870: 
                   15871: $id the id of the part to be checked
                   15872: $symb, optional the symb of the resource to check
                   15873: $udom, optional the domain of the user to check for
                   15874: $uname, optional the username of the user to check for
                   15875: 
                   15876: =cut
1.84      albertel 15877: 
                   15878: sub check_if_partid_hidden {
                   15879:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15880:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15881: 					 $symb,$udom,$uname);
1.141     albertel 15882:     my $truth=1;
                   15883:     #if the string starts with !, then the list is the list to show not hide
                   15884:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15885:     my @hiddenlist=split(/,/,$hiddenparts);
                   15886:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15887: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15888:     }
1.141     albertel 15889:     return !$truth;
1.84      albertel 15890: }
1.127     matthew  15891: 
1.138     matthew  15892: 
                   15893: ############################################################
                   15894: ############################################################
                   15895: 
                   15896: =pod
                   15897: 
1.157     matthew  15898: =back 
                   15899: 
1.138     matthew  15900: =head1 cgi-bin script and graphing routines
                   15901: 
1.157     matthew  15902: =over 4
                   15903: 
1.648     raeburn  15904: =item * &get_cgi_id()
1.138     matthew  15905: 
                   15906: Inputs: none
                   15907: 
                   15908: Returns an id which can be used to pass environment variables
                   15909: to various cgi-bin scripts.  These environment variables will
                   15910: be removed from the users environment after a given time by
                   15911: the routine &Apache::lonnet::transfer_profile_to_env.
                   15912: 
                   15913: =cut
                   15914: 
                   15915: ############################################################
                   15916: ############################################################
1.152     albertel 15917: my $uniq=0;
1.136     matthew  15918: sub get_cgi_id {
1.154     albertel 15919:     $uniq=($uniq+1)%100000;
1.280     albertel 15920:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15921: }
                   15922: 
1.127     matthew  15923: ############################################################
                   15924: ############################################################
                   15925: 
                   15926: =pod
                   15927: 
1.648     raeburn  15928: =item * &DrawBarGraph()
1.127     matthew  15929: 
1.138     matthew  15930: Facilitates the plotting of data in a (stacked) bar graph.
                   15931: Puts plot definition data into the users environment in order for 
                   15932: graph.png to plot it.  Returns an <img> tag for the plot.
                   15933: The bars on the plot are labeled '1','2',...,'n'.
                   15934: 
                   15935: Inputs:
                   15936: 
                   15937: =over 4
                   15938: 
                   15939: =item $Title: string, the title of the plot
                   15940: 
                   15941: =item $xlabel: string, text describing the X-axis of the plot
                   15942: 
                   15943: =item $ylabel: string, text describing the Y-axis of the plot
                   15944: 
                   15945: =item $Max: scalar, the maximum Y value to use in the plot
                   15946: If $Max is < any data point, the graph will not be rendered.
                   15947: 
1.140     matthew  15948: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15949: they are plotted.  If undefined, default values will be used.
                   15950: 
1.178     matthew  15951: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15952: 
1.138     matthew  15953: =item @Values: An array of array references.  Each array reference holds data
                   15954: to be plotted in a stacked bar chart.
                   15955: 
1.239     matthew  15956: =item If the final element of @Values is a hash reference the key/value
                   15957: pairs will be added to the graph definition.
                   15958: 
1.138     matthew  15959: =back
                   15960: 
                   15961: Returns:
                   15962: 
                   15963: An <img> tag which references graph.png and the appropriate identifying
                   15964: information for the plot.
                   15965: 
1.127     matthew  15966: =cut
                   15967: 
                   15968: ############################################################
                   15969: ############################################################
1.134     matthew  15970: sub DrawBarGraph {
1.178     matthew  15971:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15972:     #
                   15973:     if (! defined($colors)) {
                   15974:         $colors = ['#33ff00', 
                   15975:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15976:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15977:                   ]; 
                   15978:     }
1.228     matthew  15979:     my $extra_settings = {};
                   15980:     if (ref($Values[-1]) eq 'HASH') {
                   15981:         $extra_settings = pop(@Values);
                   15982:     }
1.127     matthew  15983:     #
1.136     matthew  15984:     my $identifier = &get_cgi_id();
                   15985:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15986:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15987:         return '';
                   15988:     }
1.225     matthew  15989:     #
                   15990:     my @Labels;
                   15991:     if (defined($labels)) {
                   15992:         @Labels = @$labels;
                   15993:     } else {
                   15994:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15995:             push(@Labels,$i+1);
1.225     matthew  15996:         }
                   15997:     }
                   15998:     #
1.129     matthew  15999:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  16000:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  16001:     my %ValuesHash;
                   16002:     my $NumSets=1;
                   16003:     foreach my $array (@Values) {
                   16004:         next if (! ref($array));
1.136     matthew  16005:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  16006:             join(',',@$array);
1.129     matthew  16007:     }
1.127     matthew  16008:     #
1.136     matthew  16009:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  16010:     if ($NumBars < 3) {
                   16011:         $width = 120+$NumBars*32;
1.220     matthew  16012:         $xskip = 1;
1.225     matthew  16013:         $bar_width = 30;
                   16014:     } elsif ($NumBars < 5) {
                   16015:         $width = 120+$NumBars*20;
                   16016:         $xskip = 1;
                   16017:         $bar_width = 20;
1.220     matthew  16018:     } elsif ($NumBars < 10) {
1.136     matthew  16019:         $width = 120+$NumBars*15;
                   16020:         $xskip = 1;
                   16021:         $bar_width = 15;
                   16022:     } elsif ($NumBars <= 25) {
                   16023:         $width = 120+$NumBars*11;
                   16024:         $xskip = 5;
                   16025:         $bar_width = 8;
                   16026:     } elsif ($NumBars <= 50) {
                   16027:         $width = 120+$NumBars*8;
                   16028:         $xskip = 5;
                   16029:         $bar_width = 4;
                   16030:     } else {
                   16031:         $width = 120+$NumBars*8;
                   16032:         $xskip = 5;
                   16033:         $bar_width = 4;
                   16034:     }
                   16035:     #
1.137     matthew  16036:     $Max = 1 if ($Max < 1);
                   16037:     if ( int($Max) < $Max ) {
                   16038:         $Max++;
                   16039:         $Max = int($Max);
                   16040:     }
1.127     matthew  16041:     $Title  = '' if (! defined($Title));
                   16042:     $xlabel = '' if (! defined($xlabel));
                   16043:     $ylabel = '' if (! defined($ylabel));
1.369     www      16044:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   16045:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   16046:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  16047:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  16048:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   16049:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   16050:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   16051:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16052:     $ValuesHash{$id.'.height'}   = $height;
                   16053:     $ValuesHash{$id.'.width'}    = $width;
                   16054:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   16055:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   16056:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  16057:     #
1.228     matthew  16058:     # Deal with other parameters
                   16059:     while (my ($key,$value) = each(%$extra_settings)) {
                   16060:         $ValuesHash{$id.'.'.$key} = $value;
                   16061:     }
                   16062:     #
1.646     raeburn  16063:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  16064:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16065: }
                   16066: 
                   16067: ############################################################
                   16068: ############################################################
                   16069: 
                   16070: =pod
                   16071: 
1.648     raeburn  16072: =item * &DrawXYGraph()
1.137     matthew  16073: 
1.138     matthew  16074: Facilitates the plotting of data in an XY graph.
                   16075: Puts plot definition data into the users environment in order for 
                   16076: graph.png to plot it.  Returns an <img> tag for the plot.
                   16077: 
                   16078: Inputs:
                   16079: 
                   16080: =over 4
                   16081: 
                   16082: =item $Title: string, the title of the plot
                   16083: 
                   16084: =item $xlabel: string, text describing the X-axis of the plot
                   16085: 
                   16086: =item $ylabel: string, text describing the Y-axis of the plot
                   16087: 
                   16088: =item $Max: scalar, the maximum Y value to use in the plot
                   16089: If $Max is < any data point, the graph will not be rendered.
                   16090: 
                   16091: =item $colors: Array ref containing the hex color codes for the data to be 
                   16092: plotted in.  If undefined, default values will be used.
                   16093: 
                   16094: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16095: 
                   16096: =item $Ydata: Array ref containing Array refs.  
1.185     www      16097: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  16098: 
                   16099: =item %Values: hash indicating or overriding any default values which are 
                   16100: passed to graph.png.  
                   16101: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16102: 
                   16103: =back
                   16104: 
                   16105: Returns:
                   16106: 
                   16107: An <img> tag which references graph.png and the appropriate identifying
                   16108: information for the plot.
                   16109: 
1.137     matthew  16110: =cut
                   16111: 
                   16112: ############################################################
                   16113: ############################################################
                   16114: sub DrawXYGraph {
                   16115:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   16116:     #
                   16117:     # Create the identifier for the graph
                   16118:     my $identifier = &get_cgi_id();
                   16119:     my $id = 'cgi.'.$identifier;
                   16120:     #
                   16121:     $Title  = '' if (! defined($Title));
                   16122:     $xlabel = '' if (! defined($xlabel));
                   16123:     $ylabel = '' if (! defined($ylabel));
                   16124:     my %ValuesHash = 
                   16125:         (
1.369     www      16126:          $id.'.title'  => &escape($Title),
                   16127:          $id.'.xlabel' => &escape($xlabel),
                   16128:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  16129:          $id.'.y_max_value'=> $Max,
                   16130:          $id.'.labels'     => join(',',@$Xlabels),
                   16131:          $id.'.PlotType'   => 'XY',
                   16132:          );
                   16133:     #
                   16134:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16135:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16136:     }
                   16137:     #
                   16138:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   16139:         return '';
                   16140:     }
                   16141:     my $NumSets=1;
1.138     matthew  16142:     foreach my $array (@{$Ydata}){
1.137     matthew  16143:         next if (! ref($array));
                   16144:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   16145:     }
1.138     matthew  16146:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  16147:     #
                   16148:     # Deal with other parameters
                   16149:     while (my ($key,$value) = each(%Values)) {
                   16150:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  16151:     }
                   16152:     #
1.646     raeburn  16153:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  16154:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   16155: }
                   16156: 
                   16157: ############################################################
                   16158: ############################################################
                   16159: 
                   16160: =pod
                   16161: 
1.648     raeburn  16162: =item * &DrawXYYGraph()
1.138     matthew  16163: 
                   16164: Facilitates the plotting of data in an XY graph with two Y axes.
                   16165: Puts plot definition data into the users environment in order for 
                   16166: graph.png to plot it.  Returns an <img> tag for the plot.
                   16167: 
                   16168: Inputs:
                   16169: 
                   16170: =over 4
                   16171: 
                   16172: =item $Title: string, the title of the plot
                   16173: 
                   16174: =item $xlabel: string, text describing the X-axis of the plot
                   16175: 
                   16176: =item $ylabel: string, text describing the Y-axis of the plot
                   16177: 
                   16178: =item $colors: Array ref containing the hex color codes for the data to be 
                   16179: plotted in.  If undefined, default values will be used.
                   16180: 
                   16181: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16182: 
                   16183: =item $Ydata1: The first data set
                   16184: 
                   16185: =item $Min1: The minimum value of the left Y-axis
                   16186: 
                   16187: =item $Max1: The maximum value of the left Y-axis
                   16188: 
                   16189: =item $Ydata2: The second data set
                   16190: 
                   16191: =item $Min2: The minimum value of the right Y-axis
                   16192: 
                   16193: =item $Max2: The maximum value of the left Y-axis
                   16194: 
                   16195: =item %Values: hash indicating or overriding any default values which are 
                   16196: passed to graph.png.  
                   16197: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16198: 
                   16199: =back
                   16200: 
                   16201: Returns:
                   16202: 
                   16203: An <img> tag which references graph.png and the appropriate identifying
                   16204: information for the plot.
1.136     matthew  16205: 
                   16206: =cut
                   16207: 
                   16208: ############################################################
                   16209: ############################################################
1.137     matthew  16210: sub DrawXYYGraph {
                   16211:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16212:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16213:     #
                   16214:     # Create the identifier for the graph
                   16215:     my $identifier = &get_cgi_id();
                   16216:     my $id = 'cgi.'.$identifier;
                   16217:     #
                   16218:     $Title  = '' if (! defined($Title));
                   16219:     $xlabel = '' if (! defined($xlabel));
                   16220:     $ylabel = '' if (! defined($ylabel));
                   16221:     my %ValuesHash = 
                   16222:         (
1.369     www      16223:          $id.'.title'  => &escape($Title),
                   16224:          $id.'.xlabel' => &escape($xlabel),
                   16225:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16226:          $id.'.labels' => join(',',@$Xlabels),
                   16227:          $id.'.PlotType' => 'XY',
                   16228:          $id.'.NumSets' => 2,
1.137     matthew  16229:          $id.'.two_axes' => 1,
                   16230:          $id.'.y1_max_value' => $Max1,
                   16231:          $id.'.y1_min_value' => $Min1,
                   16232:          $id.'.y2_max_value' => $Max2,
                   16233:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16234:          );
                   16235:     #
1.137     matthew  16236:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16237:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16238:     }
                   16239:     #
                   16240:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16241:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16242:         return '';
                   16243:     }
                   16244:     my $NumSets=1;
1.137     matthew  16245:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16246:         next if (! ref($array));
                   16247:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16248:     }
                   16249:     #
                   16250:     # Deal with other parameters
                   16251:     while (my ($key,$value) = each(%Values)) {
                   16252:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16253:     }
                   16254:     #
1.646     raeburn  16255:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16256:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16257: }
                   16258: 
                   16259: ############################################################
                   16260: ############################################################
                   16261: 
                   16262: =pod
                   16263: 
1.157     matthew  16264: =back 
                   16265: 
1.139     matthew  16266: =head1 Statistics helper routines?  
                   16267: 
                   16268: Bad place for them but what the hell.
                   16269: 
1.157     matthew  16270: =over 4
                   16271: 
1.648     raeburn  16272: =item * &chartlink()
1.139     matthew  16273: 
                   16274: Returns a link to the chart for a specific student.  
                   16275: 
                   16276: Inputs:
                   16277: 
                   16278: =over 4
                   16279: 
                   16280: =item $linktext: The text of the link
                   16281: 
                   16282: =item $sname: The students username
                   16283: 
                   16284: =item $sdomain: The students domain
                   16285: 
                   16286: =back
                   16287: 
1.157     matthew  16288: =back
                   16289: 
1.139     matthew  16290: =cut
                   16291: 
                   16292: ############################################################
                   16293: ############################################################
                   16294: sub chartlink {
                   16295:     my ($linktext, $sname, $sdomain) = @_;
                   16296:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16297:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16298:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16299:        '">'.$linktext.'</a>';
1.153     matthew  16300: }
                   16301: 
                   16302: #######################################################
                   16303: #######################################################
                   16304: 
                   16305: =pod
                   16306: 
                   16307: =head1 Course Environment Routines
1.157     matthew  16308: 
                   16309: =over 4
1.153     matthew  16310: 
1.648     raeburn  16311: =item * &restore_course_settings()
1.153     matthew  16312: 
1.648     raeburn  16313: =item * &store_course_settings()
1.153     matthew  16314: 
                   16315: Restores/Store indicated form parameters from the course environment.
                   16316: Will not overwrite existing values of the form parameters.
                   16317: 
                   16318: Inputs: 
                   16319: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16320: 
                   16321: a hash ref describing the data to be stored.  For example:
                   16322:    
                   16323: %Save_Parameters = ('Status' => 'scalar',
                   16324:     'chartoutputmode' => 'scalar',
                   16325:     'chartoutputdata' => 'scalar',
                   16326:     'Section' => 'array',
1.373     raeburn  16327:     'Group' => 'array',
1.153     matthew  16328:     'StudentData' => 'array',
                   16329:     'Maps' => 'array');
                   16330: 
                   16331: Returns: both routines return nothing
                   16332: 
1.631     raeburn  16333: =back
                   16334: 
1.153     matthew  16335: =cut
                   16336: 
                   16337: #######################################################
                   16338: #######################################################
                   16339: sub store_course_settings {
1.496     albertel 16340:     return &store_settings($env{'request.course.id'},@_);
                   16341: }
                   16342: 
                   16343: sub store_settings {
1.153     matthew  16344:     # save to the environment
                   16345:     # appenv the same items, just to be safe
1.300     albertel 16346:     my $udom  = $env{'user.domain'};
                   16347:     my $uname = $env{'user.name'};
1.496     albertel 16348:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16349:     my %SaveHash;
                   16350:     my %AppHash;
                   16351:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16352:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16353:         my $envname = 'environment.'.$basename;
1.258     albertel 16354:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16355:             # Save this value away
                   16356:             if ($type eq 'scalar' &&
1.258     albertel 16357:                 (! exists($env{$envname}) || 
                   16358:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16359:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16360:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16361:             } elsif ($type eq 'array') {
                   16362:                 my $stored_form;
1.258     albertel 16363:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16364:                     $stored_form = join(',',
                   16365:                                         map {
1.369     www      16366:                                             &escape($_);
1.258     albertel 16367:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16368:                 } else {
                   16369:                     $stored_form = 
1.369     www      16370:                         &escape($env{'form.'.$setting});
1.153     matthew  16371:                 }
                   16372:                 # Determine if the array contents are the same.
1.258     albertel 16373:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16374:                     $SaveHash{$basename} = $stored_form;
                   16375:                     $AppHash{$envname}   = $stored_form;
                   16376:                 }
                   16377:             }
                   16378:         }
                   16379:     }
                   16380:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16381:                                           $udom,$uname);
1.153     matthew  16382:     if ($put_result !~ /^(ok|delayed)/) {
                   16383:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16384:                                  'got error:'.$put_result);
                   16385:     }
                   16386:     # Make sure these settings stick around in this session, too
1.646     raeburn  16387:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16388:     return;
                   16389: }
                   16390: 
                   16391: sub restore_course_settings {
1.499     albertel 16392:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16393: }
                   16394: 
                   16395: sub restore_settings {
                   16396:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16397:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16398:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16399:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16400:             '.'.$setting;
1.258     albertel 16401:         if (exists($env{$envname})) {
1.153     matthew  16402:             if ($type eq 'scalar') {
1.258     albertel 16403:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16404:             } elsif ($type eq 'array') {
1.258     albertel 16405:                 $env{'form.'.$setting} = [ 
1.153     matthew  16406:                                            map { 
1.369     www      16407:                                                &unescape($_); 
1.258     albertel 16408:                                            } split(',',$env{$envname})
1.153     matthew  16409:                                            ];
                   16410:             }
                   16411:         }
                   16412:     }
1.127     matthew  16413: }
                   16414: 
1.618     raeburn  16415: #######################################################
                   16416: #######################################################
                   16417: 
                   16418: =pod
                   16419: 
                   16420: =head1 Domain E-mail Routines  
                   16421: 
                   16422: =over 4
                   16423: 
1.648     raeburn  16424: =item * &build_recipient_list()
1.618     raeburn  16425: 
1.1144    raeburn  16426: Build recipient lists for following types of e-mail:
1.766     raeburn  16427: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16428: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16429: module change checking, student/employee ID conflict checks, as
                   16430: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16431: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16432: 
                   16433: Inputs:
1.619     raeburn  16434: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16435: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16436: requestsmail, updatesmail, or idconflictsmail).
                   16437: 
1.619     raeburn  16438: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16439: 
1.619     raeburn  16440: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16441: i.e., predates configuration by DC via domainprefs.pm
                   16442: 
                   16443: $requname username of requester (if mailing type is helpdeskmail)
                   16444: 
                   16445: $requdom domain of requester (if mailing type is helpdeskmail)
                   16446: 
                   16447: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16448: 
1.618     raeburn  16449: 
1.655     raeburn  16450: Returns: comma separated list of addresses to which to send e-mail.
                   16451: 
                   16452: =back
1.618     raeburn  16453: 
                   16454: =cut
                   16455: 
                   16456: ############################################################
                   16457: ############################################################
                   16458: sub build_recipient_list {
1.1297    raeburn  16459:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16460:     my @recipients;
1.1270    raeburn  16461:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16462:     my %domconfig =
1.1270    raeburn  16463:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16464:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16465:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16466:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16467:                 my @contacts = ('adminemail','supportemail');
                   16468:                 foreach my $item (@contacts) {
                   16469:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16470:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16471:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16472:                             push(@recipients,$addr);
                   16473:                         }
1.619     raeburn  16474:                     }
1.1270    raeburn  16475:                 }
                   16476:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16477:                 if ($mailing eq 'helpdeskmail') {
                   16478:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16479:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16480:                         my @ok_bccs;
                   16481:                         foreach my $bcc (@bccs) {
                   16482:                             $bcc =~ s/^\s+//g;
                   16483:                             $bcc =~ s/\s+$//g;
                   16484:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16485:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16486:                                     push(@ok_bccs,$bcc);
                   16487:                                 }
                   16488:                             }
                   16489:                         }
                   16490:                         if (@ok_bccs > 0) {
                   16491:                             $allbcc = join(', ',@ok_bccs);
                   16492:                         }
                   16493:                     }
                   16494:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16495:                 }
                   16496:             }
1.766     raeburn  16497:         } elsif ($origmail ne '') {
1.1270    raeburn  16498:             $lastresort = $origmail;
1.618     raeburn  16499:         }
1.1297    raeburn  16500:         if ($mailing eq 'helpdeskmail') {
                   16501:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16502:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16503:                 my ($inststatus,$inststatus_checked);
                   16504:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16505:                     ($env{'user.domain'} ne 'public')) {
                   16506:                     $inststatus_checked = 1;
                   16507:                     $inststatus = $env{'environment.inststatus'};
                   16508:                 }
                   16509:                 unless ($inststatus_checked) {
                   16510:                     if (($requname ne '') && ($requdom ne '')) {
                   16511:                         if (($requname =~ /^$match_username$/) &&
                   16512:                             ($requdom =~ /^$match_domain$/) &&
                   16513:                             (&Apache::lonnet::domain($requdom))) {
                   16514:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16515:                                                                       $requdom);
                   16516:                             unless ($requhome eq 'no_host') {
                   16517:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16518:                                 $inststatus = $userenv{'inststatus'};
                   16519:                                 $inststatus_checked = 1;
                   16520:                             }
                   16521:                         }
                   16522:                     }
                   16523:                 }
                   16524:                 unless ($inststatus_checked) {
                   16525:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16526:                         my %srch = (srchby     => 'email',
                   16527:                                     srchdomain => $defdom,
                   16528:                                     srchterm   => $reqemail,
                   16529:                                     srchtype   => 'exact');
                   16530:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16531:                         foreach my $uname (keys(%srch_results)) {
                   16532:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16533:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16534:                                 $inststatus_checked = 1;
                   16535:                                 last;
                   16536:                             }
                   16537:                         }
                   16538:                         unless ($inststatus_checked) {
                   16539:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16540:                             if ($dirsrchres eq 'ok') {
                   16541:                                 foreach my $uname (keys(%srch_results)) {
                   16542:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16543:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16544:                                         $inststatus_checked = 1;
                   16545:                                         last;
                   16546:                                     }
                   16547:                                 }
                   16548:                             }
                   16549:                         }
                   16550:                     }
                   16551:                 }
                   16552:                 if ($inststatus ne '') {
                   16553:                     foreach my $status (split(/\:/,$inststatus)) {
                   16554:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16555:                             my @contacts = ('adminemail','supportemail');
                   16556:                             foreach my $item (@contacts) {
                   16557:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16558:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16559:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16560:                                         push(@recipients,$addr);
                   16561:                                     }
                   16562:                                 }
                   16563:                             }
                   16564:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16565:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16566:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16567:                                 my @ok_bccs;
                   16568:                                 foreach my $bcc (@bccs) {
                   16569:                                     $bcc =~ s/^\s+//g;
                   16570:                                     $bcc =~ s/\s+$//g;
                   16571:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16572:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16573:                                             push(@ok_bccs,$bcc);
                   16574:                                         }
                   16575:                                     }
                   16576:                                 }
                   16577:                                 if (@ok_bccs > 0) {
                   16578:                                     $allbcc = join(', ',@ok_bccs);
                   16579:                                 }
                   16580:                             }
                   16581:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16582:                             last;
                   16583:                         }
                   16584:                     }
                   16585:                 }
                   16586:             }
                   16587:         }
1.619     raeburn  16588:     } elsif ($origmail ne '') {
1.1270    raeburn  16589:         $lastresort = $origmail;
                   16590:     }
1.1297    raeburn  16591:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16592:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16593:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16594:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16595:             my %what = (
                   16596:                           perlvar => 1,
                   16597:                        );
                   16598:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16599:             if ($primary) {
                   16600:                 my $gotaddr;
                   16601:                 my ($result,$returnhash) =
                   16602:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16603:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16604:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16605:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16606:                         $gotaddr = 1;
                   16607:                     }
                   16608:                 }
                   16609:                 unless ($gotaddr) {
                   16610:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16611:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16612:                     unless ($uintdom eq $intdom) {
                   16613:                         my %domconfig =
                   16614:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16615:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16616:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16617:                                 my @contacts = ('adminemail','supportemail');
                   16618:                                 foreach my $item (@contacts) {
                   16619:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16620:                                         my $addr = $domconfig{'contacts'}{$item};
                   16621:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16622:                                             push(@recipients,$addr);
                   16623:                                         }
                   16624:                                     }
                   16625:                                 }
                   16626:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16627:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16628:                                 }
                   16629:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16630:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16631:                                     my @ok_bccs;
                   16632:                                     foreach my $bcc (@bccs) {
                   16633:                                         $bcc =~ s/^\s+//g;
                   16634:                                         $bcc =~ s/\s+$//g;
                   16635:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16636:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16637:                                                 push(@ok_bccs,$bcc);
                   16638:                                             }
                   16639:                                         }
                   16640:                                     }
                   16641:                                     if (@ok_bccs > 0) {
                   16642:                                         $allbcc = join(', ',@ok_bccs);
                   16643:                                     }
                   16644:                                 }
                   16645:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16646:                             }
                   16647:                         }
                   16648:                     }
                   16649:                 }
                   16650:             }
                   16651:         }
1.618     raeburn  16652:     }
1.688     raeburn  16653:     if (defined($defmail)) {
                   16654:         if ($defmail ne '') {
                   16655:             push(@recipients,$defmail);
                   16656:         }
1.618     raeburn  16657:     }
                   16658:     if ($otheremails) {
1.619     raeburn  16659:         my @others;
                   16660:         if ($otheremails =~ /,/) {
                   16661:             @others = split(/,/,$otheremails);
1.618     raeburn  16662:         } else {
1.619     raeburn  16663:             push(@others,$otheremails);
                   16664:         }
                   16665:         foreach my $addr (@others) {
                   16666:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16667:                 push(@recipients,$addr);
                   16668:             }
1.618     raeburn  16669:         }
                   16670:     }
1.1298    raeburn  16671:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16672:         if ((!@recipients) && ($lastresort ne '')) {
                   16673:             push(@recipients,$lastresort);
                   16674:         }
                   16675:     } elsif ($lastresort ne '') {
                   16676:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16677:             push(@recipients,$lastresort);
                   16678:         }
                   16679:     }
1.1271    raeburn  16680:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16681:     if (wantarray) {
                   16682:         return ($recipientlist,$allbcc,$addtext);
                   16683:     } else {
                   16684:         return $recipientlist;
                   16685:     }
1.618     raeburn  16686: }
                   16687: 
1.127     matthew  16688: ############################################################
                   16689: ############################################################
1.154     albertel 16690: 
1.655     raeburn  16691: =pod
                   16692: 
1.1224    musolffc 16693: =over 4
                   16694: 
1.1223    musolffc 16695: =item * &mime_email()
                   16696: 
                   16697: Sends an email with a possible attachment
                   16698: 
                   16699: Inputs:
                   16700: 
                   16701: =over 4
                   16702: 
                   16703: from -              Sender's email address
                   16704: 
1.1343    raeburn  16705: replyto -           Reply-To email address
                   16706: 
1.1223    musolffc 16707: to -                Email address of recipient
                   16708: 
                   16709: subject -           Subject of email
                   16710: 
                   16711: body -              Body of email
                   16712: 
                   16713: cc_string -         Carbon copy email address
                   16714: 
                   16715: bcc -               Blind carbon copy email address
                   16716: 
                   16717: attachment_path -   Path of file to be attached
                   16718: 
                   16719: file_name -         Name of file to be attached
                   16720: 
                   16721: attachment_text -   The body of an attachment of type "TEXT"
                   16722: 
                   16723: =back
                   16724: 
                   16725: =back
                   16726: 
                   16727: =cut
                   16728: 
                   16729: ############################################################
                   16730: ############################################################
                   16731: 
                   16732: sub mime_email {
1.1343    raeburn  16733:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16734:         $file_name,$attachment_text) = @_;
                   16735:  
1.1223    musolffc 16736:     my $msg = MIME::Lite->new(
                   16737:              From    => $from,
                   16738:              To      => $to,
                   16739:              Subject => $subject,
                   16740:              Type    =>'TEXT',
                   16741:              Data    => $body,
                   16742:              );
1.1343    raeburn  16743:     if ($replyto ne '') {
                   16744:         $msg->add("Reply-To" => $replyto);
                   16745:     }
1.1223    musolffc 16746:     if ($cc_string ne '') {
                   16747:         $msg->add("Cc" => $cc_string);
                   16748:     }
                   16749:     if ($bcc ne '') {
                   16750:         $msg->add("Bcc" => $bcc);
                   16751:     }
                   16752:     $msg->attr("content-type"         => "text/plain");
                   16753:     $msg->attr("content-type.charset" => "UTF-8");
                   16754:     # Attach file if given
                   16755:     if ($attachment_path) {
                   16756:         unless ($file_name) {
                   16757:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16758:         }
                   16759:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16760:         $msg->attach(Type     => $type,
                   16761:                      Path     => $attachment_path,
                   16762:                      Filename => $file_name
                   16763:                      );
                   16764:     # Otherwise attach text if given
                   16765:     } elsif ($attachment_text) {
                   16766:         $msg->attach(Type => 'TEXT',
                   16767:                      Data => $attachment_text);
                   16768:     }
                   16769:     # Send it
                   16770:     $msg->send('sendmail');
                   16771: }
                   16772: 
                   16773: ############################################################
                   16774: ############################################################
                   16775: 
                   16776: =pod
                   16777: 
1.655     raeburn  16778: =head1 Course Catalog Routines
                   16779: 
                   16780: =over 4
                   16781: 
                   16782: =item * &gather_categories()
                   16783: 
                   16784: Converts category definitions - keys of categories hash stored in  
                   16785: coursecategories in configuration.db on the primary library server in a 
                   16786: domain - to an array.  Also generates javascript and idx hash used to 
                   16787: generate Domain Coordinator interface for editing Course Categories.
                   16788: 
                   16789: Inputs:
1.663     raeburn  16790: 
1.655     raeburn  16791: categories (reference to hash of category definitions).
1.663     raeburn  16792: 
1.655     raeburn  16793: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16794:       categories and subcategories).
1.663     raeburn  16795: 
1.655     raeburn  16796: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16797:       editing Course Categories).
1.663     raeburn  16798: 
1.655     raeburn  16799: jsarray (reference to array of categories used to create Javascript arrays for
                   16800:          Domain Coordinator interface for editing Course Categories).
                   16801: 
                   16802: Returns: nothing
                   16803: 
                   16804: Side effects: populates cats, idx and jsarray. 
                   16805: 
                   16806: =cut
                   16807: 
                   16808: sub gather_categories {
                   16809:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16810:     my %counters;
                   16811:     my $num = 0;
                   16812:     foreach my $item (keys(%{$categories})) {
                   16813:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16814:         if ($container eq '' && $depth == 0) {
                   16815:             $cats->[$depth][$categories->{$item}] = $cat;
                   16816:         } else {
                   16817:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16818:         }
                   16819:         my ($escitem,$tail) = split(/:/,$item,2);
                   16820:         if ($counters{$tail} eq '') {
                   16821:             $counters{$tail} = $num;
                   16822:             $num ++;
                   16823:         }
                   16824:         if (ref($idx) eq 'HASH') {
                   16825:             $idx->{$item} = $counters{$tail};
                   16826:         }
                   16827:         if (ref($jsarray) eq 'ARRAY') {
                   16828:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16829:         }
                   16830:     }
                   16831:     return;
                   16832: }
                   16833: 
                   16834: =pod
                   16835: 
                   16836: =item * &extract_categories()
                   16837: 
                   16838: Used to generate breadcrumb trails for course categories.
                   16839: 
                   16840: Inputs:
1.663     raeburn  16841: 
1.655     raeburn  16842: categories (reference to hash of category definitions).
1.663     raeburn  16843: 
1.655     raeburn  16844: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16845:       categories and subcategories).
1.663     raeburn  16846: 
1.655     raeburn  16847: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16848: 
1.655     raeburn  16849: allitems (reference to hash - key is category key 
                   16850:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16851: 
1.655     raeburn  16852: idx (reference to hash of counters used in Domain Coordinator interface for
                   16853:       editing Course Categories).
1.663     raeburn  16854: 
1.655     raeburn  16855: jsarray (reference to array of categories used to create Javascript arrays for
                   16856:          Domain Coordinator interface for editing Course Categories).
                   16857: 
1.665     raeburn  16858: subcats (reference to hash of arrays containing all subcategories within each 
                   16859:          category, -recursive)
                   16860: 
1.1321    raeburn  16861: maxd (reference to hash used to hold max depth for all top-level categories).
                   16862: 
1.655     raeburn  16863: Returns: nothing
                   16864: 
                   16865: Side effects: populates trails and allitems hash references.
                   16866: 
                   16867: =cut
                   16868: 
                   16869: sub extract_categories {
1.1321    raeburn  16870:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16871:     if (ref($categories) eq 'HASH') {
                   16872:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16873:         if (ref($cats->[0]) eq 'ARRAY') {
                   16874:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16875:                 my $name = $cats->[0][$i];
                   16876:                 my $item = &escape($name).'::0';
                   16877:                 my $trailstr;
                   16878:                 if ($name eq 'instcode') {
                   16879:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16880:                 } elsif ($name eq 'communities') {
                   16881:                     $trailstr = &mt('Communities');
1.1239    raeburn  16882:                 } elsif ($name eq 'placement') {
                   16883:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16884:                 } else {
                   16885:                     $trailstr = $name;
                   16886:                 }
                   16887:                 if ($allitems->{$item} eq '') {
                   16888:                     push(@{$trails},$trailstr);
                   16889:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16890:                 }
                   16891:                 my @parents = ($name);
                   16892:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16893:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16894:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16895:                         if (ref($subcats) eq 'HASH') {
                   16896:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16897:                         }
1.1321    raeburn  16898:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16899:                     }
                   16900:                 } else {
                   16901:                     if (ref($subcats) eq 'HASH') {
                   16902:                         $subcats->{$item} = [];
1.655     raeburn  16903:                     }
1.1321    raeburn  16904:                     if (ref($maxd) eq 'HASH') {
                   16905:                         $maxd->{$name} = 1;
                   16906:                     }
1.655     raeburn  16907:                 }
                   16908:             }
                   16909:         }
                   16910:     }
                   16911:     return;
                   16912: }
                   16913: 
                   16914: =pod
                   16915: 
1.1162    raeburn  16916: =item * &recurse_categories()
1.655     raeburn  16917: 
                   16918: Recursively used to generate breadcrumb trails for course categories.
                   16919: 
                   16920: Inputs:
1.663     raeburn  16921: 
1.655     raeburn  16922: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16923:       categories and subcategories).
1.663     raeburn  16924: 
1.655     raeburn  16925: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16926: 
                   16927: category (current course category, for which breadcrumb trail is being generated).
                   16928: 
                   16929: trails (reference to array of breadcrumb trails for each category).
                   16930: 
1.655     raeburn  16931: allitems (reference to hash - key is category key
                   16932:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16933: 
1.655     raeburn  16934: parents (array containing containers directories for current category, 
                   16935:          back to top level). 
                   16936: 
                   16937: Returns: nothing
                   16938: 
                   16939: Side effects: populates trails and allitems hash references
                   16940: 
                   16941: =cut
                   16942: 
                   16943: sub recurse_categories {
1.1321    raeburn  16944:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16945:     my $shallower = $depth - 1;
                   16946:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16947:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16948:             my $name = $cats->[$depth]{$category}[$k];
                   16949:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16950:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16951:             if ($allitems->{$item} eq '') {
                   16952:                 push(@{$trails},$trailstr);
                   16953:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16954:             }
                   16955:             my $deeper = $depth+1;
                   16956:             push(@{$parents},$category);
1.665     raeburn  16957:             if (ref($subcats) eq 'HASH') {
                   16958:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16959:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16960:                     my $higher;
                   16961:                     if ($j > 0) {
                   16962:                         $higher = &escape($parents->[$j]).':'.
                   16963:                                   &escape($parents->[$j-1]).':'.$j;
                   16964:                     } else {
                   16965:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16966:                     }
                   16967:                     push(@{$subcats->{$higher}},$subcat);
                   16968:                 }
                   16969:             }
                   16970:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16971:                                 $subcats,$maxd);
1.655     raeburn  16972:             pop(@{$parents});
                   16973:         }
                   16974:     } else {
                   16975:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16976:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16977:         if ($allitems->{$item} eq '') {
                   16978:             push(@{$trails},$trailstr);
                   16979:             $allitems->{$item} = scalar(@{$trails})-1;
                   16980:         }
1.1321    raeburn  16981:         if (ref($maxd) eq 'HASH') {
                   16982:             if ($depth > $maxd->{$parents->[0]}) {
                   16983:                 $maxd->{$parents->[0]} = $depth;
                   16984:             }
                   16985:         }
1.655     raeburn  16986:     }
                   16987:     return;
                   16988: }
                   16989: 
1.663     raeburn  16990: =pod
                   16991: 
1.1162    raeburn  16992: =item * &assign_categories_table()
1.663     raeburn  16993: 
                   16994: Create a datatable for display of hierarchical categories in a domain,
                   16995: with checkboxes to allow a course to be categorized. 
                   16996: 
                   16997: Inputs:
                   16998: 
                   16999: cathash - reference to hash of categories defined for the domain (from
                   17000:           configuration.db)
                   17001: 
                   17002: currcat - scalar with an & separated list of categories assigned to a course. 
                   17003: 
1.919     raeburn  17004: type    - scalar contains course type (Course or Community).
                   17005: 
1.1260    raeburn  17006: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   17007:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   17008: 
1.663     raeburn  17009: Returns: $output (markup to be displayed) 
                   17010: 
                   17011: =cut
                   17012: 
                   17013: sub assign_categories_table {
1.1259    raeburn  17014:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  17015:     my $output;
                   17016:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  17017:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   17018:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  17019:         $maxdepth = scalar(@cats);
                   17020:         if (@cats > 0) {
                   17021:             my $itemcount = 0;
                   17022:             if (ref($cats[0]) eq 'ARRAY') {
                   17023:                 my @currcategories;
                   17024:                 if ($currcat ne '') {
                   17025:                     @currcategories = split('&',$currcat);
                   17026:                 }
1.919     raeburn  17027:                 my $table;
1.663     raeburn  17028:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   17029:                     my $parent = $cats[0][$i];
1.919     raeburn  17030:                     next if ($parent eq 'instcode');
                   17031:                     if ($type eq 'Community') {
                   17032:                         next unless ($parent eq 'communities');
1.1239    raeburn  17033:                     } elsif ($type eq 'Placement') {
                   17034:                         next unless ($parent eq 'placement');
1.919     raeburn  17035:                     } else {
1.1239    raeburn  17036:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  17037:                     }
1.663     raeburn  17038:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   17039:                     my $item = &escape($parent).'::0';
                   17040:                     my $checked = '';
                   17041:                     if (@currcategories > 0) {
                   17042:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   17043:                             $checked = ' checked="checked"';
1.663     raeburn  17044:                         }
                   17045:                     }
1.919     raeburn  17046:                     my $parent_title = $parent;
                   17047:                     if ($parent eq 'communities') {
                   17048:                         $parent_title = &mt('Communities');
1.1239    raeburn  17049:                     } elsif ($parent eq 'placement') {
                   17050:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  17051:                     }
                   17052:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   17053:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17054:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  17055:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  17056:                     my $depth = 1;
                   17057:                     push(@path,$parent);
1.1259    raeburn  17058:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  17059:                     pop(@path);
1.919     raeburn  17060:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  17061:                     $itemcount ++;
                   17062:                 }
1.919     raeburn  17063:                 if ($itemcount) {
                   17064:                     $output = &Apache::loncommon::start_data_table().
                   17065:                               $table.
                   17066:                               &Apache::loncommon::end_data_table();
                   17067:                 }
1.663     raeburn  17068:             }
                   17069:         }
                   17070:     }
                   17071:     return $output;
                   17072: }
                   17073: 
                   17074: =pod
                   17075: 
1.1162    raeburn  17076: =item * &assign_category_rows()
1.663     raeburn  17077: 
                   17078: Create a datatable row for display of nested categories in a domain,
                   17079: with checkboxes to allow a course to be categorized,called recursively.
                   17080: 
                   17081: Inputs:
                   17082: 
                   17083: itemcount - track row number for alternating colors
                   17084: 
                   17085: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   17086:       categories and subcategories.
                   17087: 
                   17088: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   17089: 
                   17090: parent - parent of current category item
                   17091: 
                   17092: path - Array containing all categories back up through the hierarchy from the
                   17093:        current category to the top level.
                   17094: 
                   17095: currcategories - reference to array of current categories assigned to the course
                   17096: 
1.1260    raeburn  17097: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   17098:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   17099: 
1.663     raeburn  17100: Returns: $output (markup to be displayed).
                   17101: 
                   17102: =cut
                   17103: 
                   17104: sub assign_category_rows {
1.1259    raeburn  17105:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  17106:     my ($text,$name,$item,$chgstr);
                   17107:     if (ref($cats) eq 'ARRAY') {
                   17108:         my $maxdepth = scalar(@{$cats});
                   17109:         if (ref($cats->[$depth]) eq 'HASH') {
                   17110:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   17111:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   17112:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  17113:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  17114:                 for (my $j=0; $j<$numchildren; $j++) {
                   17115:                     $name = $cats->[$depth]{$parent}[$j];
                   17116:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   17117:                     my $deeper = $depth+1;
                   17118:                     my $checked = '';
                   17119:                     if (ref($currcategories) eq 'ARRAY') {
                   17120:                         if (@{$currcategories} > 0) {
                   17121:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   17122:                                 $checked = ' checked="checked"';
1.663     raeburn  17123:                             }
                   17124:                         }
                   17125:                     }
1.664     raeburn  17126:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   17127:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  17128:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  17129:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   17130:                              '</td><td>';
1.663     raeburn  17131:                     if (ref($path) eq 'ARRAY') {
                   17132:                         push(@{$path},$name);
1.1259    raeburn  17133:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  17134:                         pop(@{$path});
                   17135:                     }
                   17136:                     $text .= '</td></tr>';
                   17137:                 }
                   17138:                 $text .= '</table></td>';
                   17139:             }
                   17140:         }
                   17141:     }
                   17142:     return $text;
                   17143: }
                   17144: 
1.1181    raeburn  17145: =pod
                   17146: 
                   17147: =back
                   17148: 
                   17149: =cut
                   17150: 
1.655     raeburn  17151: ############################################################
                   17152: ############################################################
                   17153: 
                   17154: 
1.443     albertel 17155: sub commit_customrole {
1.1408    raeburn  17156:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  17157:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  17158:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   17159:                      $context,$othdomby,$requester);
1.630     raeburn  17160:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 17161:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  17162:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   17163:     if (wantarray) {
                   17164:         return ($output,$result);
                   17165:     } else {
                   17166:         return $output;
                   17167:     }
1.443     albertel 17168: }
                   17169: 
                   17170: sub commit_standardrole {
1.1408    raeburn  17171:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17172:         $othdomby,$requester) = @_;
1.1399    raeburn  17173:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17174:     if ($context eq 'auto') {
                   17175:         $linefeed = "\n";
                   17176:     } else {
                   17177:         $linefeed = "<br />\n";
                   17178:     }  
1.443     albertel 17179:     if ($three eq 'st') {
1.1399    raeburn  17180:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17181:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17182:                                       $requester);
1.541     raeburn  17183:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17184:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17185:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17186:         } else {
1.541     raeburn  17187:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17188:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17189:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17190:             if ($context eq 'auto') {
                   17191:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17192:             } else {
                   17193:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17194:                &mt('Add to classlist').': <b>ok</b>';
                   17195:             }
                   17196:             $output .= $linefeed;
1.443     albertel 17197:         }
                   17198:     } else {
                   17199:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17200:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17201:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17202:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17203:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17204:         if ($context eq 'auto') {
                   17205:             $output .= $result.$linefeed;
                   17206:         } else {
                   17207:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17208:         }
1.443     albertel 17209:     }
1.1399    raeburn  17210:     if (wantarray) {
                   17211:         return ($output,$result);
                   17212:     } else {
                   17213:         return $output;
                   17214:     }
1.443     albertel 17215: }
                   17216: 
                   17217: sub commit_studentrole {
1.1116    raeburn  17218:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17219:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17220:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17221:     if ($context eq 'auto') {
                   17222:         $linefeed = "\n";
                   17223:     } else {
                   17224:         $linefeed = '<br />'."\n";
                   17225:     }
1.443     albertel 17226:     if (defined($one) && defined($two)) {
                   17227:         my $cid=$one.'_'.$two;
                   17228:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17229:         my $secchange = 0;
                   17230:         my $expire_role_result;
                   17231:         my $modify_section_result;
1.628     raeburn  17232:         if ($oldsec ne '-1') { 
                   17233:             if ($oldsec ne $sec) {
1.443     albertel 17234:                 $secchange = 1;
1.628     raeburn  17235:                 my $now = time;
1.443     albertel 17236:                 my $uurl='/'.$cid;
                   17237:                 $uurl=~s/\_/\//g;
                   17238:                 if ($oldsec) {
                   17239:                     $uurl.='/'.$oldsec;
                   17240:                 }
1.626     raeburn  17241:                 $oldsecurl = $uurl;
1.628     raeburn  17242:                 $expire_role_result = 
1.1408    raeburn  17243:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17244:                                                 '','','',$context,$othdomby,$requester);
                   17245:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17246:                     if ($expire_role_result eq 'refused') {
                   17247:                         my @roles = ('st');
                   17248:                         my @statuses = ('previous');
                   17249:                         my @roledoms = ($one);
                   17250:                         my $withsec = 1;
                   17251:                         my %roleshash = 
                   17252:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17253:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17254:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17255:                             my ($oldstart,$oldend) = 
                   17256:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17257:                             if ($oldend > 0 && $oldend <= $now) {
                   17258:                                 $expire_role_result = 'ok';
                   17259:                             }
                   17260:                         }
                   17261:                     }
                   17262:                 }
1.443     albertel 17263:                 $result = $expire_role_result;
                   17264:             }
                   17265:         }
                   17266:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17267:             $modify_section_result = 
                   17268:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17269:                                                            undef,undef,undef,$sec,
                   17270:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17271:                                                            '',$context,$credits,'',
                   17272:                                                            $othdomby,$requester);
1.443     albertel 17273:             if ($modify_section_result =~ /^ok/) {
                   17274:                 if ($secchange == 1) {
1.628     raeburn  17275:                     if ($sec eq '') {
                   17276:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17277:                     } else {
                   17278:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17279:                     }
1.443     albertel 17280:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17281:                     if ($sec eq '') {
                   17282:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17283:                     } else {
                   17284:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17285:                     }
1.443     albertel 17286:                 } else {
1.628     raeburn  17287:                     if ($sec eq '') {
                   17288:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17289:                     } else {
                   17290:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17291:                     }
1.443     albertel 17292:                 }
                   17293:             } else {
1.1115    raeburn  17294:                 if ($secchange) { 
1.628     raeburn  17295:                     $$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;
                   17296:                 } else {
                   17297:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17298:                 }
1.443     albertel 17299:             }
                   17300:             $result = $modify_section_result;
                   17301:         } elsif ($secchange == 1) {
1.628     raeburn  17302:             if ($oldsec eq '') {
1.1103    raeburn  17303:                 $$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  17304:             } else {
                   17305:                 $$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;
                   17306:             }
1.626     raeburn  17307:             if ($expire_role_result eq 'refused') {
                   17308:                 my $newsecurl = '/'.$cid;
                   17309:                 $newsecurl =~ s/\_/\//g;
                   17310:                 if ($sec ne '') {
                   17311:                     $newsecurl.='/'.$sec;
                   17312:                 }
                   17313:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17314:                     if ($sec eq '') {
                   17315:                         $$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;
                   17316:                     } else {
                   17317:                         $$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;
                   17318:                     }
                   17319:                 }
                   17320:             }
1.443     albertel 17321:         }
                   17322:     } else {
1.626     raeburn  17323:         $$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 17324:         $result = "error: incomplete course id\n";
                   17325:     }
                   17326:     return $result;
                   17327: }
                   17328: 
1.1108    raeburn  17329: sub show_role_extent {
                   17330:     my ($scope,$context,$role) = @_;
                   17331:     $scope =~ s{^/}{};
                   17332:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17333:     push(@courseroles,'co');
                   17334:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17335:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17336:         $scope =~ s{/}{_};
                   17337:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17338:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17339:         my ($audom,$auname) = split(/\//,$scope);
                   17340:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17341:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17342:     } else {
                   17343:         $scope =~ s{/$}{};
                   17344:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17345:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17346:     }
                   17347: }
                   17348: 
1.443     albertel 17349: ############################################################
                   17350: ############################################################
                   17351: 
1.566     albertel 17352: sub check_clone {
1.578     raeburn  17353:     my ($args,$linefeed) = @_;
1.566     albertel 17354:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17355:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17356:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17357:     my $clonetitle;
                   17358:     my @clonemsg;
1.566     albertel 17359:     my $can_clone = 0;
1.944     raeburn  17360:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17361:     if ($lctype ne 'community') {
                   17362:         $lctype = 'course';
                   17363:     }
1.566     albertel 17364:     if ($clonehome eq 'no_host') {
1.944     raeburn  17365:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17366:             push(@clonemsg,({
                   17367:                               mt => 'No new community created.',
                   17368:                               args => [],
                   17369:                             },
                   17370:                             {
                   17371:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17372:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17373:                             }));
1.908     raeburn  17374:         } else {
1.1344    raeburn  17375:             push(@clonemsg,({
                   17376:                               mt => 'No new course created.',
                   17377:                               args => [],
                   17378:                             },
                   17379:                             {
                   17380:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17381:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17382:                             }));
                   17383:         }
1.566     albertel 17384:     } else {
                   17385: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17386:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17387:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17388:             if ($clonedesc{'type'} ne '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 course not a community.',
                   17395:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17396:                                 }));
                   17397:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17398:             }
                   17399:         }
1.1262    raeburn  17400: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17401:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17402: 	    $can_clone = 1;
                   17403: 	} else {
1.1221    raeburn  17404: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17405: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17406:             if ($clonehash{'cloners'} eq '') {
                   17407:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17408:                 if ($domdefs{'canclone'}) {
                   17409:                     unless ($domdefs{'canclone'} eq 'none') {
                   17410:                         if ($domdefs{'canclone'} eq 'domain') {
                   17411:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17412:                                 $can_clone = 1;
                   17413:                             }
                   17414:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17415:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17416:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17417:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17418:                                 $can_clone = 1;
                   17419:                             }
                   17420:                         }
                   17421:                     }
                   17422:                 }
1.578     raeburn  17423:             } else {
1.1221    raeburn  17424: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17425:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17426:                     $can_clone = 1;
1.1221    raeburn  17427:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17428:                     $can_clone = 1;
1.1225    raeburn  17429:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17430:                     $can_clone = 1;
1.1221    raeburn  17431:                 }
                   17432:                 unless ($can_clone) {
1.1225    raeburn  17433:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17434:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17435:                         my (%gotdomdefaults,%gotcodedefaults);
                   17436:                         foreach my $cloner (@cloners) {
                   17437:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17438:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17439:                                 my (%codedefaults,@code_order);
                   17440:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17441:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17442:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17443:                                     }
                   17444:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17445:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17446:                                     }
                   17447:                                 } else {
                   17448:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17449:                                                                             \%codedefaults,
                   17450:                                                                             \@code_order);
                   17451:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17452:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17453:                                 }
                   17454:                                 if (@code_order > 0) {
                   17455:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17456:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17457:                                                                                 $args->{'crscode'})) {
                   17458:                                         $can_clone = 1;
                   17459:                                         last;
                   17460:                                     }
                   17461:                                 }
                   17462:                             }
                   17463:                         }
                   17464:                     }
1.1225    raeburn  17465:                 }
                   17466:             }
                   17467:             unless ($can_clone) {
                   17468:                 my $ccrole = 'cc';
                   17469:                 if ($args->{'crstype'} eq 'Community') {
                   17470:                     $ccrole = 'co';
                   17471:                 }
                   17472: 	        my %roleshash =
                   17473: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17474: 					          $args->{'ccdomain'},
                   17475:                                                   'userroles',['active'],[$ccrole],
                   17476: 					          [$args->{'clonedomain'}]);
                   17477: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17478:                     $can_clone = 1;
                   17479:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17480:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17481:                     $can_clone = 1;
1.1221    raeburn  17482:                 }
                   17483:             }
                   17484:             unless ($can_clone) {
                   17485:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17486:                     push(@clonemsg,({
                   17487:                                       mt => 'No new community created.',
                   17488:                                       args => [],
                   17489:                                     },
                   17490:                                     {
                   17491:                                       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]).',
                   17492:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17493:                                     }));
1.942     raeburn  17494:                 } else {
1.1344    raeburn  17495:                     push(@clonemsg,({
                   17496:                                       mt => 'No new course created.',
                   17497:                                       args => [],
                   17498:                                     },
                   17499:                                     {
                   17500:                                       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]).',
                   17501:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17502:                                     }));
1.1221    raeburn  17503:                 }
1.566     albertel 17504: 	    }
1.578     raeburn  17505:         }
1.566     albertel 17506:     }
1.1344    raeburn  17507:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17508: }
                   17509: 
1.444     albertel 17510: sub construct_course {
1.1262    raeburn  17511:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17512:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17513:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17514:     my $linefeed =  '<br />'."\n";
                   17515:     if ($context eq 'auto') {
                   17516:         $linefeed = "\n";
                   17517:     }
1.566     albertel 17518: 
                   17519: #
                   17520: # Are we cloning?
                   17521: #
1.1344    raeburn  17522:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17523:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17524: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17525:         if (!$can_clone) {
1.1344    raeburn  17526: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17527: 	}
                   17528:     }
                   17529: 
1.444     albertel 17530: #
                   17531: # Open course
                   17532: #
1.1239    raeburn  17533:     my $showncrstype;
                   17534:     if ($args->{'crstype'} eq 'Placement') {
                   17535:         $showncrstype = 'placement test'; 
                   17536:     } else {  
                   17537:         $showncrstype = lc($args->{'crstype'});
                   17538:     }
1.444     albertel 17539:     my %cenv=();
                   17540:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17541:                                              $args->{'cdescr'},
                   17542:                                              $args->{'curl'},
                   17543:                                              $args->{'course_home'},
                   17544:                                              $args->{'nonstandard'},
                   17545:                                              $args->{'crscode'},
                   17546:                                              $args->{'ccuname'}.':'.
                   17547:                                              $args->{'ccdomain'},
1.882     raeburn  17548:                                              $args->{'crstype'},
1.1344    raeburn  17549:                                              $cnum,$context,$category,
                   17550:                                              $callercontext);
1.444     albertel 17551: 
                   17552:     # Note: The testing routines depend on this being output; see 
                   17553:     # Utils::Course. This needs to at least be output as a comment
                   17554:     # if anyone ever decides to not show this, and Utils::Course::new
                   17555:     # will need to be suitably modified.
1.1344    raeburn  17556:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17557:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17558:     } else {
                   17559:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17560:     }
1.943     raeburn  17561:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17562:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17563:     }
                   17564: 
1.444     albertel 17565: #
                   17566: # Check if created correctly
                   17567: #
1.479     albertel 17568:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17569:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17570:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17571:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17572:             $outcome .= &mt_user($user_lh,
                   17573:                             'Course creation failed, unrecognized course home server.');
                   17574:         } else {
                   17575:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17576:         }
                   17577:         $outcome .= $linefeed;
                   17578:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17579:     }
1.541     raeburn  17580:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17581: 
1.444     albertel 17582: #
1.566     albertel 17583: # Do the cloning
                   17584: #   
1.1344    raeburn  17585:     my @clonemsg;
1.566     albertel 17586:     if ($can_clone && $cloneid) {
1.1344    raeburn  17587:         push(@clonemsg,
                   17588:                       {
                   17589:                           mt => 'Created [_1] by cloning from [_2]',
                   17590:                           args => [$showncrstype,$clonetitle],
                   17591:                       });
1.566     albertel 17592: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17593: # Copy all files
1.1344    raeburn  17594:         my @info =
                   17595: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17596: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17597:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17598:                                                      $args->{'tinyurls'});
                   17599:         if (@info) {
                   17600:             push(@clonemsg,@info);
                   17601:         }
1.444     albertel 17602: # Restore URL
1.566     albertel 17603: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17604: # Restore title
1.566     albertel 17605: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17606: # Restore creation date, creator and creation context.
                   17607:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17608:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17609:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17610: # Mark as cloned
1.566     albertel 17611: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17612: # Need to clone grading mode
                   17613:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17614:         $cenv{'grading'}=$newenv{'grading'};
                   17615: # Do not clone these environment entries
                   17616:         &Apache::lonnet::del('environment',
                   17617:                   ['default_enrollment_start_date',
                   17618:                    'default_enrollment_end_date',
                   17619:                    'question.email',
                   17620:                    'policy.email',
                   17621:                    'comment.email',
                   17622:                    'pch.users.denied',
1.725     raeburn  17623:                    'plc.users.denied',
                   17624:                    'hidefromcat',
1.1121    raeburn  17625:                    'checkforpriv',
1.1355    raeburn  17626:                    'categories'],
1.638     www      17627:                    $$crsudom,$$crsunum);
1.1170    raeburn  17628:         if ($args->{'textbook'}) {
                   17629:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17630:         }
1.444     albertel 17631:     }
1.566     albertel 17632: 
1.444     albertel 17633: #
                   17634: # Set environment (will override cloned, if existing)
                   17635: #
                   17636:     my @sections = ();
                   17637:     my @xlists = ();
                   17638:     if ($args->{'crstype'}) {
                   17639:         $cenv{'type'}=$args->{'crstype'};
                   17640:     }
1.1371    raeburn  17641:     if ($args->{'lti'}) {
                   17642:         $cenv{'internal.lti'}=$args->{'lti'};
                   17643:     }
1.444     albertel 17644:     if ($args->{'crsid'}) {
                   17645:         $cenv{'courseid'}=$args->{'crsid'};
                   17646:     }
                   17647:     if ($args->{'crscode'}) {
                   17648:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17649:     }
                   17650:     if ($args->{'crsquota'} ne '') {
                   17651:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17652:     } else {
                   17653:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17654:     }
                   17655:     if ($args->{'ccuname'}) {
                   17656:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17657:                                         ':'.$args->{'ccdomain'};
                   17658:     } else {
                   17659:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17660:     }
1.1116    raeburn  17661:     if ($args->{'defaultcredits'}) {
                   17662:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17663:     }
1.444     albertel 17664:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17665:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17666:     if ($args->{'crssections'}) {
                   17667:         $cenv{'internal.sectionnums'} = '';
                   17668:         if ($args->{'crssections'} =~ m/,/) {
                   17669:             @sections = split/,/,$args->{'crssections'};
                   17670:         } else {
                   17671:             $sections[0] = $args->{'crssections'};
                   17672:         }
                   17673:         if (@sections > 0) {
                   17674:             foreach my $item (@sections) {
                   17675:                 my ($sec,$gp) = split/:/,$item;
                   17676:                 my $class = $args->{'crscode'}.$sec;
                   17677:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17678:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17679:                 if ($addcheck eq 'ok') {
                   17680:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17681:                         push(@oklcsecs,$gp);
                   17682:                     }
                   17683:                 } else {
1.1263    raeburn  17684:                     push(@badclasses,$class);
1.444     albertel 17685:                 }
                   17686:             }
                   17687:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17688:         }
                   17689:     }
                   17690: # do not hide course coordinator from staff listing, 
                   17691: # even if privileged
                   17692:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17693: # add course coordinator's domain to domains to check for privileged users
                   17694: # if different to course domain
                   17695:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17696:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17697:     }
1.444     albertel 17698: # add crosslistings
                   17699:     if ($args->{'crsxlist'}) {
                   17700:         $cenv{'internal.crosslistings'}='';
                   17701:         if ($args->{'crsxlist'} =~ m/,/) {
                   17702:             @xlists = split/,/,$args->{'crsxlist'};
                   17703:         } else {
                   17704:             $xlists[0] = $args->{'crsxlist'};
                   17705:         }
                   17706:         if (@xlists > 0) {
                   17707:             foreach my $item (@xlists) {
                   17708:                 my ($xl,$gp) = split/:/,$item;
                   17709:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17710:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17711:                 if ($addcheck eq 'ok') {
                   17712:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17713:                         push(@oklcsecs,$gp);
                   17714:                     }
                   17715:                 } else {
1.1263    raeburn  17716:                     push(@badclasses,$xl);
1.444     albertel 17717:                 }
                   17718:             }
                   17719:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17720:         }
                   17721:     }
                   17722:     if ($args->{'autoadds'}) {
                   17723:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17724:     }
                   17725:     if ($args->{'autodrops'}) {
                   17726:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17727:     }
                   17728: # check for notification of enrollment changes
                   17729:     my @notified = ();
                   17730:     if ($args->{'notify_owner'}) {
                   17731:         if ($args->{'ccuname'} ne '') {
                   17732:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17733:         }
                   17734:     }
                   17735:     if ($args->{'notify_dc'}) {
                   17736:         if ($uname ne '') { 
1.630     raeburn  17737:             push(@notified,$uname.':'.$udom);
1.444     albertel 17738:         }
                   17739:     }
                   17740:     if (@notified > 0) {
                   17741:         my $notifylist;
                   17742:         if (@notified > 1) {
                   17743:             $notifylist = join(',',@notified);
                   17744:         } else {
                   17745:             $notifylist = $notified[0];
                   17746:         }
                   17747:         $cenv{'internal.notifylist'} = $notifylist;
                   17748:     }
                   17749:     if (@badclasses > 0) {
                   17750:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17751:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17752:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17753:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17754:         );
1.1264    raeburn  17755:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17756:                            &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  17757:         if ($context eq 'auto') {
                   17758:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17759:         } else {
1.566     albertel 17760:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17761:         }
                   17762:         foreach my $item (@badclasses) {
1.541     raeburn  17763:             if ($context eq 'auto') {
1.1261    raeburn  17764:                 $outcome .= " - $item\n";
1.541     raeburn  17765:             } else {
1.1261    raeburn  17766:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17767:             }
1.1261    raeburn  17768:         }
                   17769:         if ($context eq 'auto') {
                   17770:             $outcome .= $linefeed;
                   17771:         } else {
                   17772:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17773:         } 
1.444     albertel 17774:     }
                   17775:     if ($args->{'no_end_date'}) {
                   17776:         $args->{'endaccess'} = 0;
                   17777:     }
1.1412    raeburn  17778: #  If an official course with institutional sections is created by cloning 
                   17779: #  an existing course, section-specific hiding of course totals in student's
                   17780: #  view of grades as copied from cloned course, will be checked for valid 
                   17781: #  sections.
                   17782:     if (($can_clone && $cloneid) &&
                   17783:         ($cenv{'internal.coursecode'} ne '') &&
                   17784:         ($cenv{'grading'} eq 'standard') &&
                   17785:         ($cenv{'hidetotals'} ne '') &&
                   17786:         ($cenv{'hidetotals'} ne 'all')) {
                   17787:         my @hidesecs;
                   17788:         my $deletehidetotals;
                   17789:         if (@oklcsecs) {
                   17790:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17791:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17792:                     push(@hidesecs,$sec);
                   17793:                 }
                   17794:             }
                   17795:             if (@hidesecs) {
                   17796:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17797:             } else {
                   17798:                 $deletehidetotals = 1;
                   17799:             }
                   17800:         } else {
                   17801:             $deletehidetotals = 1;
                   17802:         }
                   17803:         if ($deletehidetotals) {
                   17804:             delete($cenv{'hidetotals'});
                   17805:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17806:         }
                   17807:     }
1.444     albertel 17808:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17809:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17810:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17811:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17812:     if ($args->{'showphotos'}) {
                   17813:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17814:     }
                   17815:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17816:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17817:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17818:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17819:             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'); 
                   17820:             if ($context eq 'auto') {
                   17821:                 $outcome .= $krb_msg;
                   17822:             } else {
1.566     albertel 17823:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17824:             }
                   17825:             $outcome .= $linefeed;
1.444     albertel 17826:         }
                   17827:     }
                   17828:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17829:        if ($args->{'setpolicy'}) {
                   17830:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17831:        }
                   17832:        if ($args->{'setcontent'}) {
                   17833:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17834:        }
1.1251    raeburn  17835:        if ($args->{'setcomment'}) {
                   17836:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17837:        }
1.444     albertel 17838:     }
                   17839:     if ($args->{'reshome'}) {
                   17840: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17841: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17842:     }
                   17843: #
                   17844: # course has keyed access
                   17845: #
                   17846:     if ($args->{'setkeys'}) {
                   17847:        $cenv{'keyaccess'}='yes';
                   17848:     }
                   17849: # if specified, key authority is not course, but user
                   17850: # only active if keyaccess is yes
                   17851:     if ($args->{'keyauth'}) {
1.487     albertel 17852: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17853: 	$user = &LONCAPA::clean_username($user);
                   17854: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17855: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17856: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17857: 	}
                   17858:     }
                   17859: 
1.1166    raeburn  17860: #
1.1167    raeburn  17861: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17862: #
                   17863:     if ($args->{'uniquecode'}) {
                   17864:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17865:         if ($code) {
                   17866:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17867:             my %crsinfo =
                   17868:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17869:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17870:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17871:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17872:             } 
1.1166    raeburn  17873:             if (ref($coderef)) {
                   17874:                 $$coderef = $code;
                   17875:             }
                   17876:         }
                   17877:     }
                   17878: 
1.444     albertel 17879:     if ($args->{'disresdis'}) {
                   17880:         $cenv{'pch.roles.denied'}='st';
                   17881:     }
                   17882:     if ($args->{'disablechat'}) {
                   17883:         $cenv{'plc.roles.denied'}='st';
                   17884:     }
                   17885: 
                   17886:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17887:     # course
                   17888:     $cenv{'course.helper.not.run'} = 1;
                   17889:     #
                   17890:     # Use new Randomseed
                   17891:     #
                   17892:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17893:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17894:     #
                   17895:     # The encryption code and receipt prefix for this course
                   17896:     #
                   17897:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17898:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17899:     #
                   17900:     # By default, use standard grading
                   17901:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17902: 
1.541     raeburn  17903:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17904:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17905: #
                   17906: # Open all assignments
                   17907: #
                   17908:     if ($args->{'openall'}) {
1.1341    raeburn  17909:        my $opendate = time;
                   17910:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17911:            $opendate = $args->{'openallfrom'};
                   17912:        }
1.444     albertel 17913:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17914:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17915:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17916:        $outcome .= &mt('All assignments open starting [_1]',
                   17917:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17918:                    &Apache::lonnet::cput
                   17919:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17920:    }
                   17921: #
                   17922: # Set first page
                   17923: #
                   17924:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17925: 	    || ($cloneid)) {
                   17926: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17927: 
                   17928: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17929:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17930: 
1.444     albertel 17931:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17932:         my $title; my $url;
                   17933:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17934: 	    $title=&mt('Syllabus');
1.444     albertel 17935:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17936:         } else {
1.963     raeburn  17937:             $title=&mt('Table of Contents');
1.444     albertel 17938:             $url='/adm/navmaps';
                   17939:         }
1.445     albertel 17940: 
                   17941:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17942: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17943: 
                   17944: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17945:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17946:     }
1.566     albertel 17947: 
1.1237    raeburn  17948: # 
                   17949: # Set params for Placement Tests
                   17950: #
1.1239    raeburn  17951:     if ($args->{'crstype'} eq 'Placement') {
                   17952:        my %storecontent; 
                   17953:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17954:        my %defaults = (
                   17955:                         buttonshide   => { value => 'yes',
                   17956:                                            type => 'string_yesno',},
                   17957:                         type          => { value => 'randomizetry',
                   17958:                                            type  => 'string_questiontype',},
                   17959:                         maxtries      => { value => 1,
                   17960:                                            type => 'int_pos',},
                   17961:                         problemstatus => { value => 'no',
                   17962:                                            type  => 'string_problemstatus',},
                   17963:                       );
                   17964:        foreach my $key (keys(%defaults)) {
                   17965:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17966:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17967:        }
1.1237    raeburn  17968:        &Apache::lonnet::cput
                   17969:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17970:     }
                   17971: 
1.1344    raeburn  17972:     return (1,$outcome,\@clonemsg);
1.444     albertel 17973: }
                   17974: 
1.1166    raeburn  17975: sub make_unique_code {
                   17976:     my ($cdom,$cnum) = @_;
                   17977:     # get lock on uniquecodes db
                   17978:     my $lockhash = {
                   17979:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17980:                                                   ':'.$env{'user.domain'},
                   17981:                    };
                   17982:     my $tries = 0;
                   17983:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17984:     my ($code,$error);
                   17985:   
                   17986:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17987:         $tries ++;
                   17988:         sleep 1;
                   17989:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17990:     }
                   17991:     if ($gotlock eq 'ok') {
                   17992:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17993:         my $gotcode;
                   17994:         my $attempts = 0;
                   17995:         while ((!$gotcode) && ($attempts < 100)) {
                   17996:             $code = &generate_code();
                   17997:             if (!exists($currcodes{$code})) {
                   17998:                 $gotcode = 1;
                   17999:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   18000:                     $error = 'nostore';
                   18001:                 }
                   18002:             }
                   18003:             $attempts ++;
                   18004:         }
                   18005:         my @del_lock = ($cnum."\0".'uniquecodes');
                   18006:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   18007:     } else {
                   18008:         $error = 'nolock';
                   18009:     }
                   18010:     return ($code,$error);
                   18011: }
                   18012: 
                   18013: sub generate_code {
                   18014:     my $code;
                   18015:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   18016:     for (my $i=0; $i<6; $i++) {
                   18017:         my $lettnum = int (rand 2);
                   18018:         my $item = '';
                   18019:         if ($lettnum) {
                   18020:             $item = $letts[int( rand(18) )];
                   18021:         } else {
                   18022:             $item = 1+int( rand(8) );
                   18023:         }
                   18024:         $code .= $item;
                   18025:     }
                   18026:     return $code;
                   18027: }
                   18028: 
1.444     albertel 18029: ############################################################
                   18030: ############################################################
                   18031: 
1.1237    raeburn  18032: # Community, Course and Placement Test
1.378     raeburn  18033: sub course_type {
                   18034:     my ($cid) = @_;
                   18035:     if (!defined($cid)) {
                   18036:         $cid = $env{'request.course.id'};
                   18037:     }
1.404     albertel 18038:     if (defined($env{'course.'.$cid.'.type'})) {
                   18039:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  18040:     } else {
                   18041:         return 'Course';
1.377     raeburn  18042:     }
                   18043: }
1.156     albertel 18044: 
1.406     raeburn  18045: sub group_term {
                   18046:     my $crstype = &course_type();
                   18047:     my %names = (
                   18048:                   'Course' => 'group',
1.865     raeburn  18049:                   'Community' => 'group',
1.1237    raeburn  18050:                   'Placement' => 'group',
1.406     raeburn  18051:                 );
                   18052:     return $names{$crstype};
                   18053: }
                   18054: 
1.902     raeburn  18055: sub course_types {
1.1310    raeburn  18056:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  18057:     my %typename = (
                   18058:                          official   => 'Official course',
                   18059:                          unofficial => 'Unofficial course',
                   18060:                          community  => 'Community',
1.1165    raeburn  18061:                          textbook   => 'Textbook course',
1.1237    raeburn  18062:                          placement  => 'Placement test',
1.1310    raeburn  18063:                          lti        => 'LTI provider',
1.902     raeburn  18064:                    );
                   18065:     return (\@types,\%typename);
                   18066: }
                   18067: 
1.156     albertel 18068: sub icon {
                   18069:     my ($file)=@_;
1.505     albertel 18070:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 18071:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 18072:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 18073:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   18074: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   18075: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18076: 	            $curfext.".gif") {
                   18077: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   18078: 		$curfext.".gif";
                   18079: 	}
                   18080:     }
1.249     albertel 18081:     return &lonhttpdurl($iconname);
1.154     albertel 18082: } 
1.84      albertel 18083: 
1.575     albertel 18084: sub lonhttpdurl {
1.692     www      18085: #
                   18086: # Had been used for "small fry" static images on separate port 8080.
                   18087: # Modify here if lightweight http functionality desired again.
                   18088: # Currently eliminated due to increasing firewall issues.
                   18089: #
1.575     albertel 18090:     my ($url)=@_;
1.692     www      18091:     return $url;
1.215     albertel 18092: }
                   18093: 
1.213     albertel 18094: sub connection_aborted {
                   18095:     my ($r)=@_;
                   18096:     $r->print(" ");$r->rflush();
                   18097:     my $c = $r->connection;
                   18098:     return $c->aborted();
                   18099: }
                   18100: 
1.221     foxr     18101: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     18102: #    strings as 'strings'.
                   18103: sub escape_single {
1.221     foxr     18104:     my ($input) = @_;
1.223     albertel 18105:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     18106:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   18107:     return $input;
                   18108: }
1.223     albertel 18109: 
1.222     foxr     18110: #  Same as escape_single, but escape's "'s  This 
                   18111: #  can be used for  "strings"
                   18112: sub escape_double {
                   18113:     my ($input) = @_;
                   18114:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   18115:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   18116:     return $input;
                   18117: }
1.223     albertel 18118:  
1.222     foxr     18119: #   Escapes the last element of a full URL.
                   18120: sub escape_url {
                   18121:     my ($url)   = @_;
1.238     raeburn  18122:     my @urlslices = split(/\//, $url,-1);
1.369     www      18123:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  18124:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     18125: }
1.462     albertel 18126: 
1.820     raeburn  18127: sub compare_arrays {
                   18128:     my ($arrayref1,$arrayref2) = @_;
                   18129:     my (@difference,%count);
                   18130:     @difference = ();
                   18131:     %count = ();
                   18132:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   18133:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   18134:         foreach my $element (keys(%count)) {
                   18135:             if ($count{$element} == 1) {
                   18136:                 push(@difference,$element);
                   18137:             }
                   18138:         }
                   18139:     }
                   18140:     return @difference;
                   18141: }
                   18142: 
1.1322    raeburn  18143: sub lon_status_items {
                   18144:     my %defaults = (
                   18145:                      E         => 100,
                   18146:                      W         => 4,
                   18147:                      N         => 1,
1.1324    raeburn  18148:                      U         => 5,
1.1322    raeburn  18149:                      threshold => 200,
                   18150:                      sysmail   => 2500,
                   18151:                    );
                   18152:     my %names = (
                   18153:                    E => 'Errors',
                   18154:                    W => 'Warnings',
                   18155:                    N => 'Notices',
1.1324    raeburn  18156:                    U => 'Unsent',
1.1322    raeburn  18157:                 );
                   18158:     return (\%defaults,\%names);
                   18159: }
                   18160: 
1.817     bisitz   18161: # -------------------------------------------------------- Initialize user login
1.462     albertel 18162: sub init_user_environment {
1.463     albertel 18163:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 18164:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   18165: 
                   18166:     my $public=($username eq 'public' && $domain eq 'public');
                   18167: 
1.1415    raeburn  18168:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   18169:         $coauthorenv);
1.462     albertel 18170:     my $now=time;
                   18171: 
                   18172:     if ($public) {
                   18173: 	my $max_public=100;
                   18174: 	my $oldest;
                   18175: 	my $oldest_time=0;
                   18176: 	for(my $next=1;$next<=$max_public;$next++) {
                   18177: 	    if (-e $lonids."/publicuser_$next.id") {
                   18178: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18179: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18180: 		    $oldest_time=$mtime;
                   18181: 		    $oldest=$next;
                   18182: 		}
                   18183: 	    } else {
                   18184: 		$cookie="publicuser_$next";
                   18185: 		last;
                   18186: 	    }
                   18187: 	}
                   18188: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18189:     } else {
1.1275    raeburn  18190: 	# See if old ID present, if so, remove if this isn't a robot,
                   18191: 	# killing any existing non-robot sessions
1.463     albertel 18192: 	if (!$args->{'robot'}) {
                   18193: 	    opendir(DIR,$lonids);
                   18194: 	    while ($filename=readdir(DIR)) {
                   18195: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18196:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18197:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18198:                         my $linkedfile;
1.1320    raeburn  18199:                         if (exists($oldenv{'user.linkedenv'})) {
                   18200:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18201:                         }
1.1320    raeburn  18202:                         untie(%oldenv);
                   18203:                         if (unlink("$lonids/$filename")) {
                   18204:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18205:                                 if (-l "$lonids/$linkedfile.id") {
                   18206:                                     unlink("$lonids/$linkedfile.id");
                   18207:                                 }
1.1295    raeburn  18208:                             }
                   18209:                         }
                   18210:                     } else {
                   18211:                         unlink($lonids.'/'.$filename);
                   18212:                     }
1.463     albertel 18213: 		}
1.462     albertel 18214: 	    }
1.463     albertel 18215: 	    closedir(DIR);
1.1204    raeburn  18216: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18217:             my $namespace = 'nohist_courseeditor';
                   18218:             my $lockingkey = 'paste'."\0".'locked_num';
                   18219:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18220:                                                 $domain,$username);
                   18221:             if (exists($lockhash{$lockingkey})) {
                   18222:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18223:                 unless ($delresult eq 'ok') {
                   18224:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18225:                 }
                   18226:             }
1.462     albertel 18227: 	}
                   18228: # Give them a new cookie
1.463     albertel 18229: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18230: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18231: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18232:     
                   18233: # Initialize roles
                   18234: 
1.1414    raeburn  18235: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18236:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18237:     }
                   18238: # ------------------------------------ Check browser type and MathML capability
                   18239: 
1.1194    raeburn  18240:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18241:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18242: 
                   18243: # ------------------------------------------------------------- Get environment
                   18244: 
                   18245:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18246:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18247:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18248: 	undef(%userenv);
                   18249:     }
                   18250:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18251: 	$form->{'interface'}=$userenv{'interface'};
                   18252:     }
                   18253:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18254: 
                   18255: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18256:     foreach my $option ('interface','localpath','localres') {
                   18257:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18258:     }
                   18259: # --------------------------------------------------------- Write first profile
                   18260: 
                   18261:     {
1.1350    raeburn  18262:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18263: 	my %initial_env = 
                   18264: 	    ("user.name"          => $username,
                   18265: 	     "user.domain"        => $domain,
                   18266: 	     "user.home"          => $authhost,
                   18267: 	     "browser.type"       => $clientbrowser,
                   18268: 	     "browser.version"    => $clientversion,
                   18269: 	     "browser.mathml"     => $clientmathml,
                   18270: 	     "browser.unicode"    => $clientunicode,
                   18271: 	     "browser.os"         => $clientos,
1.1137    raeburn  18272:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18273:              "browser.info"       => $clientinfo,
1.1194    raeburn  18274:              "browser.osversion"  => $clientosversion,
1.462     albertel 18275: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18276: 	     "request.course.fn"  => '',
                   18277: 	     "request.course.uri" => '',
                   18278: 	     "request.course.sec" => '',
                   18279: 	     "request.role"       => 'cm',
                   18280: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18281: 	     "request.host"       => $ip,);
1.462     albertel 18282: 
                   18283:         if ($form->{'localpath'}) {
                   18284: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18285: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18286:         }
                   18287: 	
                   18288: 	if ($form->{'interface'}) {
                   18289: 	    $form->{'interface'}=~s/\W//gs;
                   18290: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18291: 	    $env{'browser.interface'}=$form->{'interface'};
                   18292: 	}
                   18293: 
1.1157    raeburn  18294:         if ($form->{'iptoken'}) {
                   18295:             my $lonhost = $r->dir_config('lonHostID');
                   18296:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18297:             $env{'user.noloadbalance'} = $lonhost;
                   18298:         }
                   18299: 
1.1268    raeburn  18300:         if ($form->{'noloadbalance'}) {
                   18301:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18302:             my $hosthere = $form->{'noloadbalance'};
                   18303:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18304:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18305:                 $env{'user.noloadbalance'} = $hosthere;
                   18306:             }
                   18307:         }
                   18308: 
1.1016    raeburn  18309:         unless ($domain eq 'public') {
1.1273    raeburn  18310:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18311:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18312: 
1.1414    raeburn  18313:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18314:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18315:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18316:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18317:             }
1.980     raeburn  18318: 
1.1311    raeburn  18319:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18320:                 $userenv{'canrequest.'.$crstype} =
                   18321:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18322:                                                       'reload','requestcourses',
                   18323:                                                       \%userenv,\%domdef,\%is_adv);
                   18324:             }
1.724     raeburn  18325: 
1.1418    raeburn  18326:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18327:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18328:                 if ($userenv{'authoreditors'}) {
                   18329:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18330:                 } elsif ($domdef{'editors'} ne '') {
                   18331:                     $userenv{'editors'} = $domdef{'editors'};
                   18332:                 } else {
                   18333:                     $userenv{'editors'} = 'edit,xml';
                   18334:                 }
1.1431    raeburn  18335:                 if ($userenv{'authorarchive'}) {
                   18336:                     $userenv{'canarchive'} = 1;
                   18337:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18338:                          ($domdef{'archive'})) {
                   18339:                     $userenv{'canarchive'} = 1;
                   18340:                 }
1.1418    raeburn  18341:             }
                   18342: 
1.1273    raeburn  18343:             $userenv{'canrequest.author'} =
                   18344:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18345:                                                   'reload','requestauthor',
1.980     raeburn  18346:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18347:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18348:                                                  $domain,$username);
                   18349:             my $reqstatus = $reqauthor{'author_status'};
                   18350:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18351:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18352:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18353:                                                       $reqauthor{'author'}{'timestamp'};
                   18354:                 }
1.1092    raeburn  18355:             }
1.1287    raeburn  18356:             my ($types,$typename) = &course_types();
                   18357:             if (ref($types) eq 'ARRAY') {
                   18358:                 my @options = ('approval','validate','autolimit');
                   18359:                 my $optregex = join('|',@options);
                   18360:                 my (%willtrust,%trustchecked);
                   18361:                 foreach my $type (@{$types}) {
                   18362:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18363:                     if ($dom_str ne '') {
                   18364:                         my $updatedstr = '';
                   18365:                         my @possdomains = split(',',$dom_str);
                   18366:                         foreach my $entry (@possdomains) {
                   18367:                             my ($extdom,$extopt) = split(':',$entry);
                   18368:                             unless ($trustchecked{$extdom}) {
                   18369:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18370:                                 $trustchecked{$extdom} = 1;
                   18371:                             }
                   18372:                             if ($willtrust{$extdom}) {
                   18373:                                 $updatedstr .= $entry.',';
                   18374:                             }
                   18375:                         }
                   18376:                         $updatedstr =~ s/,$//;
                   18377:                         if ($updatedstr) {
                   18378:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18379:                         } else {
                   18380:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18381:                         }
                   18382:                     }
                   18383:                 }
                   18384:             }
1.1092    raeburn  18385:         }
1.462     albertel 18386: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18387: 
1.462     albertel 18388: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18389: 		 &GDBM_WRCREAT(),0640)) {
                   18390: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18391: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18392: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18393:             if (ref($firstaccenv) eq 'HASH') {
                   18394:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18395:             }
                   18396:             if (ref($timerintenv) eq 'HASH') {
                   18397:                 &_add_to_env(\%disk_env,$timerintenv);
                   18398:             }
1.1414    raeburn  18399:             if (ref($coauthorenv) eq 'HASH') {
                   18400:                 if (keys(%{$coauthorenv})) {
                   18401:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18402:                 }
                   18403:             }
1.463     albertel 18404: 	    if (ref($args->{'extra_env'})) {
                   18405: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18406: 	    }
1.462     albertel 18407: 	    untie(%disk_env);
                   18408: 	} else {
1.705     tempelho 18409: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18410: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18411: 	    return 'error: '.$!;
                   18412: 	}
                   18413:     }
                   18414:     $env{'request.role'}='cm';
                   18415:     $env{'request.role.adv'}=$env{'user.adv'};
                   18416:     $env{'browser.type'}=$clientbrowser;
                   18417: 
                   18418:     return $cookie;
                   18419: 
                   18420: }
                   18421: 
                   18422: sub _add_to_env {
                   18423:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18424:     if (ref($env_data) eq 'HASH') {
                   18425:         while (my ($key,$value) = each(%$env_data)) {
                   18426: 	    $idf->{$prefix.$key} = $value;
                   18427: 	    $env{$prefix.$key}   = $value;
                   18428:         }
1.462     albertel 18429:     }
                   18430: }
                   18431: 
1.685     tempelho 18432: # --- Get the symbolic name of a problem and the url
                   18433: sub get_symb {
                   18434:     my ($request,$silent) = @_;
1.726     raeburn  18435:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18436:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18437:     if ($symb eq '') {
                   18438:         if (!$silent) {
1.1071    raeburn  18439:             if (ref($request)) { 
                   18440:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18441:             }
1.685     tempelho 18442:             return ();
                   18443:         }
                   18444:     }
                   18445:     &Apache::lonenc::check_decrypt(\$symb);
                   18446:     return ($symb);
                   18447: }
                   18448: 
                   18449: # --------------------------------------------------------------Get annotation
                   18450: 
                   18451: sub get_annotation {
                   18452:     my ($symb,$enc) = @_;
                   18453: 
                   18454:     my $key = $symb;
                   18455:     if (!$enc) {
                   18456:         $key =
                   18457:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18458:     }
                   18459:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18460:     return $annotation{$key};
                   18461: }
                   18462: 
                   18463: sub clean_symb {
1.731     raeburn  18464:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18465: 
                   18466:     &Apache::lonenc::check_decrypt(\$symb);
                   18467:     my $enc = $env{'request.enc'};
1.731     raeburn  18468:     if ($delete_enc) {
1.730     raeburn  18469:         delete($env{'request.enc'});
                   18470:     }
1.685     tempelho 18471: 
                   18472:     return ($symb,$enc);
                   18473: }
1.462     albertel 18474: 
1.1181    raeburn  18475: ############################################################
                   18476: ############################################################
                   18477: 
                   18478: =pod
                   18479: 
                   18480: =head1 Routines for building display used to search for courses
                   18481: 
                   18482: 
                   18483: =over 4
                   18484: 
                   18485: =item * &build_filters()
                   18486: 
                   18487: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18488: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18489: and quotacheck.pl
                   18490: 
1.1181    raeburn  18491: 
                   18492: Inputs:
                   18493: 
                   18494: filterlist - anonymous array of fields to include as potential filters 
                   18495: 
                   18496: crstype - course type
                   18497: 
                   18498: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18499:               to pop-open a course selector (will contain "extra element"). 
                   18500: 
                   18501: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18502: 
                   18503: filter - anonymous hash of criteria and their values
                   18504: 
                   18505: action - form action
                   18506: 
                   18507: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18508: 
1.1182    raeburn  18509: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18510: 
                   18511: cloneruname - username of owner of new course who wants to clone
                   18512: 
                   18513: clonerudom - domain of owner of new course who wants to clone
                   18514: 
                   18515: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18516: 
                   18517: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18518: 
                   18519: codedom - domain
                   18520: 
                   18521: formname - value of form element named "form". 
                   18522: 
                   18523: fixeddom - domain, if fixed.
                   18524: 
                   18525: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18526: 
                   18527: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18528: 
                   18529: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18530: 
                   18531: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18532: 
                   18533: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18534: 
                   18535: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18536: 
                   18537: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18538: 
1.1182    raeburn  18539: 
1.1181    raeburn  18540: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18541: 
1.1182    raeburn  18542: 
1.1181    raeburn  18543: Side Effects: None
                   18544: 
                   18545: =cut
                   18546: 
                   18547: # ---------------------------------------------- search for courses based on last activity etc.
                   18548: 
                   18549: sub build_filters {
                   18550:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18551:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18552:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18553:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18554:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18555:     my ($list,$jscript);
1.1181    raeburn  18556:     my $onchange = 'javascript:updateFilters(this)';
                   18557:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18558:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18559:         $typeselectform,$instcodetitle);
                   18560:     if ($formname eq '') {
                   18561:         $formname = $caller;
                   18562:     }
                   18563:     foreach my $item (@{$filterlist}) {
                   18564:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18565:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18566:             if ($item eq 'domainfilter') {
                   18567:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18568:             } elsif ($item eq 'coursefilter') {
                   18569:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18570:             } elsif ($item eq 'ownerfilter') {
                   18571:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18572:             } elsif ($item eq 'ownerdomfilter') {
                   18573:                 $filter->{'ownerdomfilter'} =
                   18574:                     &LONCAPA::clean_domain($filter->{$item});
                   18575:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18576:                                                        'ownerdomfilter',1);
                   18577:             } elsif ($item eq 'personfilter') {
                   18578:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18579:             } elsif ($item eq 'persondomfilter') {
                   18580:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18581:                                                         'persondomfilter',1);
                   18582:             } else {
                   18583:                 $filter->{$item} =~ s/\W//g;
                   18584:             }
                   18585:             if (!$filter->{$item}) {
                   18586:                 $filter->{$item} = '';
                   18587:             }
                   18588:         }
                   18589:         if ($item eq 'domainfilter') {
                   18590:             my $allow_blank = 1;
                   18591:             if ($formname eq 'portform') {
                   18592:                 $allow_blank=0;
                   18593:             } elsif ($formname eq 'studentform') {
                   18594:                 $allow_blank=0;
                   18595:             }
                   18596:             if ($fixeddom) {
                   18597:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18598:                                     ' value="'.$codedom.'" />'.
                   18599:                                     &Apache::lonnet::domain($codedom,'description');
                   18600:             } else {
                   18601:                 $domainselectform = &select_dom_form($filter->{$item},
                   18602:                                                      'domainfilter',
                   18603:                                                       $allow_blank,'',$onchange);
                   18604:             }
                   18605:         } else {
                   18606:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18607:         }
                   18608:     }
                   18609: 
                   18610:     # last course activity filter and selection
                   18611:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18612: 
                   18613:     # course created filter and selection
                   18614:     if (exists($filter->{'createdfilter'})) {
                   18615:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18616:     }
                   18617: 
1.1239    raeburn  18618:     my $prefix = $crstype;
                   18619:     if ($crstype eq 'Placement') {
                   18620:         $prefix = 'Placement Test'
                   18621:     }
1.1181    raeburn  18622:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18623:                 'cac' => "$prefix Activity",
                   18624:                 'ccr' => "$prefix Created",
                   18625:                 'cde' => "$prefix Title",
                   18626:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18627:                 'ins' => 'Institutional Code',
                   18628:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18629:                 'cow' => "$prefix Owner/Co-owner",
                   18630:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18631:                 'cog' => 'Type',
                   18632:              );
                   18633: 
                   18634:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18635:         my $typeval = 'Course';
                   18636:         if ($crstype eq 'Community') {
                   18637:             $typeval = 'Community';
1.1239    raeburn  18638:         } elsif ($crstype eq 'Placement') {
                   18639:             $typeval = 'Placement';
1.1181    raeburn  18640:         }
                   18641:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18642:     } else {
                   18643:         $typeselectform =  '<select name="type" size="1"';
                   18644:         if ($onchange) {
                   18645:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18646:         }
                   18647:         $typeselectform .= '>'."\n";
1.1237    raeburn  18648:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18649:             my $shown;
                   18650:             if ($posstype eq 'Placement') {
                   18651:                 $shown = &mt('Placement Test');
                   18652:             } else {
                   18653:                 $shown = &mt($posstype);
                   18654:             }
1.1181    raeburn  18655:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18656:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18657:         }
                   18658:         $typeselectform.="</select>";
                   18659:     }
                   18660: 
                   18661:     my ($cloneableonlyform,$cloneabletitle);
                   18662:     if (exists($filter->{'cloneableonly'})) {
                   18663:         my $cloneableon = '';
                   18664:         my $cloneableoff = ' checked="checked"';
                   18665:         if ($filter->{'cloneableonly'}) {
                   18666:             $cloneableon = $cloneableoff;
                   18667:             $cloneableoff = '';
                   18668:         }
                   18669:         $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>';
                   18670:         if ($formname eq 'ccrs') {
1.1187    bisitz   18671:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18672:         } else {
                   18673:             $cloneabletitle = &mt('Cloneable by you');
                   18674:         }
                   18675:     }
                   18676:     my $officialjs;
                   18677:     if ($crstype eq 'Course') {
                   18678:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18679: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18680: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18681:             if ($codedom) { 
1.1181    raeburn  18682:                 $officialjs = 1;
                   18683:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18684:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18685:                                                                   $officialjs,$codetitlesref);
                   18686:                 if ($jscript) {
1.1182    raeburn  18687:                     $jscript = '<script type="text/javascript">'."\n".
                   18688:                                '// <![CDATA['."\n".
                   18689:                                $jscript."\n".
                   18690:                                '// ]]>'."\n".
                   18691:                                '</script>'."\n";
1.1181    raeburn  18692:                 }
                   18693:             }
                   18694:             if ($instcodeform eq '') {
                   18695:                 $instcodeform =
                   18696:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18697:                     $list->{'instcodefilter'}.'" />';
                   18698:                 $instcodetitle = $lt{'ins'};
                   18699:             } else {
                   18700:                 $instcodetitle = $lt{'inc'};
                   18701:             }
                   18702:             if ($fixeddom) {
                   18703:                 $instcodetitle .= '<br />('.$codedom.')';
                   18704:             }
                   18705:         }
                   18706:     }
                   18707:     my $output = qq|
                   18708: <form method="post" name="filterpicker" action="$action">
                   18709: <input type="hidden" name="form" value="$formname" />
                   18710: |;
                   18711:     if ($formname eq 'modifycourse') {
                   18712:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18713:                    '<input type="hidden" name="prevphase" value="'.
                   18714:                    $prevphase.'" />'."\n";
1.1198    musolffc 18715:     } elsif ($formname eq 'quotacheck') {
                   18716:         $output .= qq|
                   18717: <input type="hidden" name="sortby" value="" />
                   18718: <input type="hidden" name="sortorder" value="" />
                   18719: |;
                   18720:     } else {
1.1181    raeburn  18721:         my $name_input;
                   18722:         if ($cnameelement ne '') {
                   18723:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18724:                           $cnameelement.'" />';
                   18725:         }
                   18726:         $output .= qq|
1.1182    raeburn  18727: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18728: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18729: $name_input
                   18730: $roleelement
                   18731: $multelement
                   18732: $typeelement
                   18733: |;
                   18734:         if ($formname eq 'portform') {
                   18735:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18736:         }
                   18737:     }
                   18738:     if ($fixeddom) {
                   18739:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18740:     }
                   18741:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18742:     if ($sincefilterform) {
                   18743:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18744:                   .$sincefilterform
                   18745:                   .&Apache::lonhtmlcommon::row_closure();
                   18746:     }
                   18747:     if ($createdfilterform) {
                   18748:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18749:                   .$createdfilterform
                   18750:                   .&Apache::lonhtmlcommon::row_closure();
                   18751:     }
                   18752:     if ($domainselectform) {
                   18753:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18754:                   .$domainselectform
                   18755:                   .&Apache::lonhtmlcommon::row_closure();
                   18756:     }
                   18757:     if ($typeselectform) {
                   18758:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18759:             $output .= $typeselectform;
                   18760:         } else {
                   18761:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18762:                       .$typeselectform
                   18763:                       .&Apache::lonhtmlcommon::row_closure();
                   18764:         }
                   18765:     }
                   18766:     if ($instcodeform) {
                   18767:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18768:                   .$instcodeform
                   18769:                   .&Apache::lonhtmlcommon::row_closure();
                   18770:     }
                   18771:     if (exists($filter->{'ownerfilter'})) {
                   18772:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18773:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18774:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18775:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18776:                    $ownerdomselectform.'</td></tr></table>'.
                   18777:                    &Apache::lonhtmlcommon::row_closure();
                   18778:     }
                   18779:     if (exists($filter->{'personfilter'})) {
                   18780:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18781:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18782:                    '<input type="text" name="personfilter" size="20" value="'.
                   18783:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18784:                    $persondomselectform.'</td></tr></table>'.
                   18785:                    &Apache::lonhtmlcommon::row_closure();
                   18786:     }
                   18787:     if (exists($filter->{'coursefilter'})) {
                   18788:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18789:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18790:                   .$list->{'coursefilter'}.'" />'
                   18791:                   .&Apache::lonhtmlcommon::row_closure();
                   18792:     }
                   18793:     if ($cloneableonlyform) {
                   18794:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18795:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18796:     }
                   18797:     if (exists($filter->{'descriptfilter'})) {
                   18798:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18799:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18800:                   .$list->{'descriptfilter'}.'" />'
                   18801:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18802:     }
                   18803:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18804:                '<input type="hidden" name="updater" value="" />'."\n".
                   18805:                '<input type="submit" name="gosearch" value="'.
                   18806:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18807:     return $jscript.$clonewarning.$output;
                   18808: }
                   18809: 
                   18810: =pod 
                   18811: 
                   18812: =item * &timebased_select_form()
                   18813: 
1.1182    raeburn  18814: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18815: filter e.g., Course Activity, Course Created, when searching for courses
                   18816: or communities
                   18817: 
                   18818: Inputs:
                   18819: 
                   18820: item - name of form element (sincefilter or createdfilter)
                   18821: 
                   18822: filter - anonymous hash of criteria and their values
                   18823: 
                   18824: Returns: HTML for a select box contained a blank, then six time selections,
                   18825:          with value set in incoming form variables currently selected. 
                   18826: 
                   18827: Side Effects: None
                   18828: 
                   18829: =cut
                   18830: 
                   18831: sub timebased_select_form {
                   18832:     my ($item,$filter) = @_;
                   18833:     if (ref($filter) eq 'HASH') {
                   18834:         $filter->{$item} =~ s/[^\d-]//g;
                   18835:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18836:         return &select_form(
                   18837:                             $filter->{$item},
                   18838:                             $item,
                   18839:                             {      '-1' => '',
                   18840:                                 '86400' => &mt('today'),
                   18841:                                '604800' => &mt('last week'),
                   18842:                               '2592000' => &mt('last month'),
                   18843:                               '7776000' => &mt('last three months'),
                   18844:                              '15552000' => &mt('last six months'),
                   18845:                              '31104000' => &mt('last year'),
                   18846:                     'select_form_order' =>
                   18847:                            ['-1','86400','604800','2592000','7776000',
                   18848:                             '15552000','31104000']});
                   18849:     }
                   18850: }
                   18851: 
                   18852: =pod
                   18853: 
                   18854: =item * &js_changer()
                   18855: 
                   18856: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18857: when course type or domain is changed, and also to hide 'Searching ...' on
                   18858: page load completion for page showing search result.
1.1181    raeburn  18859: 
                   18860: Inputs: None
                   18861: 
1.1183    raeburn  18862: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18863: 
                   18864: Side Effects: None
                   18865: 
                   18866: =cut
                   18867: 
                   18868: sub js_changer {
                   18869:     return <<ENDJS;
                   18870: <script type="text/javascript">
                   18871: // <![CDATA[
                   18872: function updateFilters(caller) {
                   18873:     if (typeof(caller) != "undefined") {
                   18874:         document.filterpicker.updater.value = caller.name;
                   18875:     }
                   18876:     document.filterpicker.submit();
                   18877: }
1.1183    raeburn  18878: 
                   18879: function hideSearching() {
                   18880:     if (document.getElementById('searching')) {
                   18881:         document.getElementById('searching').style.display = 'none';
                   18882:     }
                   18883:     return;
                   18884: }
                   18885: 
1.1181    raeburn  18886: // ]]>
                   18887: </script>
                   18888: 
                   18889: ENDJS
                   18890: }
                   18891: 
                   18892: =pod
                   18893: 
1.1182    raeburn  18894: =item * &search_courses()
                   18895: 
                   18896: Process selected filters form course search form and pass to lonnet::courseiddump
                   18897: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18898: 
                   18899: Inputs:
                   18900: 
                   18901: dom - domain being searched 
                   18902: 
                   18903: type - course type ('Course' or 'Community' or '.' if any).
                   18904: 
                   18905: filter - anonymous hash of criteria and their values
                   18906: 
                   18907: numtitles - for institutional codes - number of categories
                   18908: 
                   18909: cloneruname - optional username of new course owner
                   18910: 
                   18911: clonerudom - optional domain of new course owner
                   18912: 
1.1221    raeburn  18913: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18914:             (used when DC is using course creation form)
                   18915: 
                   18916: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18917: 
1.1221    raeburn  18918: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18919:            (and so can clone automatically)
                   18920: 
                   18921: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18922: 
                   18923: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18924:               courses to clone 
1.1182    raeburn  18925: 
                   18926: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18927: 
                   18928: 
                   18929: Side Effects: None
                   18930: 
                   18931: =cut
                   18932: 
                   18933: 
                   18934: sub search_courses {
1.1221    raeburn  18935:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18936:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18937:     my (%courses,%showcourses,$cloner);
                   18938:     if (($filter->{'ownerfilter'} ne '') ||
                   18939:         ($filter->{'ownerdomfilter'} ne '')) {
                   18940:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18941:                                        $filter->{'ownerdomfilter'};
                   18942:     }
                   18943:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18944:         if (!$filter->{$item}) {
                   18945:             $filter->{$item}='.';
                   18946:         }
                   18947:     }
                   18948:     my $now = time;
                   18949:     my $timefilter =
                   18950:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18951:     my ($createdbefore,$createdafter);
                   18952:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18953:         $createdbefore = $now;
                   18954:         $createdafter = $now-$filter->{'createdfilter'};
                   18955:     }
                   18956:     my ($instcodefilter,$regexpok);
                   18957:     if ($numtitles) {
                   18958:         if ($env{'form.official'} eq 'on') {
                   18959:             $instcodefilter =
                   18960:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18961:             $regexpok = 1;
                   18962:         } elsif ($env{'form.official'} eq 'off') {
                   18963:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18964:             unless ($instcodefilter eq '') {
                   18965:                 $regexpok = -1;
                   18966:             }
                   18967:         }
                   18968:     } else {
                   18969:         $instcodefilter = $filter->{'instcodefilter'};
                   18970:     }
                   18971:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18972:     if ($type eq '') { $type = '.'; }
                   18973: 
                   18974:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18975:         $cloner = $cloneruname.':'.$clonerudom;
                   18976:     }
                   18977:     %courses = &Apache::lonnet::courseiddump($dom,
                   18978:                                              $filter->{'descriptfilter'},
                   18979:                                              $timefilter,
                   18980:                                              $instcodefilter,
                   18981:                                              $filter->{'combownerfilter'},
                   18982:                                              $filter->{'coursefilter'},
                   18983:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18984:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18985:                                              $filter->{'cloneableonly'},
                   18986:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18987:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18988:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18989:         my $ccrole;
                   18990:         if ($type eq 'Community') {
                   18991:             $ccrole = 'co';
                   18992:         } else {
                   18993:             $ccrole = 'cc';
                   18994:         }
                   18995:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18996:                                                      $filter->{'persondomfilter'},
                   18997:                                                      'userroles',undef,
                   18998:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18999:                                                      $dom);
                   19000:         foreach my $role (keys(%rolehash)) {
                   19001:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   19002:             my $cid = $cdom.'_'.$cnum;
                   19003:             if (exists($courses{$cid})) {
                   19004:                 if (ref($courses{$cid}) eq 'HASH') {
                   19005:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   19006:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  19007:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  19008:                         }
                   19009:                     } else {
                   19010:                         $courses{$cid}{roles} = [$courserole];
                   19011:                     }
                   19012:                     $showcourses{$cid} = $courses{$cid};
                   19013:                 }
                   19014:             }
                   19015:         }
                   19016:         %courses = %showcourses;
                   19017:     }
                   19018:     return %courses;
                   19019: }
                   19020: 
                   19021: =pod
                   19022: 
1.1181    raeburn  19023: =back
                   19024: 
1.1207    raeburn  19025: =head1 Routines for version requirements for current course.
                   19026: 
                   19027: =over 4
                   19028: 
                   19029: =item * &check_release_required()
                   19030: 
                   19031: Compares required LON-CAPA version with version on server, and
                   19032: if required version is newer looks for a server with the required version.
                   19033: 
                   19034: Looks first at servers in user's owen domain; if none suitable, looks at
                   19035: servers in course's domain are permitted to host sessions for user's domain.
                   19036: 
                   19037: Inputs:
                   19038: 
                   19039: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19040: 
                   19041: $courseid - Course ID of current course
                   19042: 
                   19043: $rolecode - User's current role in course (for switchserver query string).
                   19044: 
                   19045: $required - LON-CAPA version needed by course (format: Major.Minor).
                   19046: 
                   19047: 
                   19048: Returns:
                   19049: 
                   19050: $switchserver - query string tp append to /adm/switchserver call (if 
                   19051:                 current server's LON-CAPA version is too old. 
                   19052: 
                   19053: $warning - Message is displayed if no suitable server could be found.
                   19054: 
                   19055: =cut
                   19056: 
                   19057: sub check_release_required {
                   19058:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   19059:     my ($switchserver,$warning);
                   19060:     if ($required ne '') {
                   19061:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   19062:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19063:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   19064:             my $otherserver;
                   19065:             if (($major eq '' && $minor eq '') ||
                   19066:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   19067:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   19068:                 my $switchlcrev =
                   19069:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   19070:                                                            $userdomserver);
                   19071:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   19072:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   19073:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   19074:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   19075:                     if ($cdom ne $env{'user.domain'}) {
                   19076:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   19077:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   19078:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   19079:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   19080:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   19081:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   19082:                         my $canhost =
                   19083:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   19084:                                                               $coursedomserver,
                   19085:                                                               $remoterev,
                   19086:                                                               $udomdefaults{'remotesessions'},
                   19087:                                                               $defdomdefaults{'hostedsessions'});
                   19088: 
                   19089:                         if ($canhost) {
                   19090:                             $otherserver = $coursedomserver;
                   19091:                         } else {
                   19092:                             $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.");
                   19093:                         }
                   19094:                     } else {
                   19095:                         $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).");
                   19096:                     }
                   19097:                 } else {
                   19098:                     $otherserver = $userdomserver;
                   19099:                 }
                   19100:             }
                   19101:             if ($otherserver ne '') {
                   19102:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   19103:             }
                   19104:         }
                   19105:     }
                   19106:     return ($switchserver,$warning);
                   19107: }
                   19108: 
                   19109: =pod
                   19110: 
                   19111: =item * &check_release_result()
                   19112: 
                   19113: Inputs:
                   19114: 
                   19115: $switchwarning - Warning message if no suitable server found to host session.
                   19116: 
                   19117: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19118:                 and current role.
                   19119: 
                   19120: Returns: HTML to display with information about requirement to switch server.
                   19121:          Either displaying warning with link to Roles/Courses screen or
                   19122:          display link to switchserver.
                   19123: 
1.1181    raeburn  19124: =cut
                   19125: 
1.1207    raeburn  19126: sub check_release_result {
                   19127:     my ($switchwarning,$switchserver) = @_;
                   19128:     my $output = &start_page('Selected course unavailable on this server').
1.1463    raeburn  19129:                  '<div class="LC_landmark" role="main"><p class="LC_warning">';
1.1207    raeburn  19130:     if ($switchwarning) {
                   19131:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   19132:         if (&show_course()) {
                   19133:             $output .= &mt('Display courses');
                   19134:         } else {
                   19135:             $output .= &mt('Display roles');
                   19136:         }
                   19137:         $output .= '</a>';
                   19138:     } elsif ($switchserver) {
                   19139:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   19140:                    '<br />'.
                   19141:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   19142:                    &mt('Switch Server').
                   19143:                    '</a>';
                   19144:     }
1.1463    raeburn  19145:     $output .= '</p></div>'.&end_page();
1.1207    raeburn  19146:     return $output;
                   19147: }
                   19148: 
                   19149: =pod
                   19150: 
                   19151: =item * &needs_coursereinit()
                   19152: 
                   19153: Determine if course contents stored for user's session needs to be
                   19154: refreshed, because content has changed since "Big Hash" last tied.
                   19155: 
                   19156: Check for change is made if time last checked is more than 10 minutes ago
                   19157: (by default).
                   19158: 
                   19159: Inputs:
                   19160: 
                   19161: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   19162: 
                   19163: $interval (optional) - Time which may elapse (in s) between last check for content
                   19164:                        change in current course. (default: 600 s).  
                   19165: 
                   19166: Returns: an array; first element is:
                   19167: 
                   19168: =over 4
                   19169: 
                   19170: 'switch' - if content updates mean user's session
                   19171:            needs to be switched to a server running a newer LON-CAPA version
                   19172:  
                   19173: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19174:            on current server hosting user's session                
                   19175: 
                   19176: ''       - if no action required.
                   19177: 
                   19178: =back
                   19179: 
                   19180: If first item element is 'switch':
                   19181: 
                   19182: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19183: 
                   19184: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19185:                               and current role. 
                   19186: 
                   19187: otherwise: no other elements returned.
                   19188: 
                   19189: =back
                   19190: 
                   19191: =cut
                   19192: 
                   19193: sub needs_coursereinit {
                   19194:     my ($loncaparev,$interval) = @_;
                   19195:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19196:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19197:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19198:     my $now = time;
                   19199:     if ($interval eq '') {
                   19200:         $interval = 600;
                   19201:     }
                   19202:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19203:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19204:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19205:         if ($blocked) {
                   19206:             return ();
                   19207:         }
1.1391    raeburn  19208:         my $update;
                   19209:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19210:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19211:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19212:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19213:             if ($needswitch) {
                   19214:                 return ('switch',$switchwarning,$switchserver);
                   19215:             }
                   19216:             $update = 'main';
                   19217:         }
                   19218:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19219:             if ($update) {
                   19220:                 $update = 'both';
                   19221:             } else {
                   19222:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19223:                 if ($needswitch) {
                   19224:                     return ('switch',$switchwarning,$switchserver);
                   19225:                 } else {
                   19226:                     $update = 'supp';
1.1207    raeburn  19227:                 }
                   19228:             }
1.1391    raeburn  19229:         }
1.1453    raeburn  19230:         return ($update);
1.1391    raeburn  19231:     }
                   19232:     return ();
                   19233: }
                   19234: 
                   19235: sub switch_for_update {
                   19236:     my ($loncaparev,$cdom,$cnum) = @_;
                   19237:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19238:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19239:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19240:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19241:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19242:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19243:             my ($switchserver,$switchwarning) =
                   19244:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19245:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19246:             if ($switchwarning ne '' || $switchserver ne '') {
                   19247:                 return ('switch',$switchwarning,$switchserver);
                   19248:             }
1.1207    raeburn  19249:         }
                   19250:     }
                   19251:     return ();
                   19252: }
1.1181    raeburn  19253: 
1.1083    raeburn  19254: sub update_content_constraints {
1.1395    raeburn  19255:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19256:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19257:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19258:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19259:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19260:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19261:         if ($item eq 'resourcetag') {
                   19262:             if ($name eq 'responsetype') {
                   19263:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19264:             }
1.1307    raeburn  19265:         } elsif ($item eq 'course') {
                   19266:             if ($name eq 'courserestype') {
                   19267:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19268:             }
1.1083    raeburn  19269:         }
                   19270:     }
                   19271:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19272:     if (defined($navmap)) {
1.1307    raeburn  19273:         my (%allresponses,%allcrsrestypes);
                   19274:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19275:             if ($res->is_tool()) {
                   19276:                 if ($allcrsrestypes{'exttool'}) {
                   19277:                     $allcrsrestypes{'exttool'} ++;
                   19278:                 } else {
                   19279:                     $allcrsrestypes{'exttool'} = 1;
                   19280:                 }
                   19281:                 next;
                   19282:             }
1.1083    raeburn  19283:             my %responses = $res->responseTypes();
                   19284:             foreach my $key (keys(%responses)) {
                   19285:                 next unless(exists($checkresponsetypes{$key}));
                   19286:                 $allresponses{$key} += $responses{$key};
                   19287:             }
                   19288:         }
                   19289:         foreach my $key (keys(%allresponses)) {
                   19290:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19291:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19292:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19293:             }
                   19294:         }
1.1307    raeburn  19295:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19296:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19297:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19298:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19299:             }
                   19300:         }
1.1083    raeburn  19301:         undef($navmap);
                   19302:     }
1.1391    raeburn  19303:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19304:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19305:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19306:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19307:         }
                   19308:     }
1.1083    raeburn  19309:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19310:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19311:     }
                   19312:     return;
                   19313: }
                   19314: 
1.1110    raeburn  19315: sub allmaps_incourse {
                   19316:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19317:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19318:         $cid = $env{'request.course.id'};
                   19319:         $cdom = $env{'course.'.$cid.'.domain'};
                   19320:         $cnum = $env{'course.'.$cid.'.num'};
                   19321:         $chome = $env{'course.'.$cid.'.home'};
                   19322:     }
                   19323:     my %allmaps = ();
                   19324:     my $lastchange =
                   19325:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19326:     if ($lastchange > $env{'request.course.tied'}) {
                   19327:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19328:         unless ($ferr) {
1.1395    raeburn  19329:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19330:         }
                   19331:     }
                   19332:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19333:     if (defined($navmap)) {
                   19334:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19335:             $allmaps{$res->src()} = 1;
                   19336:         }
                   19337:     }
                   19338:     return \%allmaps;
                   19339: }
                   19340: 
1.1083    raeburn  19341: sub parse_supplemental_title {
                   19342:     my ($title) = @_;
                   19343: 
                   19344:     my ($foldertitle,$renametitle);
                   19345:     if ($title =~ /&amp;&amp;&amp;/) {
                   19346:         $title = &HTML::Entites::decode($title);
                   19347:     }
                   19348:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19349:         $renametitle=$4;
                   19350:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19351:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19352:         my $name =  &plainname($uname,$udom);
                   19353:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19354:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19355:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19356:         if ($foldertitle ne '') {
1.1401    raeburn  19357:             $title .= ': <br />'.$foldertitle;
                   19358:         }
1.1083    raeburn  19359:     }
                   19360:     if (wantarray) {
                   19361:         return ($title,$foldertitle,$renametitle);
                   19362:     }
                   19363:     return $title;
                   19364: }
                   19365: 
1.1395    raeburn  19366: sub get_supplemental {
                   19367:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19368:     my $hashid=$cnum.':'.$cdom;
                   19369:     my ($supplemental,$cached,$set_httprefs);
                   19370:     unless ($ignorecache) {
                   19371:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19372:     }
                   19373:     unless (defined($cached)) {
                   19374:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19375:         unless ($chome eq 'no_host') {
                   19376:             my @order = @LONCAPA::map::order;
                   19377:             my @resources = @LONCAPA::map::resources;
                   19378:             my @resparms = @LONCAPA::map::resparms;
                   19379:             my @zombies = @LONCAPA::map::zombies;
                   19380:             my ($errors,%ids,%hidden);
                   19381:             $errors =
                   19382:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19383:                                       $errors,$possdel,\%ids,\%hidden);
                   19384:             @LONCAPA::map::order = @order;
                   19385:             @LONCAPA::map::resources = @resources;
                   19386:             @LONCAPA::map::resparms = @resparms;
                   19387:             @LONCAPA::map::zombies = @zombies;
                   19388:             $set_httprefs = 1;
                   19389:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19390:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19391:             }
                   19392:             $supplemental = {
                   19393:                                ids => \%ids,
                   19394:                                hidden => \%hidden,
                   19395:                             };
                   19396:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19397:         }
                   19398:     }
                   19399:     return ($supplemental,$set_httprefs);
                   19400: }
                   19401: 
1.1143    raeburn  19402: sub recurse_supplemental {
1.1391    raeburn  19403:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19404:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19405:         my $mapnum;
                   19406:         if ($suppmap eq 'supplemental.sequence') {
                   19407:             $mapnum = 0;
                   19408:         } else {
                   19409:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19410:         }
1.1143    raeburn  19411:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19412:         if ($fatal) {
                   19413:             $errors ++;
                   19414:         } else {
1.1389    raeburn  19415:             my @order = @LONCAPA::map::order;
                   19416:             if (@order > 0) {
                   19417:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19418:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19419:                 foreach my $idx (@order) {
                   19420:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19421:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19422:                         my $id = $mapnum.':'.$idx;
                   19423:                         push(@{$suppids->{$src}},$id);
                   19424:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19425:                             $hiddensupp->{$id} = 1;
                   19426:                         }
1.1146    raeburn  19427:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19428:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19429:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19430:                         } else {
1.1391    raeburn  19431:                             my $allowed;
                   19432:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19433:                                 $allowed = 1;
                   19434:                             } elsif ($possdel) {
                   19435:                                 foreach my $item (@{$suppids->{$src}}) {
                   19436:                                     next if ($item eq $id);
                   19437:                                     unless ($hiddensupp->{$item}) {
                   19438:                                        $allowed = 1;
                   19439:                                        last;
                   19440:                                     }
                   19441:                                 }
                   19442:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19443:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19444:                                 }
                   19445:                             }
                   19446:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19447:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19448:                             }
1.1143    raeburn  19449:                         }
                   19450:                     }
                   19451:                 }
                   19452:             }
                   19453:         }
                   19454:     }
1.1391    raeburn  19455:     return $errors;
                   19456: }
                   19457: 
                   19458: sub set_supp_httprefs {
                   19459:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19460:     if (ref($supplemental) eq 'HASH') {
                   19461:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19462:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19463:                 next if ($src =~ /\.sequence$/);
                   19464:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19465:                     my $allowed;
                   19466:                     if ($env{'request.role.adv'}) {
                   19467:                         $allowed = 1;
                   19468:                     } else {
                   19469:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19470:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19471:                                 $allowed = 1;
                   19472:                                 last;
                   19473:                             }
                   19474:                         }
                   19475:                     }
                   19476:                     if (exists($env{'httpref.'.$src})) {
                   19477:                         if ($possdel) {
                   19478:                             unless ($allowed) {
                   19479:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19480:                             }
                   19481:                         }
                   19482:                     } elsif ($allowed) {
                   19483:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19484:                     }
                   19485:                 }
                   19486:             }
                   19487:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19488:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19489:             }
                   19490:         }
                   19491:     }
                   19492: }
                   19493: 
                   19494: sub get_supp_parameter {
                   19495:     my ($resparm,$name)=@_;
                   19496:     return if ($resparm eq '');
                   19497:     my $value=undef;
                   19498:     my $ptype=undef;
                   19499:     foreach (split('&&&',$resparm)) {
                   19500:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19501:         if ($thisname eq $name) {
                   19502:             $value=$thisvalue;
                   19503:             $ptype=$thistype;
                   19504:         }
                   19505:     }
                   19506:     return $value;
1.1143    raeburn  19507: }
                   19508: 
1.1101    raeburn  19509: sub symb_to_docspath {
1.1267    raeburn  19510:     my ($symb,$navmapref) = @_;
                   19511:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19512:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19513:     if ($resurl=~/\.(sequence|page)$/) {
                   19514:         $mapurl=$resurl;
                   19515:     } elsif ($resurl eq 'adm/navmaps') {
                   19516:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19517:     }
                   19518:     my $mapresobj;
1.1267    raeburn  19519:     unless (ref($$navmapref)) {
                   19520:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19521:     }
                   19522:     if (ref($$navmapref)) {
                   19523:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19524:     }
                   19525:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19526:     my $type=$2;
                   19527:     my $path;
                   19528:     if (ref($mapresobj)) {
                   19529:         my $pcslist = $mapresobj->map_hierarchy();
                   19530:         if ($pcslist ne '') {
                   19531:             foreach my $pc (split(/,/,$pcslist)) {
                   19532:                 next if ($pc <= 1);
1.1267    raeburn  19533:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19534:                 if (ref($res)) {
                   19535:                     my $thisurl = $res->src();
                   19536:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19537:                     my $thistitle = $res->title();
                   19538:                     $path .= '&'.
                   19539:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19540:                              &escape($thistitle).
1.1101    raeburn  19541:                              ':'.$res->randompick().
                   19542:                              ':'.$res->randomout().
                   19543:                              ':'.$res->encrypted().
                   19544:                              ':'.$res->randomorder().
                   19545:                              ':'.$res->is_page();
                   19546:                 }
                   19547:             }
                   19548:         }
                   19549:         $path =~ s/^\&//;
                   19550:         my $maptitle = $mapresobj->title();
                   19551:         if ($mapurl eq 'default') {
1.1129    raeburn  19552:             $maptitle = 'Main Content';
1.1101    raeburn  19553:         }
                   19554:         $path .= (($path ne '')? '&' : '').
                   19555:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19556:                  &escape($maptitle).
1.1101    raeburn  19557:                  ':'.$mapresobj->randompick().
                   19558:                  ':'.$mapresobj->randomout().
                   19559:                  ':'.$mapresobj->encrypted().
                   19560:                  ':'.$mapresobj->randomorder().
                   19561:                  ':'.$mapresobj->is_page();
                   19562:     } else {
                   19563:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19564:         my $ispage = (($type eq 'page')? 1 : '');
                   19565:         if ($mapurl eq 'default') {
1.1129    raeburn  19566:             $maptitle = 'Main Content';
1.1101    raeburn  19567:         }
                   19568:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19569:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19570:     }
                   19571:     unless ($mapurl eq 'default') {
                   19572:         $path = 'default&'.
1.1146    raeburn  19573:                 &escape('Main Content').
1.1101    raeburn  19574:                 ':::::&'.$path;
                   19575:     }
                   19576:     return $path;
                   19577: }
                   19578: 
1.1393    raeburn  19579: sub validate_folderpath {
                   19580:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19581:     if ($env{'form.folderpath'} ne '') {
                   19582:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19583:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19584:         for (my $i=0; $i<@items; $i++) {
                   19585:             my $odd = $i%2;
                   19586:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19587:                 $badpath = 1;
1.1394    raeburn  19588:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19589:                 my $idx = $i-1;
1.1394    raeburn  19590:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19591:                     my $esc_name = $1;
                   19592:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19593:                         $supppath .= '&'.$esc_name;
                   19594:                         $changed = 1;
                   19595:                     } else {
                   19596:                         $supppath .= '&'.$items[$i];
                   19597:                     }
                   19598:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19599:                     $changed = 1;
1.1393    raeburn  19600:                     my $is_hidden;
                   19601:                     unless ($got_supp) {
1.1395    raeburn  19602:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19603:                         if (ref($supplemental) eq 'HASH') {
                   19604:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19605:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19606:                             }
                   19607:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19608:                                 %suppids = %{$supplemental->{'ids'}};
                   19609:                             }
                   19610:                         }
                   19611:                         $got_supp = 1;
                   19612:                     }
                   19613:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19614:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19615:                         if ($supphidden{$mapid}) {
                   19616:                             $is_hidden = 1;
                   19617:                         }
                   19618:                     }
1.1394    raeburn  19619:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19620:                 } else {
                   19621:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19622:                 }
                   19623:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19624:                 $badpath = 1;
1.1394    raeburn  19625:             } elsif ($supplementalflag) {
1.1393    raeburn  19626:                 $supppath .= '&'.$items[$i];
                   19627:             }
                   19628:             last if ($badpath);
                   19629:         }
                   19630:         if ($badpath) {
                   19631:             delete($env{'form.folderpath'});
1.1394    raeburn  19632:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19633:             $supppath =~ s/^\&//;
                   19634:             $env{'form.folderpath'} = $supppath;
                   19635:         }
                   19636:     }
                   19637:     return;
                   19638: }
                   19639: 
1.1094    raeburn  19640: sub captcha_display {
1.1327    raeburn  19641:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19642:     my ($output,$error);
1.1234    raeburn  19643:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19644:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19645:     if ($captcha eq 'original') {
1.1094    raeburn  19646:         $output = &create_captcha();
                   19647:         unless ($output) {
1.1172    raeburn  19648:             $error = 'captcha';
1.1094    raeburn  19649:         }
                   19650:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19651:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19652:         unless ($output) {
1.1172    raeburn  19653:             $error = 'recaptcha';
1.1094    raeburn  19654:         }
                   19655:     }
1.1234    raeburn  19656:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19657: }
                   19658: 
                   19659: sub captcha_response {
1.1327    raeburn  19660:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19661:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19662:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19663:     if ($captcha eq 'original') {
1.1094    raeburn  19664:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19665:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19666:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19667:     } else {
                   19668:         $captcha_chk = 1;
                   19669:     }
                   19670:     return ($captcha_chk,$captcha_error);
                   19671: }
                   19672: 
                   19673: sub get_captcha_config {
1.1327    raeburn  19674:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19675:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19676:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19677:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19678:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19679:     if ($context eq 'usercreation') {
                   19680:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19681:         if (ref($domconfig{$context}) eq 'HASH') {
                   19682:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19683:             if (ref($hashtocheck) eq 'HASH') {
                   19684:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19685:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19686:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19687:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19688:                     }
                   19689:                     if ($privkey && $pubkey) {
                   19690:                         $captcha = 'recaptcha';
1.1234    raeburn  19691:                         $version = $hashtocheck->{'recaptchaversion'};
                   19692:                         if ($version ne '2') {
                   19693:                             $version = 1;
                   19694:                         }
1.1095    raeburn  19695:                     } else {
                   19696:                         $captcha = 'original';
                   19697:                     }
                   19698:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19699:                     $captcha = 'original';
                   19700:                 }
1.1094    raeburn  19701:             }
1.1095    raeburn  19702:         } else {
                   19703:             $captcha = 'captcha';
                   19704:         }
                   19705:     } elsif ($context eq 'login') {
                   19706:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19707:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19708:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19709:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19710:             if ($privkey && $pubkey) {
                   19711:                 $captcha = 'recaptcha';
1.1234    raeburn  19712:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19713:                 if ($version ne '2') {
                   19714:                     $version = 1; 
                   19715:                 }
1.1095    raeburn  19716:             } else {
                   19717:                 $captcha = 'original';
1.1094    raeburn  19718:             }
1.1095    raeburn  19719:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19720:             $captcha = 'original';
1.1094    raeburn  19721:         }
1.1327    raeburn  19722:     } elsif ($context eq 'passwords') {
                   19723:         if ($dom_in_effect) {
                   19724:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19725:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19726:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19727:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19728:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19729:                 }
                   19730:                 if ($privkey && $pubkey) {
                   19731:                     $captcha = 'recaptcha';
                   19732:                     $version = $passwdconf{'recaptchaversion'};
                   19733:                     if ($version ne '2') {
                   19734:                         $version = 1;
                   19735:                     }
                   19736:                 } else {
                   19737:                     $captcha = 'original';
                   19738:                 }
                   19739:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19740:                 $captcha = 'original';
                   19741:             }
                   19742:         }
                   19743:     } 
1.1234    raeburn  19744:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19745: }
                   19746: 
                   19747: sub create_captcha {
                   19748:     my %captcha_params = &captcha_settings();
                   19749:     my ($output,$maxtries,$tries) = ('',10,0);
                   19750:     while ($tries < $maxtries) {
                   19751:         $tries ++;
                   19752:         my $captcha = Authen::Captcha->new (
                   19753:                                            output_folder => $captcha_params{'output_dir'},
                   19754:                                            data_folder   => $captcha_params{'db_dir'},
                   19755:                                           );
                   19756:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19757: 
                   19758:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19759:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19760:                       '<span class="LC_nobreak">'.
1.1453    raeburn  19761:                       '<label>'.&mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1463    raeburn  19762:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" aria-required="true" />'.
1.1453    raeburn  19763:                       '</label></span><br />'.
1.1176    raeburn  19764:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19765:             last;
                   19766:         }
                   19767:     }
1.1323    raeburn  19768:     if ($output eq '') {
                   19769:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19770:     }
1.1094    raeburn  19771:     return $output;
                   19772: }
                   19773: 
                   19774: sub captcha_settings {
                   19775:     my %captcha_params = (
                   19776:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19777:                            www_output_dir => "/captchaspool",
                   19778:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19779:                            numchars       => '5',
                   19780:                          );
                   19781:     return %captcha_params;
                   19782: }
                   19783: 
                   19784: sub check_captcha {
                   19785:     my ($captcha_chk,$captcha_error);
                   19786:     my $code = $env{'form.code'};
                   19787:     my $md5sum = $env{'form.crypt'};
                   19788:     my %captcha_params = &captcha_settings();
                   19789:     my $captcha = Authen::Captcha->new(
                   19790:                       output_folder => $captcha_params{'output_dir'},
                   19791:                       data_folder   => $captcha_params{'db_dir'},
                   19792:                   );
1.1109    raeburn  19793:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19794:     my %captcha_hash = (
                   19795:                         0       => 'Code not checked (file error)',
                   19796:                        -1      => 'Failed: code expired',
                   19797:                        -2      => 'Failed: invalid code (not in database)',
                   19798:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19799:     );
                   19800:     if ($captcha_chk != 1) {
                   19801:         $captcha_error = $captcha_hash{$captcha_chk}
                   19802:     }
                   19803:     return ($captcha_chk,$captcha_error);
                   19804: }
                   19805: 
                   19806: sub create_recaptcha {
1.1234    raeburn  19807:     my ($pubkey,$version) = @_;
                   19808:     if ($version >= 2) {
1.1367    raeburn  19809:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19810:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19811:     } else {
                   19812:         my $use_ssl;
                   19813:         if ($ENV{'SERVER_PORT'} == 443) {
                   19814:             $use_ssl = 1;
                   19815:         }
                   19816:         my $captcha = Captcha::reCAPTCHA->new;
                   19817:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19818:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19819:                &mt('If the text is hard to read, [_1] will replace them.',
                   19820:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19821:                '<br /><br />';
                   19822:     }
1.1094    raeburn  19823: }
                   19824: 
                   19825: sub check_recaptcha {
1.1234    raeburn  19826:     my ($privkey,$version) = @_;
1.1094    raeburn  19827:     my $captcha_chk;
1.1350    raeburn  19828:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19829:     if ($version >= 2) {
                   19830:         my %info = (
                   19831:                      secret   => $privkey, 
                   19832:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19833:                      remoteip => $ip,
1.1234    raeburn  19834:                    );
1.1280    raeburn  19835:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19836:         $request->content(join('&',map {
                   19837:                          my $name = escape($_);
                   19838:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19839:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19840:                          : &escape($info{$_}) );
                   19841:         } keys(%info)));
                   19842:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19843:         if ($response->is_success)  {
                   19844:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19845:             if (ref($data) eq 'HASH') {
                   19846:                 if ($data->{'success'}) {
                   19847:                     $captcha_chk = 1;
                   19848:                 }
                   19849:             }
                   19850:         }
                   19851:     } else {
                   19852:         my $captcha = Captcha::reCAPTCHA->new;
                   19853:         my $captcha_result =
                   19854:             $captcha->check_answer(
                   19855:                                     $privkey,
1.1350    raeburn  19856:                                     $ip,
1.1234    raeburn  19857:                                     $env{'form.recaptcha_challenge_field'},
                   19858:                                     $env{'form.recaptcha_response_field'},
                   19859:                                   );
                   19860:         if ($captcha_result->{is_valid}) {
                   19861:             $captcha_chk = 1;
                   19862:         }
1.1094    raeburn  19863:     }
                   19864:     return $captcha_chk;
                   19865: }
                   19866: 
1.1174    raeburn  19867: sub emailusername_info {
1.1244    raeburn  19868:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19869:     my %titles = &Apache::lonlocal::texthash (
                   19870:                      lastname      => 'Last Name',
                   19871:                      firstname     => 'First Name',
                   19872:                      institution   => 'School/college/university',
                   19873:                      location      => "School's city, state/province, country",
                   19874:                      web           => "School's web address",
                   19875:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19876:                      id            => 'Student/Employee ID',
1.1174    raeburn  19877:                  );
                   19878:     return (\@fields,\%titles);
                   19879: }
                   19880: 
1.1161    raeburn  19881: sub cleanup_html {
                   19882:     my ($incoming) = @_;
                   19883:     my $outgoing;
                   19884:     if ($incoming ne '') {
                   19885:         $outgoing = $incoming;
                   19886:         $outgoing =~ s/;/&#059;/g;
                   19887:         $outgoing =~ s/\#/&#035;/g;
                   19888:         $outgoing =~ s/\&/&#038;/g;
                   19889:         $outgoing =~ s/</&#060;/g;
                   19890:         $outgoing =~ s/>/&#062;/g;
                   19891:         $outgoing =~ s/\(/&#040/g;
                   19892:         $outgoing =~ s/\)/&#041;/g;
                   19893:         $outgoing =~ s/"/&#034;/g;
                   19894:         $outgoing =~ s/'/&#039;/g;
                   19895:         $outgoing =~ s/\$/&#036;/g;
                   19896:         $outgoing =~ s{/}{&#047;}g;
                   19897:         $outgoing =~ s/=/&#061;/g;
                   19898:         $outgoing =~ s/\\/&#092;/g
                   19899:     }
                   19900:     return $outgoing;
                   19901: }
                   19902: 
1.1190    musolffc 19903: # Checks for critical messages and returns a redirect url if one exists.
                   19904: # $interval indicates how often to check for messages.
1.1282    raeburn  19905: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19906: sub critical_redirect {
1.1282    raeburn  19907:     my ($interval,$context) = @_;
1.1356    raeburn  19908:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19909:         return ();
                   19910:     }
1.1190    musolffc 19911:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19912:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19913:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19914:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19915:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19916:             if ($blocked) {
                   19917:                 my $checkrole = "cm./$cdom/$cnum";
                   19918:                 if ($env{'request.course.sec'} ne '') {
                   19919:                     $checkrole .= "/$env{'request.course.sec'}";
                   19920:                 }
                   19921:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19922:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19923:                     return;
                   19924:                 }
                   19925:             }
                   19926:         }
1.1190    musolffc 19927:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19928:                                         $env{'user.name'});
                   19929:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19930:         my $redirecturl;
1.1190    musolffc 19931:         if ($what[0]) {
1.1356    raeburn  19932: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19933: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19934: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19935:                 return (1, $url);
1.1190    musolffc 19936:             }
1.1191    raeburn  19937:         }
                   19938:     } 
                   19939:     return ();
1.1190    musolffc 19940: }
                   19941: 
1.1174    raeburn  19942: # Use:
                   19943: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19944: #
                   19945: ##################################################
                   19946: #          password associated functions         #
                   19947: ##################################################
                   19948: sub des_keys {
                   19949:     # Make a new key for DES encryption.
                   19950:     # Each key has two parts which are returned separately.
                   19951:     # Please note:  Each key must be passed through the &hex function
                   19952:     # before it is output to the web browser.  The hex versions cannot
                   19953:     # be used to decrypt.
                   19954:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19955:                 '8','9','a','b','c','d','e','f');
                   19956:     my $lkey='';
                   19957:     for (0..7) {
                   19958:         $lkey.=$hexstr[rand(15)];
                   19959:     }
                   19960:     my $ukey='';
                   19961:     for (0..7) {
                   19962:         $ukey.=$hexstr[rand(15)];
                   19963:     }
                   19964:     return ($lkey,$ukey);
                   19965: }
                   19966: 
                   19967: sub des_decrypt {
                   19968:     my ($key,$cyphertext) = @_;
                   19969:     my $keybin=pack("H16",$key);
                   19970:     my $cypher;
                   19971:     if ($Crypt::DES::VERSION>=2.03) {
                   19972:         $cypher=new Crypt::DES $keybin;
                   19973:     } else {
                   19974:         $cypher=new DES $keybin;
                   19975:     }
1.1233    raeburn  19976:     my $plaintext='';
                   19977:     my $cypherlength = length($cyphertext);
                   19978:     my $numchunks = int($cypherlength/32);
                   19979:     for (my $j=0; $j<$numchunks; $j++) {
                   19980:         my $start = $j*32;
                   19981:         my $cypherblock = substr($cyphertext,$start,32);
                   19982:         my $chunk =
                   19983:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19984:         $chunk .=
                   19985:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19986:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19987:         $plaintext .= $chunk;
                   19988:     }
1.1174    raeburn  19989:     return $plaintext;
                   19990: }
                   19991: 
1.1344    raeburn  19992: sub get_requested_shorturls {
1.1309    raeburn  19993:     my ($cdom,$cnum,$navmap) = @_;
                   19994:     return unless (ref($navmap));
1.1344    raeburn  19995:     my ($numnew,$errors);
1.1309    raeburn  19996:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19997:     if (@toshorten) {
                   19998:         my (%maps,%resources,%titles);
                   19999:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   20000:                                                                'shorturls',$cdom,$cnum);
                   20001:         if (keys(%resources)) {
1.1344    raeburn  20002:             my %tocreate;
1.1309    raeburn  20003:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   20004:                 my $symb = $resources{$item};
                   20005:                 if ($symb) {
                   20006:                     $tocreate{$cnum.'&'.$symb} = 1;
                   20007:                 }
                   20008:             }
1.1344    raeburn  20009:             if (keys(%tocreate)) {
                   20010:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   20011:                                                       \%tocreate);
                   20012:             }
1.1309    raeburn  20013:         }
1.1344    raeburn  20014:     }
                   20015:     return ($numnew,$errors);
                   20016: }
                   20017: 
                   20018: sub make_short_symbs {
                   20019:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   20020:     my ($numnew,@errors);
                   20021:     if (ref($tocreateref) eq 'HASH') {
                   20022:         my %tocreate = %{$tocreateref};
1.1309    raeburn  20023:         if (keys(%tocreate)) {
                   20024:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   20025:             my $su = Short::URL->new(no_vowels => 1);
                   20026:             my $init = '';
                   20027:             my (%newunique,%addcourse,%courseonly,%failed);
                   20028:             # get lock on tiny db
                   20029:             my $now = time;
1.1344    raeburn  20030:             if ($lockuser eq '') {
                   20031:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   20032:             }
1.1309    raeburn  20033:             my $lockhash = {
1.1344    raeburn  20034:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  20035:                             };
                   20036:             my $tries = 0;
                   20037:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   20038:             my ($code,$error);
                   20039:             while (($gotlock ne 'ok') && ($tries<3)) {
                   20040:                 $tries ++;
                   20041:                 sleep 1;
1.1319    raeburn  20042:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  20043:             }
                   20044:             if ($gotlock eq 'ok') {
                   20045:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   20046:                                        \%addcourse,\%courseonly,\%failed);
                   20047:                 if (keys(%failed)) {
                   20048:                     my $numfailed = scalar(keys(%failed));
                   20049:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   20050:                 }
                   20051:                 if (keys(%newunique)) {
                   20052:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   20053:                     if ($putres eq 'ok') {
                   20054:                         $numnew = scalar(keys(%newunique));
                   20055:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   20056:                         unless ($newputres eq 'ok') {
                   20057:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   20058:                         }
                   20059:                     } else {
                   20060:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   20061:                     }
                   20062:                 }
                   20063:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   20064:                 unless ($dellockres eq 'ok') {
                   20065:                     push(@errors,&mt('error: could not release lockfile'));
                   20066:                 }
                   20067:             } else {
                   20068:                 push(@errors,&mt('error: could not obtain lockfile'));
                   20069:             }
                   20070:             if (keys(%courseonly)) {
                   20071:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   20072:                 if ($result ne 'ok') {
                   20073:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   20074:                 }
                   20075:             }
                   20076:         }
                   20077:     }
                   20078:     return ($numnew,\@errors);
                   20079: }
                   20080: 
                   20081: sub shorten_symbs {
                   20082:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   20083:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   20084:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   20085:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   20086:     my (%possibles,%collisions);
                   20087:     foreach my $key (keys(%{$tocreate})) {
                   20088:         my $num = String::CRC32::crc32($key);
                   20089:         my $tiny = $su->encode($num,$init);
                   20090:         if ($tiny) {
                   20091:             $possibles{$tiny} = $key;
                   20092:         }
                   20093:     }
                   20094:     if (!$init) {
                   20095:         $init = 1;
                   20096:     } else {
                   20097:         $init ++;
                   20098:     }
                   20099:     if (keys(%possibles)) {
                   20100:         my @posstiny = keys(%possibles);
                   20101:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   20102:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   20103:         if (keys(%currtiny)) {
                   20104:             foreach my $key (keys(%currtiny)) {
                   20105:                 next if ($currtiny{$key} eq '');
                   20106:                 if ($currtiny{$key} eq $possibles{$key}) {
                   20107:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   20108:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20109:                         $courseonly->{$tsymb} = $key;
                   20110:                     }
                   20111:                 } else {
                   20112:                     $collisions{$possibles{$key}} = 1;
                   20113:                 }
                   20114:                 delete($possibles{$key});
                   20115:             }
                   20116:         }
                   20117:         foreach my $key (keys(%possibles)) {
                   20118:             $newunique->{$key} = $possibles{$key};
                   20119:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   20120:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   20121:                 $addcourse->{$tsymb} = $key;
                   20122:             }
                   20123:         }
                   20124:     }
                   20125:     if (keys(%collisions)) {
                   20126:         if ($init <5) {
                   20127:             if (!$init) {
                   20128:                 $init = 1;
                   20129:             } else {
                   20130:                 $init ++;
                   20131:             }
                   20132:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   20133:                                    $newunique,$addcourse,$courseonly,$failed);
                   20134:         } else {
                   20135:             foreach my $key (keys(%collisions)) {
                   20136:                 $failed->{$key} = 1;
                   20137:             }
                   20138:         }
                   20139:     }
                   20140:     return $init;
                   20141: }
                   20142: 
1.1328    raeburn  20143: sub is_nonframeable {
1.1329    raeburn  20144:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   20145:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  20146:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  20147: 
                   20148:     $remprotocol = lc($remprotocol);
                   20149:     $remhost = lc($remhost);
                   20150:     my $remport = 80;
                   20151:     if ($remprotocol eq 'https') {
                   20152:         $remport = 443;
                   20153:     }
1.1330    raeburn  20154:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  20155:     if ($cached) {
                   20156:         unless ($nocache) {
                   20157:             if ($result) {
                   20158:                 return 1;
                   20159:             } else {
                   20160:                 return 0;
                   20161:             }
                   20162:         }
                   20163:     }
1.1328    raeburn  20164:     my $uselink;
                   20165:     my $request = new HTTP::Request('HEAD',$url);
                   20166:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   20167:     if ($response->is_success()) {
                   20168:         my $secpolicy = lc($response->header('content-security-policy'));
                   20169:         my $xframeop = lc($response->header('x-frame-options'));
                   20170:         $secpolicy =~ s/^\s+|\s+$//g;
                   20171:         $xframeop =~ s/^\s+|\s+$//g;
                   20172:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20173:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20174:             my ($origin,$protocol,$port);
                   20175:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20176:                 $port = $ENV{'SERVER_PORT'};
                   20177:             } else {
                   20178:                 $port = 80;
                   20179:             }
                   20180:             if ($absolute eq '') {
                   20181:                 $protocol = 'http:';
                   20182:                 if ($port == 443) {
                   20183:                     $protocol = 'https:';
                   20184:                 }
                   20185:                 $origin = $protocol.'//'.lc($hostname);
                   20186:             } else {
                   20187:                 $origin = lc($absolute);
                   20188:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20189:             }
                   20190:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20191:                 my $framepolicy = $1;
                   20192:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20193:                 my @policies = split(/\s+/,$framepolicy);
                   20194:                 if (@policies) {
                   20195:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20196:                         $uselink = 1;
                   20197:                     } else {
                   20198:                         $uselink = 1;
                   20199:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20200:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20201:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20202:                             undef($uselink);
                   20203:                         }
                   20204:                         if ($uselink) {
                   20205:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20206:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20207:                                     undef($uselink);
                   20208:                                 }
                   20209:                             }
                   20210:                         }
                   20211:                         if ($uselink) {
                   20212:                             my @possok;
                   20213:                             if ($ip ne '') {
                   20214:                                 push(@possok,$ip);
                   20215:                             }
                   20216:                             my $hoststr = '';
                   20217:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20218:                                 if ($hoststr eq '') {
                   20219:                                     $hoststr = $part;
                   20220:                                 } else {
                   20221:                                     $hoststr = "$part.$hoststr";
                   20222:                                 }
                   20223:                                 if ($hoststr eq $hostname) {
                   20224:                                     push(@possok,$hostname);
                   20225:                                 } else {
                   20226:                                     push(@possok,"*.$hoststr");
                   20227:                                 }
                   20228:                             }
                   20229:                             if (@possok) {
                   20230:                                 foreach my $poss (@possok) {
                   20231:                                     last if (!$uselink);
                   20232:                                     foreach my $policy (@policies) {
                   20233:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20234:                                             undef($uselink);
                   20235:                                             last;
                   20236:                                         }
                   20237:                                     }
                   20238:                                 }
                   20239:                             }
                   20240:                         }
                   20241:                     }
                   20242:                 }
                   20243:             } elsif ($xframeop ne '') {
                   20244:                 $uselink = 1;
                   20245:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20246:                 if (@policies) {
                   20247:                     unless (grep(/^deny$/,@policies)) {
                   20248:                         if ($origin ne '') {
                   20249:                             if (grep(/^sameorigin$/,@policies)) {
                   20250:                                 if ($remotehost eq $origin) {
                   20251:                                     undef($uselink);
                   20252:                                 }
                   20253:                             }
                   20254:                             if ($uselink) {
                   20255:                                 foreach my $policy (@policies) {
                   20256:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20257:                                         my $allowfrom = $1;
                   20258:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20259:                                             undef($uselink);
                   20260:                                             last;
                   20261:                                         }
                   20262:                                     }
                   20263:                                 }
                   20264:                             }
                   20265:                         }
                   20266:                     }
                   20267:                 }
                   20268:             }
                   20269:         }
                   20270:     }
1.1329    raeburn  20271:     if ($nocache) {
                   20272:         if ($cached) {
                   20273:             my $devalidate;
                   20274:             if ($uselink && !$result) {
                   20275:                 $devalidate = 1;
                   20276:             } elsif (!$uselink && $result) {
                   20277:                 $devalidate = 1;
                   20278:             }
                   20279:             if ($devalidate) {
                   20280:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20281:             }
                   20282:         }
                   20283:     } else {
                   20284:         if ($uselink) {
                   20285:             $result = 1;
                   20286:         } else {
                   20287:             $result = 0;
                   20288:         }
                   20289:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20290:     }
1.1328    raeburn  20291:     return $uselink;
                   20292: }
                   20293: 
1.1359    raeburn  20294: sub page_menu {
                   20295:     my ($menucolls,$menunum) = @_;
                   20296:     my %menu;
                   20297:     foreach my $item (split(/;/,$menucolls)) {
                   20298:         my ($num,$value) = split(/\%/,$item);
                   20299:         if ($num eq $menunum) {
                   20300:             my @entries = split(/\&/,$value);
                   20301:             foreach my $entry (@entries) {
                   20302:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20303:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20304:                     $menu{$name} = $fields;
                   20305:                 } else {
                   20306:                     my @shown;
                   20307:                     if ($fields =~ /,/) {
                   20308:                         @shown = split(/,/,$fields);
                   20309:                     } else {
                   20310:                         @shown = ($fields);
                   20311:                     }
                   20312:                     if (@shown) {
                   20313:                         foreach my $field (@shown) {
                   20314:                             next if ($field eq '');
                   20315:                             $menu{$field} = 1;
                   20316:                         }
                   20317:                     }
                   20318:                 }
                   20319:             }
                   20320:         }
                   20321:     }
                   20322:     return %menu;
                   20323: }
                   20324: 
1.112     bowersj2 20325: 1;
                   20326: __END__;
1.41      ng       20327: 

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