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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.161.  .14(raeb    4:-23): # $Id: loncommon.pm,v 1.1075.2.161.2.13 2023/01/20 19:17:23 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.1075.2.161.  .7(raebu   64:22): 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.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1075.2.161.  .13(raeb   74:-23): use LONCAPA::map();
1.1075.2.135  raeburn    75: use HTTP::Request;
1.657     raeburn    76: use DateTime::TimeZone;
1.1075.2.102  raeburn    77: use DateTime::Locale;
1.1075.2.94  raeburn    78: use Encode();
1.1075.2.14  raeburn    79: use Authen::Captcha;
                     80: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    81: use JSON::DWIW;
                     82: use LWP::UserAgent;
1.1075.2.64  raeburn    83: use Crypt::DES;
                     84: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    85: use File::Copy();
                     86: use File::Path();
1.1075.2.161.  .1(raebu   87:21): use String::CRC32();
                     88:21): use Short::URL();
1.117     www        89: 
1.517     raeburn    90: # ---------------------------------------------- Designs
                     91: use vars qw(%defaultdesign);
                     92: 
1.22      www        93: my $readit;
                     94: 
1.517     raeburn    95: 
1.157     matthew    96: ##
                     97: ## Global Variables
                     98: ##
1.46      matthew    99: 
1.643     foxr      100: 
                    101: # ----------------------------------------------- SSI with retries:
                    102: #
                    103: 
                    104: =pod
                    105: 
1.648     raeburn   106: =head1 Server Side include with retries:
1.643     foxr      107: 
                    108: =over 4
                    109: 
1.648     raeburn   110: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      111: 
                    112: Performs an ssi with some number of retries.  Retries continue either
                    113: until the result is ok or until the retry count supplied by the
                    114: caller is exhausted.  
                    115: 
                    116: Inputs:
1.648     raeburn   117: 
                    118: =over 4
                    119: 
1.643     foxr      120: resource   - Identifies the resource to insert.
1.648     raeburn   121: 
1.643     foxr      122: retries    - Count of the number of retries allowed.
1.648     raeburn   123: 
1.643     foxr      124: form       - Hash that identifies the rendering options.
                    125: 
1.648     raeburn   126: =back
                    127: 
                    128: Returns:
                    129: 
                    130: =over 4
                    131: 
1.643     foxr      132: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   133: 
1.643     foxr      134: response   - The response from the last attempt (which may or may not have been successful.
                    135: 
1.648     raeburn   136: =back
                    137: 
                    138: =back
                    139: 
1.643     foxr      140: =cut
                    141: 
                    142: sub ssi_with_retries {
                    143:     my ($resource, $retries, %form) = @_;
                    144: 
                    145: 
                    146:     my $ok = 0;			# True if we got a good response.
                    147:     my $content;
                    148:     my $response;
                    149: 
                    150:     # Try to get the ssi done. within the retries count:
                    151: 
                    152:     do {
                    153: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    154: 	$ok      = $response->is_success;
1.650     www       155:         if (!$ok) {
                    156:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    157:         }
1.643     foxr      158: 	$retries--;
                    159:     } while (!$ok && ($retries > 0));
                    160: 
                    161:     if (!$ok) {
                    162: 	$content = '';		# On error return an empty content.
                    163:     }
                    164:     return ($content, $response);
                    165: 
                    166: }
                    167: 
                    168: 
                    169: 
1.20      www       170: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  171: my %language;
1.124     www       172: my %supported_language;
1.1048    foxr      173: my %latex_language;		# For choosing hyphenation in <transl..>
                    174: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  175: my %cprtag;
1.192     taceyjo1  176: my %scprtag;
1.351     www       177: my %fe; my %fd; my %fm;
1.41      ng        178: my %category_extensions;
1.12      harris41  179: 
1.46      matthew   180: # ---------------------------------------------- Thesaurus variables
1.144     matthew   181: #
                    182: # %Keywords:
                    183: #      A hash used by &keyword to determine if a word is considered a keyword.
                    184: # $thesaurus_db_file 
                    185: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   186: 
                    187: my %Keywords;
                    188: my $thesaurus_db_file;
                    189: 
1.144     matthew   190: #
                    191: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    192: # thesaurus.tab, and filecategories.tab.
                    193: #
1.18      www       194: BEGIN {
1.46      matthew   195:     # Variable initialization
                    196:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    197:     #
1.22      www       198:     unless ($readit) {
1.12      harris41  199: # ------------------------------------------------------------------- languages
                    200:     {
1.158     raeburn   201:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    202:                                    '/language.tab';
1.1075.2.128  raeburn   203:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  204:             while (my $line = <$fh>) {
                    205:                 next if ($line=~/^\#/);
                    206:                 chomp($line);
1.1048    foxr      207:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   208:                 $language{$key}=$val.' - '.$enc;
                    209:                 if ($sup) {
                    210:                     $supported_language{$key}=$sup;
                    211:                 }
1.1048    foxr      212: 		if ($latex) {
                    213: 		    $latex_language_bykey{$key} = $latex;
                    214: 		    $latex_language{$two} = $latex;
                    215: 		}
1.158     raeburn   216:             }
                    217:             close($fh);
                    218:         }
1.12      harris41  219:     }
                    220: # ------------------------------------------------------------------ copyrights
                    221:     {
1.158     raeburn   222:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    223:                                   '/copyright.tab';
1.1075.2.128  raeburn   224:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  225:             while (my $line = <$fh>) {
                    226:                 next if ($line=~/^\#/);
                    227:                 chomp($line);
                    228:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   229:                 $cprtag{$key}=$val;
                    230:             }
                    231:             close($fh);
                    232:         }
1.12      harris41  233:     }
1.351     www       234: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  235:     {
                    236:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    237:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   238:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  239:             while (my $line = <$fh>) {
                    240:                 next if ($line =~ /^\#/);
                    241:                 chomp($line);
                    242:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  243:                 $scprtag{$key}=$val;
                    244:             }
                    245:             close($fh);
                    246:         }
                    247:     }
1.63      www       248: 
1.517     raeburn   249: # -------------------------------------------------------------- default domain designs
1.63      www       250:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   251:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   252:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   253:         while (my $line = <$fh>) {
                    254:             next if ($line =~ /^\#/);
                    255:             chomp($line);
                    256:             my ($key,$val)=(split(/\=/,$line));
                    257:             if ($val) { $defaultdesign{$key}=$val; }
                    258:         }
                    259:         close($fh);
1.63      www       260:     }
                    261: 
1.15      harris41  262: # ------------------------------------------------------------- file categories
                    263:     {
1.158     raeburn   264:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    265:                                   '/filecategories.tab';
1.1075.2.128  raeburn   266:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  267: 	    while (my $line = <$fh>) {
                    268: 		next if ($line =~ /^\#/);
                    269: 		chomp($line);
                    270:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   271:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   272:             }
                    273:             close($fh);
                    274:         }
                    275: 
1.15      harris41  276:     }
1.12      harris41  277: # ------------------------------------------------------------------ file types
                    278:     {
1.158     raeburn   279:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    280:                '/filetypes.tab';
1.1075.2.128  raeburn   281:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  282:             while (my $line = <$fh>) {
                    283: 		next if ($line =~ /^\#/);
                    284: 		chomp($line);
                    285:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   286:                 if ($descr ne '') {
                    287:                     $fe{$ending}=lc($emb);
                    288:                     $fd{$ending}=$descr;
1.351     www       289:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   290:                 }
                    291:             }
                    292:             close($fh);
                    293:         }
1.12      harris41  294:     }
1.22      www       295:     &Apache::lonnet::logthis(
1.705     tempelho  296:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       297:     $readit=1;
1.46      matthew   298:     }  # end of unless($readit) 
1.32      matthew   299:     
                    300: }
1.112     bowersj2  301: 
1.42      matthew   302: ###############################################################
                    303: ##           HTML and Javascript Helper Functions            ##
                    304: ###############################################################
                    305: 
                    306: =pod 
                    307: 
1.112     bowersj2  308: =head1 HTML and Javascript Functions
1.42      matthew   309: 
1.112     bowersj2  310: =over 4
                    311: 
1.648     raeburn   312: =item * &browser_and_searcher_javascript()
1.112     bowersj2  313: 
                    314: X<browsing, javascript>X<searching, javascript>Returns a string
                    315: containing javascript with two functions, C<openbrowser> and
                    316: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    317: tags.
1.42      matthew   318: 
1.648     raeburn   319: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   320: 
                    321: inputs: formname, elementname, only, omit
                    322: 
                    323: formname and elementname indicate the name of the html form and name of
                    324: the element that the results of the browsing selection are to be placed in. 
                    325: 
                    326: Specifying 'only' will restrict the browser to displaying only files
1.185     www       327: with the given extension.  Can be a comma separated list.
1.42      matthew   328: 
                    329: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       330: with the given extension.  Can be a comma separated list.
1.42      matthew   331: 
1.648     raeburn   332: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   333: 
                    334: Inputs: formname, elementname
                    335: 
                    336: formname and elementname specify the name of the html form and the name
                    337: of the element the selection from the search results will be placed in.
1.542     raeburn   338: 
1.42      matthew   339: =cut
                    340: 
                    341: sub browser_and_searcher_javascript {
1.199     albertel  342:     my ($mode)=@_;
                    343:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  344:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   345:     return <<END;
1.219     albertel  346: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   347:     var editbrowser = null;
1.135     albertel  348:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       349:         var url = '$resurl/?';
1.42      matthew   350:         if (editbrowser == null) {
                    351:             url += 'launch=1&';
                    352:         }
                    353:         url += 'catalogmode=interactive&';
1.199     albertel  354:         url += 'mode=$mode&';
1.611     albertel  355:         url += 'inhibitmenu=yes&';
1.42      matthew   356:         url += 'form=' + formname + '&';
                    357:         if (only != null) {
                    358:             url += 'only=' + only + '&';
1.217     albertel  359:         } else {
                    360:             url += 'only=&';
                    361: 	}
1.42      matthew   362:         if (omit != null) {
                    363:             url += 'omit=' + omit + '&';
1.217     albertel  364:         } else {
                    365:             url += 'omit=&';
                    366: 	}
1.135     albertel  367:         if (titleelement != null) {
                    368:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  369:         } else {
                    370: 	    url += 'titleelement=&';
                    371: 	}
1.42      matthew   372:         url += 'element=' + elementname + '';
                    373:         var title = 'Browser';
1.435     albertel  374:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   375:         options += ',width=700,height=600';
                    376:         editbrowser = open(url,title,options,'1');
                    377:         editbrowser.focus();
                    378:     }
                    379:     var editsearcher;
1.135     albertel  380:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   381:         var url = '/adm/searchcat?';
                    382:         if (editsearcher == null) {
                    383:             url += 'launch=1&';
                    384:         }
                    385:         url += 'catalogmode=interactive&';
1.199     albertel  386:         url += 'mode=$mode&';
1.42      matthew   387:         url += 'form=' + formname + '&';
1.135     albertel  388:         if (titleelement != null) {
                    389:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  390:         } else {
                    391: 	    url += 'titleelement=&';
                    392: 	}
1.42      matthew   393:         url += 'element=' + elementname + '';
                    394:         var title = 'Search';
1.435     albertel  395:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   396:         options += ',width=700,height=600';
                    397:         editsearcher = open(url,title,options,'1');
                    398:         editsearcher.focus();
                    399:     }
1.219     albertel  400: // END LON-CAPA Internal -->
1.42      matthew   401: END
1.170     www       402: }
                    403: 
                    404: sub lastresurl {
1.258     albertel  405:     if ($env{'environment.lastresurl'}) {
                    406: 	return $env{'environment.lastresurl'}
1.170     www       407:     } else {
                    408: 	return '/res';
                    409:     }
                    410: }
                    411: 
                    412: sub storeresurl {
                    413:     my $resurl=&Apache::lonnet::clutter(shift);
                    414:     unless ($resurl=~/^\/res/) { return 0; }
                    415:     $resurl=~s/\/$//;
                    416:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   417:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       418:     return 1;
1.42      matthew   419: }
                    420: 
1.74      www       421: sub studentbrowser_javascript {
1.111     www       422:    unless (
1.258     albertel  423:             (($env{'request.course.id'}) && 
1.302     albertel  424:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    425: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    426: 					  '/'.$env{'request.course.sec'})
                    427: 	      ))
1.258     albertel  428:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       429:           ) { return ''; }  
1.74      www       430:    return (<<'ENDSTDBRW');
1.776     bisitz    431: <script type="text/javascript" language="Javascript">
1.824     bisitz    432: // <![CDATA[
1.74      www       433:     var stdeditbrowser;
1.1075.2.143  raeburn   434:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv) {
1.74      www       435:         var url = '/adm/pickstudent?';
                    436:         var filter;
1.558     albertel  437: 	if (!ignorefilter) {
                    438: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    439: 	}
1.74      www       440:         if (filter != null) {
                    441:            if (filter != '') {
                    442:                url += 'filter='+filter+'&';
                    443: 	   }
                    444:         }
                    445:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       446:                                     '&udomelement='+udom+
                    447:                                     '&clicker='+clicker;
1.111     www       448: 	if (roleflag) { url+="&roles=1"; }
1.1075.2.143  raeburn   449:         if (courseadv == 'condition') {
                    450:             if (document.getElementById('courseadv')) {
                    451:                 courseadv = document.getElementById('courseadv').value;
                    452:             }
                    453:         }
                    454:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.102     www       455:         var title = 'Student_Browser';
1.74      www       456:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    457:         options += ',width=700,height=600';
                    458:         stdeditbrowser = open(url,title,options,'1');
                    459:         stdeditbrowser.focus();
                    460:     }
1.824     bisitz    461: // ]]>
1.74      www       462: </script>
                    463: ENDSTDBRW
                    464: }
1.42      matthew   465: 
1.1003    www       466: sub resourcebrowser_javascript {
                    467:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       468:    return (<<'ENDRESBRW');
1.1003    www       469: <script type="text/javascript" language="Javascript">
                    470: // <![CDATA[
                    471:     var reseditbrowser;
1.1004    www       472:     function openresbrowser(formname,reslink) {
1.1005    www       473:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       474:         var title = 'Resource_Browser';
                    475:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       476:         options += ',width=700,height=500';
1.1004    www       477:         reseditbrowser = open(url,title,options,'1');
                    478:         reseditbrowser.focus();
1.1003    www       479:     }
                    480: // ]]>
                    481: </script>
1.1004    www       482: ENDRESBRW
1.1003    www       483: }
                    484: 
1.74      www       485: sub selectstudent_link {
1.1075.2.143  raeburn   486:    my ($form,$unameele,$udomele,$courseadv,$clickerid)=@_;
1.999     www       487:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    488:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    489:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  490:    if ($env{'request.course.id'}) {  
1.302     albertel  491:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    492: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    493: 					'/'.$env{'request.course.sec'})) {
1.111     www       494: 	   return '';
                    495:        }
1.999     www       496:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1075.2.143  raeburn   497:        if ($courseadv eq 'only') {
                    498:            $callargs .= ",'',1,'$courseadv'";
                    499:        } elsif ($courseadv eq 'none') {
                    500:            $callargs .= ",'','','$courseadv'";
                    501:        } elsif ($courseadv eq 'condition') {
                    502:            $callargs .= ",'','','$courseadv'";
1.793     raeburn   503:        }
                    504:        return '<span class="LC_nobreak">'.
                    505:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    506:               &mt('Select User').'</a></span>';
1.74      www       507:    }
1.258     albertel  508:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       509:        $callargs .= ",'',1"; 
1.793     raeburn   510:        return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    512:               &mt('Select User').'</a></span>';
1.111     www       513:    }
                    514:    return '';
1.91      www       515: }
                    516: 
1.1004    www       517: sub selectresource_link {
                    518:    my ($form,$reslink,$arg)=@_;
                    519:    
                    520:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    521:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    522:    unless ($env{'request.course.id'}) { return $arg; }
                    523:    return '<span class="LC_nobreak">'.
                    524:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    525:               $arg.'</a></span>';
                    526: }
                    527: 
                    528: 
                    529: 
1.653     raeburn   530: sub authorbrowser_javascript {
                    531:     return <<"ENDAUTHORBRW";
1.776     bisitz    532: <script type="text/javascript" language="JavaScript">
1.824     bisitz    533: // <![CDATA[
1.653     raeburn   534: var stdeditbrowser;
                    535: 
                    536: function openauthorbrowser(formname,udom) {
                    537:     var url = '/adm/pickauthor?';
                    538:     url += 'form='+formname+'&roledom='+udom;
                    539:     var title = 'Author_Browser';
                    540:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    541:     options += ',width=700,height=600';
                    542:     stdeditbrowser = open(url,title,options,'1');
                    543:     stdeditbrowser.focus();
                    544: }
                    545: 
1.824     bisitz    546: // ]]>
1.653     raeburn   547: </script>
                    548: ENDAUTHORBRW
                    549: }
                    550: 
1.91      www       551: sub coursebrowser_javascript {
1.1075.2.31  raeburn   552:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   553:         $credits_element,$instcode) = @_;
1.932     raeburn   554:     my $wintitle = 'Course_Browser';
1.931     raeburn   555:     if ($crstype eq 'Community') {
1.932     raeburn   556:         $wintitle = 'Community_Browser';
1.909     raeburn   557:     }
1.876     raeburn   558:     my $id_functions = &javascript_index_functions();
                    559:     my $output = '
1.776     bisitz    560: <script type="text/javascript" language="JavaScript">
1.824     bisitz    561: // <![CDATA[
1.468     raeburn   562:     var stdeditbrowser;'."\n";
1.876     raeburn   563: 
                    564:     $output .= <<"ENDSTDBRW";
1.909     raeburn   565:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       566:         var url = '/adm/pickcourse?';
1.895     raeburn   567:         var formid = getFormIdByName(formname);
1.876     raeburn   568:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  569:         if (domainfilter != null) {
                    570:            if (domainfilter != '') {
                    571:                url += 'domainfilter='+domainfilter+'&';
                    572: 	   }
                    573:         }
1.91      www       574:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  575: 	                            '&cdomelement='+udom+
                    576:                                     '&cnameelement='+desc;
1.468     raeburn   577:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   578:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   579:                 url += '&roleelement='+extra_element;
                    580:                 if (domainfilter == null || domainfilter == '') {
                    581:                     url += '&domainfilter='+extra_element;
                    582:                 }
1.234     raeburn   583:             }
1.468     raeburn   584:             else {
                    585:                 if (formname == 'portform') {
                    586:                     url += '&setroles='+extra_element;
1.800     raeburn   587:                 } else {
                    588:                     if (formname == 'rules') {
                    589:                         url += '&fixeddom='+extra_element; 
                    590:                     }
1.468     raeburn   591:                 }
                    592:             }     
1.230     raeburn   593:         }
1.909     raeburn   594:         if (type != null && type != '') {
                    595:             url += '&type='+type;
                    596:         }
                    597:         if (type_elem != null && type_elem != '') {
                    598:             url += '&typeelement='+type_elem;
                    599:         }
1.872     raeburn   600:         if (formname == 'ccrs') {
                    601:             var ownername = document.forms[formid].ccuname.value;
                    602:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   603:             url += '&cloner='+ownername+':'+ownerdom;
                    604:             if (type == 'Course') {
                    605:                 url += '&crscode='+document.forms[formid].crscode.value;
                    606:             }
1.1075.2.95  raeburn   607:         }
                    608:         if (formname == 'requestcrs') {
                    609:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   610:         }
1.293     raeburn   611:         if (multflag !=null && multflag != '') {
                    612:             url += '&multiple='+multflag;
                    613:         }
1.909     raeburn   614:         var title = '$wintitle';
1.91      www       615:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    616:         options += ',width=700,height=600';
                    617:         stdeditbrowser = open(url,title,options,'1');
                    618:         stdeditbrowser.focus();
                    619:     }
1.876     raeburn   620: $id_functions
                    621: ENDSTDBRW
1.1075.2.31  raeburn   622:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    623:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    624:                                       $credits_element);
1.876     raeburn   625:     }
                    626:     $output .= '
                    627: // ]]>
                    628: </script>';
                    629:     return $output;
                    630: }
                    631: 
                    632: sub javascript_index_functions {
                    633:     return <<"ENDJS";
                    634: 
                    635: function getFormIdByName(formname) {
                    636:     for (var i=0;i<document.forms.length;i++) {
                    637:         if (document.forms[i].name == formname) {
                    638:             return i;
                    639:         }
                    640:     }
                    641:     return -1;
                    642: }
                    643: 
                    644: function getIndexByName(formid,item) {
                    645:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    646:         if (document.forms[formid].elements[i].name == item) {
                    647:             return i;
                    648:         }
                    649:     }
                    650:     return -1;
                    651: }
1.468     raeburn   652: 
1.876     raeburn   653: function getDomainFromSelectbox(formname,udom) {
                    654:     var userdom;
                    655:     var formid = getFormIdByName(formname);
                    656:     if (formid > -1) {
                    657:         var domid = getIndexByName(formid,udom);
                    658:         if (domid > -1) {
                    659:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    660:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    661:             }
                    662:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    663:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   664:             }
                    665:         }
                    666:     }
1.876     raeburn   667:     return userdom;
                    668: }
                    669: 
                    670: ENDJS
1.468     raeburn   671: 
1.876     raeburn   672: }
                    673: 
1.1017    raeburn   674: sub javascript_array_indexof {
1.1018    raeburn   675:     return <<ENDJS;
1.1017    raeburn   676: <script type="text/javascript" language="JavaScript">
                    677: // <![CDATA[
                    678: 
                    679: if (!Array.prototype.indexOf) {
                    680:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    681:         "use strict";
                    682:         if (this === void 0 || this === null) {
                    683:             throw new TypeError();
                    684:         }
                    685:         var t = Object(this);
                    686:         var len = t.length >>> 0;
                    687:         if (len === 0) {
                    688:             return -1;
                    689:         }
                    690:         var n = 0;
                    691:         if (arguments.length > 0) {
                    692:             n = Number(arguments[1]);
                    693:             if (n !== n) { // shortcut for verifying if it's NaN
                    694:                 n = 0;
                    695:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    696:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    697:             }
                    698:         }
                    699:         if (n >= len) {
                    700:             return -1;
                    701:         }
                    702:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    703:         for (; k < len; k++) {
                    704:             if (k in t && t[k] === searchElement) {
                    705:                 return k;
                    706:             }
                    707:         }
                    708:         return -1;
                    709:     }
                    710: }
                    711: 
                    712: // ]]>
                    713: </script>
                    714: 
                    715: ENDJS
                    716: 
                    717: }
                    718: 
1.876     raeburn   719: sub userbrowser_javascript {
                    720:     my $id_functions = &javascript_index_functions();
                    721:     return <<"ENDUSERBRW";
                    722: 
1.888     raeburn   723: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   724:     var url = '/adm/pickuser?';
                    725:     var userdom = getDomainFromSelectbox(formname,udom);
                    726:     if (userdom != null) {
                    727:        if (userdom != '') {
                    728:            url += 'srchdom='+userdom+'&';
                    729:        }
                    730:     }
                    731:     url += 'form=' + formname + '&unameelement='+uname+
                    732:                                 '&udomelement='+udom+
                    733:                                 '&ulastelement='+ulast+
                    734:                                 '&ufirstelement='+ufirst+
                    735:                                 '&uemailelement='+uemail+
1.881     raeburn   736:                                 '&hideudomelement='+hideudom+
                    737:                                 '&coursedom='+crsdom;
1.888     raeburn   738:     if ((caller != null) && (caller != undefined)) {
                    739:         url += '&caller='+caller;
                    740:     }
1.876     raeburn   741:     var title = 'User_Browser';
                    742:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    743:     options += ',width=700,height=600';
                    744:     var stdeditbrowser = open(url,title,options,'1');
                    745:     stdeditbrowser.focus();
                    746: }
                    747: 
1.888     raeburn   748: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   749:     var formid = getFormIdByName(formname);
                    750:     if (formid > -1) {
1.888     raeburn   751:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   752:         var domid = getIndexByName(formid,udom);
                    753:         var hidedomid = getIndexByName(formid,origdom);
                    754:         if (hidedomid > -1) {
                    755:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   756:             var unameval = document.forms[formid].elements[unameid].value;
                    757:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    758:                 if (domid > -1) {
                    759:                     var slct = document.forms[formid].elements[domid];
                    760:                     if (slct.type == 'select-one') {
                    761:                         var i;
                    762:                         for (i=0;i<slct.length;i++) {
                    763:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    764:                         }
                    765:                     }
                    766:                     if (slct.type == 'hidden') {
                    767:                         slct.value = fixeddom;
1.876     raeburn   768:                     }
                    769:                 }
1.468     raeburn   770:             }
                    771:         }
                    772:     }
1.876     raeburn   773:     return;
                    774: }
                    775: 
                    776: $id_functions
                    777: ENDUSERBRW
1.468     raeburn   778: }
                    779: 
                    780: sub setsec_javascript {
1.1075.2.31  raeburn   781:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   782:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    783:         $communityrolestr);
                    784:     if ($role_element ne '') {
                    785:         my @allroles = ('st','ta','ep','in','ad');
                    786:         foreach my $crstype ('Course','Community') {
                    787:             if ($crstype eq 'Community') {
                    788:                 foreach my $role (@allroles) {
                    789:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    790:                 }
                    791:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    792:             } else {
                    793:                 foreach my $role (@allroles) {
                    794:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    795:                 }
                    796:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    797:             }
                    798:         }
                    799:         $rolestr = '"'.join('","',@allroles).'"';
                    800:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    801:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    802:     }
1.468     raeburn   803:     my $setsections = qq|
                    804: function setSect(sectionlist) {
1.629     raeburn   805:     var sectionsArray = new Array();
                    806:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    807:         sectionsArray = sectionlist.split(",");
                    808:     }
1.468     raeburn   809:     var numSections = sectionsArray.length;
                    810:     document.$formname.$sec_element.length = 0;
                    811:     if (numSections == 0) {
                    812:         document.$formname.$sec_element.multiple=false;
                    813:         document.$formname.$sec_element.size=1;
                    814:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    815:     } else {
                    816:         if (numSections == 1) {
                    817:             document.$formname.$sec_element.multiple=false;
                    818:             document.$formname.$sec_element.size=1;
                    819:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    820:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    821:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    822:         } else {
                    823:             for (var i=0; i<numSections; i++) {
                    824:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    825:             }
                    826:             document.$formname.$sec_element.multiple=true
                    827:             if (numSections < 3) {
                    828:                 document.$formname.$sec_element.size=numSections;
                    829:             } else {
                    830:                 document.$formname.$sec_element.size=3;
                    831:             }
                    832:             document.$formname.$sec_element.options[0].selected = false
                    833:         }
                    834:     }
1.91      www       835: }
1.905     raeburn   836: 
                    837: function setRole(crstype) {
1.468     raeburn   838: |;
1.905     raeburn   839:     if ($role_element eq '') {
                    840:         $setsections .= '    return;
                    841: }
                    842: ';
                    843:     } else {
                    844:         $setsections .= qq|
                    845:     var elementLength = document.$formname.$role_element.length;
                    846:     var allroles = Array($rolestr);
                    847:     var courserolenames = Array($courserolestr);
                    848:     var communityrolenames = Array($communityrolestr);
                    849:     if (elementLength != undefined) {
                    850:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    851:             if (crstype == 'Course') {
                    852:                 return;
                    853:             } else {
                    854:                 allroles[5] = 'co';
                    855:                 for (var i=0; i<6; i++) {
                    856:                     document.$formname.$role_element.options[i].value = allroles[i];
                    857:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    858:                 }
                    859:             }
                    860:         } else {
                    861:             if (crstype == 'Community') {
                    862:                 return;
                    863:             } else {
                    864:                 allroles[5] = 'cc';
                    865:                 for (var i=0; i<6; i++) {
                    866:                     document.$formname.$role_element.options[i].value = allroles[i];
                    867:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    868:                 }
                    869:             }
                    870:         }
                    871:     }
                    872:     return;
                    873: }
                    874: |;
                    875:     }
1.1075.2.31  raeburn   876:     if ($credits_element) {
                    877:         $setsections .= qq|
                    878: function setCredits(defaultcredits) {
                    879:     document.$formname.$credits_element.value = defaultcredits;
                    880:     return;
                    881: }
                    882: |;
                    883:     }
1.468     raeburn   884:     return $setsections;
                    885: }
                    886: 
1.91      www       887: sub selectcourse_link {
1.909     raeburn   888:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    889:        $typeelement) = @_;
                    890:    my $type = $selecttype;
1.871     raeburn   891:    my $linktext = &mt('Select Course');
                    892:    if ($selecttype eq 'Community') {
1.909     raeburn   893:        $linktext = &mt('Select Community');
1.906     raeburn   894:    } elsif ($selecttype eq 'Course/Community') {
                    895:        $linktext = &mt('Select Course/Community');
1.909     raeburn   896:        $type = '';
1.1019    raeburn   897:    } elsif ($selecttype eq 'Select') {
                    898:        $linktext = &mt('Select');
                    899:        $type = '';
1.871     raeburn   900:    }
1.787     bisitz    901:    return '<span class="LC_nobreak">'
                    902:          ."<a href='"
                    903:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    904:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   905:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   906:          ."'>".$linktext.'</a>'
1.787     bisitz    907:          .'</span>';
1.74      www       908: }
1.42      matthew   909: 
1.653     raeburn   910: sub selectauthor_link {
                    911:    my ($form,$udom)=@_;
                    912:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    913:           &mt('Select Author').'</a>';
                    914: }
                    915: 
1.876     raeburn   916: sub selectuser_link {
1.881     raeburn   917:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   918:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   919:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   920:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   921:            ');">'.$linktext.'</a>';
1.876     raeburn   922: }
                    923: 
1.273     raeburn   924: sub check_uncheck_jscript {
                    925:     my $jscript = <<"ENDSCRT";
                    926: function checkAll(field) {
                    927:     if (field.length > 0) {
                    928:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   929:             if (!field[i].disabled) {
                    930:                 field[i].checked = true;
                    931:             }
1.273     raeburn   932:         }
                    933:     } else {
1.1075.2.14  raeburn   934:         if (!field.disabled) {
                    935:             field.checked = true;
                    936:         }
1.273     raeburn   937:     }
                    938: }
                    939:  
                    940: function uncheckAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
                    943:             field[i].checked = false ;
1.543     albertel  944:         }
                    945:     } else {
1.273     raeburn   946:         field.checked = false ;
                    947:     }
                    948: }
                    949: ENDSCRT
                    950:     return $jscript;
                    951: }
                    952: 
1.656     www       953: sub select_timezone {
1.1075.2.161.  .10(raeb  954:-22):    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    955:-22):    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   956:    if ($includeempty) {
                    957:        $output .= '<option value=""';
                    958:        if (($selected eq '') || ($selected eq 'local')) {
                    959:            $output .= ' selected="selected" ';
                    960:        }
                    961:        $output .= '> </option>';
                    962:    }
1.657     raeburn   963:    my @timezones = DateTime::TimeZone->all_names;
                    964:    foreach my $tzone (@timezones) {
                    965:        $output.= '<option value="'.$tzone.'"';
                    966:        if ($tzone eq $selected) {
                    967:            $output.=' selected="selected"';
                    968:        }
                    969:        $output.=">$tzone</option>\n";
1.656     www       970:    }
                    971:    $output.="</select>";
                    972:    return $output;
                    973: }
1.273     raeburn   974: 
1.687     raeburn   975: sub select_datelocale {
1.1075.2.115  raeburn   976:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    977:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   978:     if ($includeempty) {
                    979:         $output .= '<option value=""';
                    980:         if ($selected eq '') {
                    981:             $output .= ' selected="selected" ';
                    982:         }
                    983:         $output .= '> </option>';
                    984:     }
1.1075.2.102  raeburn   985:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   986:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   987:     my @locales = DateTime::Locale->ids();
                    988:     foreach my $id (@locales) {
                    989:         if ($id ne '') {
                    990:             my ($en_terr,$native_terr);
                    991:             my $loc = DateTime::Locale->load($id);
                    992:             if (ref($loc)) {
                    993:                 $en_terr = $loc->name();
                    994:                 $native_terr = $loc->native_name();
1.687     raeburn   995:                 if (grep(/^en$/,@languages) || !@languages) {
                    996:                     if ($en_terr ne '') {
                    997:                         $locale_names{$id} = '('.$en_terr.')';
                    998:                     } elsif ($native_terr ne '') {
                    999:                         $locale_names{$id} = $native_terr;
                   1000:                     }
                   1001:                 } else {
                   1002:                     if ($native_terr ne '') {
                   1003:                         $locale_names{$id} = $native_terr.' ';
                   1004:                     } elsif ($en_terr ne '') {
                   1005:                         $locale_names{$id} = '('.$en_terr.')';
                   1006:                     }
                   1007:                 }
1.1075.2.94  raeburn  1008:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn  1009:                 push(@possibles,$id);
1.687     raeburn  1010:             }
                   1011:         }
                   1012:     }
                   1013:     foreach my $item (sort(@possibles)) {
                   1014:         $output.= '<option value="'.$item.'"';
                   1015:         if ($item eq $selected) {
                   1016:             $output.=' selected="selected"';
                   1017:         }
                   1018:         $output.=">$item";
                   1019:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1020:             $output.='  '.$locale_names{$item};
1.687     raeburn  1021:         }
                   1022:         $output.="</option>\n";
                   1023:     }
                   1024:     $output.="</select>";
                   1025:     return $output;
                   1026: }
                   1027: 
1.792     raeburn  1028: sub select_language {
1.1075.2.115  raeburn  1029:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1030:     my %langchoices;
                   1031:     if ($includeempty) {
1.1075.2.32  raeburn  1032:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1033:     }
                   1034:     foreach my $id (&languageids()) {
                   1035:         my $code = &supportedlanguagecode($id);
                   1036:         if ($code) {
                   1037:             $langchoices{$code} = &plainlanguagedescription($id);
                   1038:         }
                   1039:     }
1.1075.2.32  raeburn  1040:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1041:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1042: }
                   1043: 
1.42      matthew  1044: =pod
1.36      matthew  1045: 
1.648     raeburn  1046: =item * &linked_select_forms(...)
1.36      matthew  1047: 
                   1048: linked_select_forms returns a string containing a <script></script> block
                   1049: and html for two <select> menus.  The select menus will be linked in that
                   1050: changing the value of the first menu will result in new values being placed
                   1051: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1052: order unless a defined order is provided.
1.36      matthew  1053: 
                   1054: linked_select_forms takes the following ordered inputs:
                   1055: 
                   1056: =over 4
                   1057: 
1.112     bowersj2 1058: =item * $formname, the name of the <form> tag
1.36      matthew  1059: 
1.112     bowersj2 1060: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1061: 
1.112     bowersj2 1062: =item * $firstdefault, the default value for the first menu
1.36      matthew  1063: 
1.112     bowersj2 1064: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1069: 
1.609     raeburn  1070: =item * $menuorder, the order of values in the first menu
                   1071: 
1.1075.2.31  raeburn  1072: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1073:         event for the first <select> tag
                   1074: 
                   1075: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1076:         event for the second <select> tag
                   1077: 
1.41      ng       1078: =back 
                   1079: 
1.36      matthew  1080: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1081: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1082: values for the first select menu.  The text that coincides with the 
1.41      ng       1083: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1084: and text for the second menu are given in the hash pointed to by 
                   1085: $menu{$choice1}->{'select2'}.  
                   1086: 
1.112     bowersj2 1087:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1088:                        default => "B3",
                   1089:                        select2 => { 
                   1090:                            B1 => "Choice B1",
                   1091:                            B2 => "Choice B2",
                   1092:                            B3 => "Choice B3",
                   1093:                            B4 => "Choice B4"
1.609     raeburn  1094:                            },
                   1095:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1096:                    },
                   1097:                A2 => { text =>"Choice A2" ,
                   1098:                        default => "C2",
                   1099:                        select2 => { 
                   1100:                            C1 => "Choice C1",
                   1101:                            C2 => "Choice C2",
                   1102:                            C3 => "Choice C3"
1.609     raeburn  1103:                            },
                   1104:                        order => ['C2','C1','C3'],
1.112     bowersj2 1105:                    },
                   1106:                A3 => { text =>"Choice A3" ,
                   1107:                        default => "D6",
                   1108:                        select2 => { 
                   1109:                            D1 => "Choice D1",
                   1110:                            D2 => "Choice D2",
                   1111:                            D3 => "Choice D3",
                   1112:                            D4 => "Choice D4",
                   1113:                            D5 => "Choice D5",
                   1114:                            D6 => "Choice D6",
                   1115:                            D7 => "Choice D7"
1.609     raeburn  1116:                            },
                   1117:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1118:                    }
                   1119:                );
1.36      matthew  1120: 
                   1121: =cut
                   1122: 
                   1123: sub linked_select_forms {
                   1124:     my ($formname,
                   1125:         $middletext,
                   1126:         $firstdefault,
                   1127:         $firstselectname,
                   1128:         $secondselectname, 
1.609     raeburn  1129:         $hashref,
                   1130:         $menuorder,
1.1075.2.31  raeburn  1131:         $onchangefirst,
                   1132:         $onchangesecond
1.36      matthew  1133:         ) = @_;
                   1134:     my $second = "document.$formname.$secondselectname";
                   1135:     my $first = "document.$formname.$firstselectname";
                   1136:     # output the javascript to do the changing
                   1137:     my $result = '';
1.776     bisitz   1138:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1139:     $result.="// <![CDATA[\n";
1.36      matthew  1140:     $result.="var select2data = new Object();\n";
                   1141:     $" = '","';
                   1142:     my $debug = '';
                   1143:     foreach my $s1 (sort(keys(%$hashref))) {
                   1144:         $result.="select2data.d_$s1 = new Object();\n";        
                   1145:         $result.="select2data.d_$s1.def = new String('".
                   1146:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1147:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1148:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1149:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1150:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1151:         }
1.36      matthew  1152:         $result.="\"@s2values\");\n";
                   1153:         $result.="select2data.d_$s1.texts = new Array(";        
                   1154:         my @s2texts;
                   1155:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1156:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1157:         }
                   1158:         $result.="\"@s2texts\");\n";
                   1159:     }
                   1160:     $"=' ';
                   1161:     $result.= <<"END";
                   1162: 
                   1163: function select1_changed() {
                   1164:     // Determine new choice
                   1165:     var newvalue = "d_" + $first.value;
                   1166:     // update select2
                   1167:     var values     = select2data[newvalue].values;
                   1168:     var texts      = select2data[newvalue].texts;
                   1169:     var select2def = select2data[newvalue].def;
                   1170:     var i;
                   1171:     // out with the old
                   1172:     for (i = 0; i < $second.options.length; i++) {
                   1173:         $second.options[i] = null;
                   1174:     }
                   1175:     // in with the nuclear
                   1176:     for (i=0;i<values.length; i++) {
                   1177:         $second.options[i] = new Option(values[i]);
1.143     matthew  1178:         $second.options[i].value = values[i];
1.36      matthew  1179:         $second.options[i].text = texts[i];
                   1180:         if (values[i] == select2def) {
                   1181:             $second.options[i].selected = true;
                   1182:         }
                   1183:     }
                   1184: }
1.824     bisitz   1185: // ]]>
1.36      matthew  1186: </script>
                   1187: END
                   1188:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1189:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1190:     my @order = sort(keys(%{$hashref}));
                   1191:     if (ref($menuorder) eq 'ARRAY') {
                   1192:         @order = @{$menuorder};
                   1193:     }
                   1194:     foreach my $value (@order) {
1.36      matthew  1195:         $result.="    <option value=\"$value\" ";
1.253     albertel 1196:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1197:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1198:     }
                   1199:     $result .= "</select>\n";
                   1200:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1201:     $result .= $middletext;
1.1075.2.31  raeburn  1202:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1203:     if ($onchangesecond) {
                   1204:         $result .= ' onchange="'.$onchangesecond.'"';
                   1205:     }
                   1206:     $result .= ">\n";
1.36      matthew  1207:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1208:     
                   1209:     my @secondorder = sort(keys(%select2));
                   1210:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1211:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1212:     }
                   1213:     foreach my $value (@secondorder) {
1.36      matthew  1214:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1215:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1216:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1217:     }
                   1218:     $result .= "</select>\n";
                   1219:     #    return $debug;
                   1220:     return $result;
                   1221: }   #  end of sub linked_select_forms {
                   1222: 
1.45      matthew  1223: =pod
1.44      bowersj2 1224: 
1.1075.2.161.  .6(raebu 1225:22): =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1226: 
1.112     bowersj2 1227: Returns a string corresponding to an HTML link to the given help
                   1228: $topic, where $topic corresponds to the name of a .tex file in
                   1229: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1230: spaces. 
                   1231: 
                   1232: $text will optionally be linked to the same topic, allowing you to
                   1233: link text in addition to the graphic. If you do not want to link
                   1234: text, but wish to specify one of the later parameters, pass an
                   1235: empty string. 
                   1236: 
                   1237: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1238: the link will not open a new window. If false, the link will open
                   1239: a new window using Javascript. (Default is false.) 
                   1240: 
                   1241: $width and $height are optional numerical parameters that will
                   1242: override the width and height of the popped up window, which may
1.973     raeburn  1243: be useful for certain help topics with big pictures included.
                   1244: 
                   1245: $imgid is the id of the img tag used for the help icon. This may be
                   1246: used in a javascript call to switch the image src.  See 
                   1247: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1248: 
1.1075.2.161.  .6(raebu 1249:22): $links_target will optionally be set to a target (_top, _parent or _self).
                   1250:22): 
1.44      bowersj2 1251: =cut
                   1252: 
                   1253: sub help_open_topic {
1.1075.2.161.  .6(raebu 1254:22):     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1255:     $text = "" if (not defined $text);
1.44      bowersj2 1256:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1257:     $width = 500 if (not defined $width);
1.44      bowersj2 1258:     $height = 400 if (not defined $height);
                   1259:     my $filename = $topic;
                   1260:     $filename =~ s/ /_/g;
                   1261: 
1.48      bowersj2 1262:     my $template = "";
                   1263:     my $link;
1.572     banghart 1264:     
1.159     www      1265:     $topic=~s/\W/\_/g;
1.44      bowersj2 1266: 
1.572     banghart 1267:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1268:         if ($env{'browser.mobile'}) {
                   1269: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1270:         } else {
                   1271:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1272:         }
1.1037    www      1273:     } elsif ($stayOnPage eq 'popup') {
                   1274:         $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 1275:     } else {
1.48      bowersj2 1276: 	$link = "/adm/help/${filename}.hlp";
                   1277:     }
                   1278: 
                   1279:     # Add the text
1.1075.2.161.  .6(raebu 1280:22):     my $target = ' target="_top"';
                   1281:22):     if ($links_target) {
                   1282:22):         $target = ' target="'.$links_target.'"';
                   1283:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self')) {
                   1284:22):         $target = '';
                   1285:22):     }
1.755     neumanie 1286:     if ($text ne "") {	
1.763     bisitz   1287: 	$template.='<span class="LC_help_open_topic">'
1.1075.2.161.  .6(raebu 1288:22):                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1289:                   .$text.'</a>';
1.48      bowersj2 1290:     }
                   1291: 
1.763     bisitz   1292:     # (Always) Add the graphic
1.179     matthew  1293:     my $title = &mt('Online Help');
1.667     raeburn  1294:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1295:     if ($imgid ne '') {
                   1296:         $imgid = ' id="'.$imgid.'"';
                   1297:     }
1.1075.2.161.  .6(raebu 1298:22):     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1299:               .'<img src="'.$helpicon.'" border="0"'
                   1300:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1301:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1302:               .' /></a>';
                   1303:     if ($text ne "") {	
                   1304:         $template.='</span>';
                   1305:     }
1.44      bowersj2 1306:     return $template;
                   1307: 
1.106     bowersj2 1308: }
                   1309: 
                   1310: # This is a quicky function for Latex cheatsheet editing, since it 
                   1311: # appears in at least four places
                   1312: sub helpLatexCheatsheet {
1.1037    www      1313:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1314:     my $out;
1.106     bowersj2 1315:     my $addOther = '';
1.732     raeburn  1316:     if ($topic) {
1.1037    www      1317: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1318:     }
                   1319:     $out = '<span>' # Start cheatsheet
                   1320: 	  .$addOther
                   1321:           .'<span>'
1.1037    www      1322: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1323: 	  .'</span> <span>'
1.1037    www      1324: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1325: 	  .'</span>';
1.732     raeburn  1326:     unless ($not_author) {
1.763     bisitz   1327:         $out .= ' <span>'
1.1037    www      1328: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1329: 	       .'</span> <span>'
1.1075.2.78  raeburn  1330:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1331:                .'</span>';
1.732     raeburn  1332:     }
1.763     bisitz   1333:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1334:     return $out;
1.172     www      1335: }
                   1336: 
1.430     albertel 1337: sub general_help {
                   1338:     my $helptopic='Student_Intro';
                   1339:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1340: 	$helptopic='Authoring_Intro';
1.907     raeburn  1341:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1342: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1343:     } elsif ($env{'request.role'}=~/^dc/) {
                   1344:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1345:     }
                   1346:     return $helptopic;
                   1347: }
                   1348: 
                   1349: sub update_help_link {
                   1350:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1351:     my $origurl = $ENV{'REQUEST_URI'};
                   1352:     $origurl=~s|^/~|/priv/|;
                   1353:     my $timestamp = time;
                   1354:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1355:         $$datum = &escape($$datum);
                   1356:     }
                   1357: 
                   1358:     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";
                   1359:     my $output .= <<"ENDOUTPUT";
                   1360: <script type="text/javascript">
1.824     bisitz   1361: // <![CDATA[
1.430     albertel 1362: banner_link = '$banner_link';
1.824     bisitz   1363: // ]]>
1.430     albertel 1364: </script>
                   1365: ENDOUTPUT
                   1366:     return $output;
                   1367: }
                   1368: 
                   1369: # now just updates the help link and generates a blue icon
1.193     raeburn  1370: sub help_open_menu {
1.1075.2.161.  .6(raebu 1371:22):     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1372: 	= @_;    
1.949     droeschl 1373:     $stayOnPage = 1;
1.430     albertel 1374:     my $output;
                   1375:     if ($component_help) {
                   1376: 	if (!$text) {
                   1377: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1075.2.161.  .6(raebu 1378:22): 				       $width,$height,'',$links_target);
1.430     albertel 1379: 	} else {
                   1380: 	    my $help_text;
                   1381: 	    $help_text=&unescape($topic);
                   1382: 	    $output='<table><tr><td>'.
                   1383: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1075.2.161.  .6(raebu 1384:22): 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1385: 	}
                   1386:     }
                   1387:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1388:     return $output.$banner_link;
                   1389: }
                   1390: 
                   1391: sub top_nav_help {
1.1075.2.158  raeburn  1392:     my ($text,$linkattr) = @_;
1.436     albertel 1393:     $text = &mt($text);
1.1075.2.60  raeburn  1394:     my $stay_on_page;
                   1395:     unless ($env{'environment.remote'} eq 'on') {
                   1396:         $stay_on_page = 1;
                   1397:     }
1.1075.2.61  raeburn  1398:     my ($link,$banner_link);
                   1399:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1400:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1401: 	                         : "javascript:helpMenu('open')";
                   1402:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1403:     }
1.201     raeburn  1404:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1405:     if ($link) {
                   1406:         return <<"END";
1.436     albertel 1407: $banner_link
1.1075.2.158  raeburn  1408: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1409: END
1.1075.2.61  raeburn  1410:     } else {
                   1411:         return '&nbsp;'.$text.'&nbsp;';
                   1412:     }
1.436     albertel 1413: }
                   1414: 
                   1415: sub help_menu_js {
1.1075.2.52  raeburn  1416:     my ($httphost) = @_;
1.949     droeschl 1417:     my $stayOnPage = 1;
1.436     albertel 1418:     my $width = 620;
                   1419:     my $height = 600;
1.430     albertel 1420:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1421:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1422:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1423:     my $start_page =
                   1424:         &Apache::loncommon::start_page('Help Menu', undef,
                   1425: 				       {'frameset'    => 1,
                   1426: 					'js_ready'    => 1,
1.1075.2.136  raeburn  1427:                                         'use_absolute' => $httphost,
1.331     albertel 1428: 					'add_entries' => {
                   1429: 					    'border' => '0',
1.579     raeburn  1430: 					    'rows'   => "110,*",},});
1.331     albertel 1431:     my $end_page =
                   1432:         &Apache::loncommon::end_page({'frameset' => 1,
                   1433: 				      'js_ready' => 1,});
                   1434: 
1.436     albertel 1435:     my $template .= <<"ENDTEMPLATE";
                   1436: <script type="text/javascript">
1.877     bisitz   1437: // <![CDATA[
1.253     albertel 1438: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1439: var banner_link = '';
1.243     raeburn  1440: function helpMenu(target) {
                   1441:     var caller = this;
                   1442:     if (target == 'open') {
                   1443:         var newWindow = null;
                   1444:         try {
1.262     albertel 1445:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1446:         }
                   1447:         catch(error) {
                   1448:             writeHelp(caller);
                   1449:             return;
                   1450:         }
                   1451:         if (newWindow) {
                   1452:             caller = newWindow;
                   1453:         }
1.193     raeburn  1454:     }
1.243     raeburn  1455:     writeHelp(caller);
                   1456:     return;
                   1457: }
                   1458: function writeHelp(caller) {
1.1075.2.61  raeburn  1459:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1460:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1461:     caller.document.close();
                   1462:     caller.focus();
1.193     raeburn  1463: }
1.877     bisitz   1464: // END LON-CAPA Internal -->
1.253     albertel 1465: // ]]>
1.436     albertel 1466: </script>
1.193     raeburn  1467: ENDTEMPLATE
                   1468:     return $template;
                   1469: }
                   1470: 
1.172     www      1471: sub help_open_bug {
                   1472:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1473:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1474:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1475:     $text = "" if (not defined $text);
                   1476: 	$stayOnPage=1;
1.184     albertel 1477:     $width = 600 if (not defined $width);
                   1478:     $height = 600 if (not defined $height);
1.172     www      1479: 
                   1480:     $topic=~s/\W+/\+/g;
                   1481:     my $link='';
                   1482:     my $template='';
1.379     albertel 1483:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1484: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1485:     if (!$stayOnPage)
                   1486:     {
                   1487: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1488:     }
                   1489:     else
                   1490:     {
                   1491: 	$link = $url;
                   1492:     }
1.1075.2.161.  .6(raebu 1493:22): 
                   1494:22):     my $target = '_top';
                   1495:22):     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1496:22):         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1497:22):         $target = '_blank';
                   1498:22):     }
                   1499:22): 
1.172     www      1500:     # Add the text
                   1501:     if ($text ne "")
                   1502:     {
                   1503: 	$template .= 
                   1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1075.2.161.  .6(raebu 1505:22):   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1506:     }
                   1507: 
                   1508:     # Add the graphic
1.179     matthew  1509:     my $title = &mt('Report a Bug');
1.215     albertel 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1511:     $template .= <<"ENDTEMPLATE";
1.1075.2.161.  .6(raebu 1512:22):  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1513: ENDTEMPLATE
                   1514:     if ($text ne '') { $template.='</td></tr></table>' };
                   1515:     return $template;
                   1516: 
                   1517: }
                   1518: 
                   1519: sub help_open_faq {
                   1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1521:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1523:     $text = "" if (not defined $text);
                   1524: 	$stayOnPage=1;
                   1525:     $width = 350 if (not defined $width);
                   1526:     $height = 400 if (not defined $height);
                   1527: 
                   1528:     $topic=~s/\W+/\+/g;
                   1529:     my $link='';
                   1530:     my $template='';
                   1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1532:     if (!$stayOnPage)
                   1533:     {
                   1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1535:     }
                   1536:     else
                   1537:     {
                   1538: 	$link = $url;
                   1539:     }
                   1540: 
                   1541:     # Add the text
                   1542:     if ($text ne "")
                   1543:     {
                   1544: 	$template .= 
1.173     www      1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1547:     }
                   1548: 
                   1549:     # Add the graphic
1.179     matthew  1550:     my $title = &mt('View the FAQ');
1.215     albertel 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1552:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1554: ENDTEMPLATE
                   1555:     if ($text ne '') { $template.='</td></tr></table>' };
                   1556:     return $template;
                   1557: 
1.44      bowersj2 1558: }
1.37      matthew  1559: 
1.180     matthew  1560: ###############################################################
                   1561: ###############################################################
                   1562: 
1.45      matthew  1563: =pod
                   1564: 
1.648     raeburn  1565: =item * &change_content_javascript():
1.256     matthew  1566: 
                   1567: This and the next function allow you to create small sections of an
                   1568: otherwise static HTML page that you can update on the fly with
                   1569: Javascript, even in Netscape 4.
                   1570: 
                   1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1572: must be written to the HTML page once. It will prove the Javascript
                   1573: function "change(name, content)". Calling the change function with the
                   1574: name of the section 
                   1575: you want to update, matching the name passed to C<changable_area>, and
                   1576: the new content you want to put in there, will put the content into
                   1577: that area.
                   1578: 
                   1579: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1580: to contain room for the original contents. You need to "make space"
                   1581: for whatever changes you wish to make, and be B<sure> to check your
                   1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1583: it's adequate for updating a one-line status display, but little more.
                   1584: This script will set the space to 100% width, so you only need to
                   1585: worry about height in Netscape 4.
                   1586: 
                   1587: Modern browsers are much less limiting, and if you can commit to the
                   1588: user not using Netscape 4, this feature may be used freely with
                   1589: pretty much any HTML.
                   1590: 
                   1591: =cut
                   1592: 
                   1593: sub change_content_javascript {
                   1594:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1595:     if ($env{'browser.type'} eq 'netscape' &&
                   1596: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1597: 	return (<<NETSCAPE4);
                   1598: 	function change(name, content) {
                   1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1600: 	    doc.open();
                   1601: 	    doc.write(content);
                   1602: 	    doc.close();
                   1603: 	}
                   1604: NETSCAPE4
                   1605:     } else {
                   1606: 	# Otherwise, we need to use semi-standards-compliant code
                   1607: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1608: 	# is really scary, and every useful browser supports it
                   1609: 	return (<<DOMBASED);
                   1610: 	function change(name, content) {
                   1611: 	    element = document.getElementById(name);
                   1612: 	    element.innerHTML = content;
                   1613: 	}
                   1614: DOMBASED
                   1615:     }
                   1616: }
                   1617: 
                   1618: =pod
                   1619: 
1.648     raeburn  1620: =item * &changable_area($name,$origContent):
1.256     matthew  1621: 
                   1622: This provides a "changable area" that can be modified on the fly via
                   1623: the Javascript code provided in C<change_content_javascript>. $name is
                   1624: the name you will use to reference the area later; do not repeat the
                   1625: same name on a given HTML page more then once. $origContent is what
                   1626: the area will originally contain, which can be left blank.
                   1627: 
                   1628: =cut
                   1629: 
                   1630: sub changable_area {
                   1631:     my ($name, $origContent) = @_;
                   1632: 
1.258     albertel 1633:     if ($env{'browser.type'} eq 'netscape' &&
                   1634: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1635: 	# If this is netscape 4, we need to use the Layer tag
                   1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1637:     } else {
                   1638: 	return "<span id='$name'>$origContent</span>";
                   1639:     }
                   1640: }
                   1641: 
                   1642: =pod
                   1643: 
1.648     raeburn  1644: =item * &viewport_geometry_js 
1.590     raeburn  1645: 
                   1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1647: 
                   1648: =cut
                   1649: 
                   1650: 
                   1651: sub viewport_geometry_js { 
                   1652:     return <<"GEOMETRY";
                   1653: var Geometry = {};
                   1654: function init_geometry() {
                   1655:     if (Geometry.init) { return };
                   1656:     Geometry.init=1;
                   1657:     if (window.innerHeight) {
                   1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1662:     }
                   1663:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1664:         Geometry.getViewportHeight =
                   1665:             function() { return document.documentElement.clientHeight; };
                   1666:         Geometry.getViewportWidth =
                   1667:             function() { return document.documentElement.clientWidth; };
                   1668: 
                   1669:         Geometry.getHorizontalScroll =
                   1670:             function() { return document.documentElement.scrollLeft; };
                   1671:         Geometry.getVerticalScroll =
                   1672:             function() { return document.documentElement.scrollTop; };
                   1673:     }
                   1674:     else if (document.body.clientHeight) {
                   1675:         Geometry.getViewportHeight =
                   1676:             function() { return document.body.clientHeight; };
                   1677:         Geometry.getViewportWidth =
                   1678:             function() { return document.body.clientWidth; };
                   1679:         Geometry.getHorizontalScroll =
                   1680:             function() { return document.body.scrollLeft; };
                   1681:         Geometry.getVerticalScroll =
                   1682:             function() { return document.body.scrollTop; };
                   1683:     }
                   1684: }
                   1685: 
                   1686: GEOMETRY
                   1687: }
                   1688: 
                   1689: =pod
                   1690: 
1.648     raeburn  1691: =item * &viewport_size_js()
1.590     raeburn  1692: 
                   1693: 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. 
                   1694: 
                   1695: =cut
                   1696: 
                   1697: sub viewport_size_js {
                   1698:     my $geometry = &viewport_geometry_js();
                   1699:     return <<"DIMS";
                   1700: 
                   1701: $geometry
                   1702: 
                   1703: function getViewportDims(width,height) {
                   1704:     init_geometry();
                   1705:     width.value = Geometry.getViewportWidth();
                   1706:     height.value = Geometry.getViewportHeight();
                   1707:     return;
                   1708: }
                   1709: 
                   1710: DIMS
                   1711: }
                   1712: 
                   1713: =pod
                   1714: 
1.648     raeburn  1715: =item * &resize_textarea_js()
1.565     albertel 1716: 
                   1717: emits the needed javascript to resize a textarea to be as big as possible
                   1718: 
                   1719: creates a function resize_textrea that takes two IDs first should be
                   1720: the id of the element to resize, second should be the id of a div that
                   1721: surrounds everything that comes after the textarea, this routine needs
                   1722: to be attached to the <body> for the onload and onresize events.
                   1723: 
1.648     raeburn  1724: =back
1.565     albertel 1725: 
                   1726: =cut
                   1727: 
                   1728: sub resize_textarea_js {
1.590     raeburn  1729:     my $geometry = &viewport_geometry_js();
1.565     albertel 1730:     return <<"RESIZE";
                   1731:     <script type="text/javascript">
1.824     bisitz   1732: // <![CDATA[
1.590     raeburn  1733: $geometry
1.565     albertel 1734: 
1.588     albertel 1735: function getX(element) {
                   1736:     var x = 0;
                   1737:     while (element) {
                   1738: 	x += element.offsetLeft;
                   1739: 	element = element.offsetParent;
                   1740:     }
                   1741:     return x;
                   1742: }
                   1743: function getY(element) {
                   1744:     var y = 0;
                   1745:     while (element) {
                   1746: 	y += element.offsetTop;
                   1747: 	element = element.offsetParent;
                   1748:     }
                   1749:     return y;
                   1750: }
                   1751: 
                   1752: 
1.565     albertel 1753: function resize_textarea(textarea_id,bottom_id) {
                   1754:     init_geometry();
                   1755:     var textarea        = document.getElementById(textarea_id);
                   1756:     //alert(textarea);
                   1757: 
1.588     albertel 1758:     var textarea_top    = getY(textarea);
1.565     albertel 1759:     var textarea_height = textarea.offsetHeight;
                   1760:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1761:     var bottom_top      = getY(bottom);
1.565     albertel 1762:     var bottom_height   = bottom.offsetHeight;
                   1763:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1764:     var fudge           = 23;
1.565     albertel 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1766:     if (new_height < 300) {
                   1767: 	new_height = 300;
                   1768:     }
                   1769:     textarea.style.height=new_height+'px';
                   1770: }
1.824     bisitz   1771: // ]]>
1.565     albertel 1772: </script>
                   1773: RESIZE
                   1774: 
                   1775: }
                   1776: 
1.1075.2.112  raeburn  1777: sub colorfuleditor_js {
                   1778:     return <<"COLORFULEDIT"
                   1779: <script type="text/javascript">
                   1780: // <![CDATA[>
                   1781:     function fold_box(curDepth, lastresource){
                   1782: 
                   1783:     // we need a list because there can be several blocks you need to fold in one tag
                   1784:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1785:     // but there is only one folding button per tag
                   1786:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1787: 
                   1788:         if(block.item(0).style.display == 'none'){
                   1789: 
                   1790:             foldbutton.value = '@{[&mt("Hide")]}';
                   1791:             for (i = 0; i < block.length; i++){
                   1792:                 block.item(i).style.display = '';
                   1793:             }
                   1794:         }else{
                   1795: 
                   1796:             foldbutton.value = '@{[&mt("Show")]}';
                   1797:             for (i = 0; i < block.length; i++){
                   1798:                 // block.item(i).style.visibility = 'collapse';
                   1799:                 block.item(i).style.display = 'none';
                   1800:             }
                   1801:         };
                   1802:         saveState(lastresource);
                   1803:     }
                   1804: 
                   1805:     function saveState (lastresource) {
                   1806: 
                   1807:         var tag_list = getTagList();
                   1808:         if(tag_list != null){
                   1809:             var timestamp = new Date().getTime();
                   1810:             var key = lastresource;
                   1811: 
                   1812:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1813:             // starting with timestamp
                   1814:             var value = timestamp+';';
                   1815: 
                   1816:             // building the list of key-value pairs
                   1817:             for(var i = 0; i < tag_list.length; i++){
                   1818:                 value += tag_list[i]+',';
                   1819:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1820:             }
                   1821: 
                   1822:             // only iterate whole storage if nothing to override
                   1823:             if(localStorage.getItem(key) == null){
                   1824: 
                   1825:                 // prevent storage from growing large
                   1826:                 if(localStorage.length > 50){
                   1827:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1828:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1829:                     var oldest_key;
                   1830: 
                   1831:                     for(var i = 1; i < localStorage.length; i++){
                   1832:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1833:                             oldest_key = localStorage.key(i);
                   1834:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1835:                         }
                   1836:                     }
                   1837:                     localStorage.removeItem(oldest_key);
                   1838:                 }
                   1839:             }
                   1840:             localStorage.setItem(key,value);
                   1841:         }
                   1842:     }
                   1843: 
                   1844:     // restore folding status of blocks (on page load)
                   1845:     function restoreState (lastresource) {
                   1846:         if(localStorage.getItem(lastresource) != null){
                   1847:             var key = lastresource;
                   1848:             var value = localStorage.getItem(key);
                   1849:             var regex_delTimestamp = /^\d+;/;
                   1850: 
                   1851:             value.replace(regex_delTimestamp, '');
                   1852: 
                   1853:             var valueArr = value.split(';');
                   1854:             var pairs;
                   1855:             var elements;
                   1856:             for (var i = 0; i < valueArr.length; i++){
                   1857:                 pairs = valueArr[i].split(',');
                   1858:                 elements = document.getElementsByName(pairs[0]);
                   1859: 
                   1860:                 for (var j = 0; j < elements.length; j++){
                   1861:                     elements[j].style.display = pairs[1];
                   1862:                     if (pairs[1] == "none"){
                   1863:                         var regex_id = /([_\\d]+)\$/;
                   1864:                         regex_id.exec(pairs[0]);
                   1865:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1866:                     }
                   1867:                 }
                   1868:             }
                   1869:         }
                   1870:     }
                   1871: 
                   1872:     function getTagList () {
                   1873: 
                   1874:         var stringToSearch = document.lonhomework.innerHTML;
                   1875: 
                   1876:         var ret = new Array();
                   1877:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1878:         var tag_list = stringToSearch.match(regex_findBlock);
                   1879: 
                   1880:         if(tag_list != null){
                   1881:             for(var i = 0; i < tag_list.length; i++){
                   1882:                 ret.push(tag_list[i].replace(/"/, ''));
                   1883:             }
                   1884:         }
                   1885:         return ret;
                   1886:     }
                   1887: 
                   1888:     function saveScrollPosition (resource) {
                   1889:         var tag_list = getTagList();
                   1890: 
                   1891:         // we dont always want to jump to the first block
                   1892:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1893:         if(\$(window).scrollTop() > 170){
                   1894:             if(tag_list != null){
                   1895:                 var result;
                   1896:                 for(var i = 0; i < tag_list.length; i++){
                   1897:                     if(isElementInViewport(tag_list[i])){
                   1898:                         result += tag_list[i]+';';
                   1899:                     }
                   1900:                 }
                   1901:                 sessionStorage.setItem('anchor_'+resource, result);
                   1902:             }
                   1903:         } else {
                   1904:             // we dont need to save zero, just delete the item to leave everything tidy
                   1905:             sessionStorage.removeItem('anchor_'+resource);
                   1906:         }
                   1907:     }
                   1908: 
                   1909:     function restoreScrollPosition(resource){
                   1910: 
                   1911:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1912:         if(elem != null){
                   1913:             var tag_list = elem.split(';');
                   1914:             var elem_list;
                   1915: 
                   1916:             for(var i = 0; i < tag_list.length; i++){
                   1917:                 elem_list = document.getElementsByName(tag_list[i]);
                   1918: 
                   1919:                 if(elem_list.length > 0){
                   1920:                     elem = elem_list[0];
                   1921:                     break;
                   1922:                 }
                   1923:             }
                   1924:             elem.scrollIntoView();
                   1925:         }
                   1926:     }
                   1927: 
                   1928:     function isElementInViewport(el) {
                   1929: 
                   1930:         // change to last element instead of first
                   1931:         var elem = document.getElementsByName(el);
                   1932:         var rect = elem[0].getBoundingClientRect();
                   1933: 
                   1934:         return (
                   1935:             rect.top >= 0 &&
                   1936:             rect.left >= 0 &&
                   1937:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1938:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1939:         );
                   1940:     }
                   1941: 
                   1942:     function autosize(depth){
                   1943:         var cmInst = window['cm'+depth];
                   1944:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1945: 
                   1946:         // is fixed size, switching to dynamic
                   1947:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1948:             cmInst.setSize("","auto");
                   1949:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1950:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1951: 
                   1952:         // is dynamic size, switching to fixed
                   1953:         } else {
                   1954:             cmInst.setSize("","300px");
                   1955:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1956:             sessionStorage.removeItem("autosized_"+depth);
                   1957:         }
                   1958:     }
                   1959: 
                   1960: 
                   1961: 
                   1962: // ]]>
                   1963: </script>
                   1964: COLORFULEDIT
                   1965: }
                   1966: 
                   1967: sub xmleditor_js {
                   1968:     return <<XMLEDIT
                   1969: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1970: <script type="text/javascript">
                   1971: // <![CDATA[>
                   1972: 
                   1973:     function saveScrollPosition (resource) {
                   1974: 
                   1975:         var scrollPos = \$(window).scrollTop();
                   1976:         sessionStorage.setItem(resource,scrollPos);
                   1977:     }
                   1978: 
                   1979:     function restoreScrollPosition(resource){
                   1980: 
                   1981:         var scrollPos = sessionStorage.getItem(resource);
                   1982:         \$(window).scrollTop(scrollPos);
                   1983:     }
                   1984: 
                   1985:     // unless internet explorer
                   1986:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1987: 
                   1988:         \$(document).ready(function() {
                   1989:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1990:         });
                   1991:     }
                   1992: 
                   1993:     // inserts text at cursor position into codemirror (xml editor only)
                   1994:     function insertText(text){
                   1995:         cm.focus();
                   1996:         var curPos = cm.getCursor();
                   1997:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1998:     }
                   1999: // ]]>
                   2000: </script>
                   2001: XMLEDIT
                   2002: }
                   2003: 
                   2004: sub insert_folding_button {
                   2005:     my $curDepth = $Apache::lonxml::curdepth;
                   2006:     my $lastresource = $env{'request.ambiguous'};
                   2007: 
                   2008:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   2009:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2010: }
                   2011: 
                   2012: 
1.565     albertel 2013: =pod
                   2014: 
1.256     matthew  2015: =head1 Excel and CSV file utility routines
                   2016: 
                   2017: =cut
                   2018: 
                   2019: ###############################################################
                   2020: ###############################################################
                   2021: 
                   2022: =pod
                   2023: 
1.1075.2.56  raeburn  2024: =over 4
                   2025: 
1.648     raeburn  2026: =item * &csv_translate($text) 
1.37      matthew  2027: 
1.185     www      2028: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2029: format.
                   2030: 
                   2031: =cut
                   2032: 
1.180     matthew  2033: ###############################################################
                   2034: ###############################################################
1.37      matthew  2035: sub csv_translate {
                   2036:     my $text = shift;
                   2037:     $text =~ s/\"/\"\"/g;
1.209     albertel 2038:     $text =~ s/\n/ /g;
1.37      matthew  2039:     return $text;
                   2040: }
1.180     matthew  2041: 
                   2042: ###############################################################
                   2043: ###############################################################
                   2044: 
                   2045: =pod
                   2046: 
1.648     raeburn  2047: =item * &define_excel_formats()
1.180     matthew  2048: 
                   2049: Define some commonly used Excel cell formats.
                   2050: 
                   2051: Currently supported formats:
                   2052: 
                   2053: =over 4
                   2054: 
                   2055: =item header
                   2056: 
                   2057: =item bold
                   2058: 
                   2059: =item h1
                   2060: 
                   2061: =item h2
                   2062: 
                   2063: =item h3
                   2064: 
1.256     matthew  2065: =item h4
                   2066: 
                   2067: =item i
                   2068: 
1.180     matthew  2069: =item date
                   2070: 
                   2071: =back
                   2072: 
                   2073: Inputs: $workbook
                   2074: 
                   2075: Returns: $format, a hash reference.
                   2076: 
1.1057    foxr     2077: 
1.180     matthew  2078: =cut
                   2079: 
                   2080: ###############################################################
                   2081: ###############################################################
                   2082: sub define_excel_formats {
                   2083:     my ($workbook) = @_;
                   2084:     my $format;
                   2085:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2086:                                                 bottom    => 1,
                   2087:                                                 align     => 'center');
                   2088:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2089:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2090:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2091:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2092:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2093:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2094:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2095:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2096:     return $format;
                   2097: }
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
1.113     bowersj2 2101: 
                   2102: =pod
                   2103: 
1.648     raeburn  2104: =item * &create_workbook()
1.255     matthew  2105: 
                   2106: Create an Excel worksheet.  If it fails, output message on the
                   2107: request object and return undefs.
                   2108: 
                   2109: Inputs: Apache request object
                   2110: 
                   2111: Returns (undef) on failure, 
                   2112:     Excel worksheet object, scalar with filename, and formats 
                   2113:     from &Apache::loncommon::define_excel_formats on success
                   2114: 
                   2115: =cut
                   2116: 
                   2117: ###############################################################
                   2118: ###############################################################
                   2119: sub create_workbook {
                   2120:     my ($r) = @_;
                   2121:         #
                   2122:     # Create the excel spreadsheet
                   2123:     my $filename = '/prtspool/'.
1.258     albertel 2124:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2125:         time.'_'.rand(1000000000).'.xls';
                   2126:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2127:     if (! defined($workbook)) {
                   2128:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2129:         $r->print(
                   2130:             '<p class="LC_error">'
                   2131:            .&mt('Problems occurred in creating the new Excel file.')
                   2132:            .' '.&mt('This error has been logged.')
                   2133:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2134:            .'</p>'
                   2135:         );
1.255     matthew  2136:         return (undef);
                   2137:     }
                   2138:     #
1.1014    foxr     2139:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2140:     #
                   2141:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2142:     return ($workbook,$filename,$format);
                   2143: }
                   2144: 
                   2145: ###############################################################
                   2146: ###############################################################
                   2147: 
                   2148: =pod
                   2149: 
1.648     raeburn  2150: =item * &create_text_file()
1.113     bowersj2 2151: 
1.542     raeburn  2152: Create a file to write to and eventually make available to the user.
1.256     matthew  2153: If file creation fails, outputs an error message on the request object and 
                   2154: return undefs.
1.113     bowersj2 2155: 
1.256     matthew  2156: Inputs: Apache request object, and file suffix
1.113     bowersj2 2157: 
1.256     matthew  2158: Returns (undef) on failure, 
                   2159:     Filehandle and filename on success.
1.113     bowersj2 2160: 
                   2161: =cut
                   2162: 
1.256     matthew  2163: ###############################################################
                   2164: ###############################################################
                   2165: sub create_text_file {
                   2166:     my ($r,$suffix) = @_;
                   2167:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2168:     my $fh;
                   2169:     my $filename = '/prtspool/'.
1.258     albertel 2170:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2171:         time.'_'.rand(1000000000).'.'.$suffix;
                   2172:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2173:     if (! defined($fh)) {
                   2174:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2175:         $r->print(
                   2176:             '<p class="LC_error">'
                   2177:            .&mt('Problems occurred in creating the output file.')
                   2178:            .' '.&mt('This error has been logged.')
                   2179:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2180:            .'</p>'
                   2181:         );
1.113     bowersj2 2182:     }
1.256     matthew  2183:     return ($fh,$filename)
1.113     bowersj2 2184: }
                   2185: 
                   2186: 
1.256     matthew  2187: =pod 
1.113     bowersj2 2188: 
                   2189: =back
                   2190: 
                   2191: =cut
1.37      matthew  2192: 
                   2193: ###############################################################
1.33      matthew  2194: ##        Home server <option> list generating code          ##
                   2195: ###############################################################
1.35      matthew  2196: 
1.169     www      2197: # ------------------------------------------
                   2198: 
                   2199: sub domain_select {
                   2200:     my ($name,$value,$multiple)=@_;
                   2201:     my %domains=map { 
1.514     albertel 2202: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2203:     } &Apache::lonnet::all_domains();
1.169     www      2204:     if ($multiple) {
                   2205: 	$domains{''}=&mt('Any domain');
1.550     albertel 2206: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2207: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2208:     } else {
1.550     albertel 2209: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2210: 	return &select_form($name,$value,\%domains);
1.169     www      2211:     }
                   2212: }
                   2213: 
1.282     albertel 2214: #-------------------------------------------
                   2215: 
                   2216: =pod
                   2217: 
1.519     raeburn  2218: =head1 Routines for form select boxes
                   2219: 
                   2220: =over 4
                   2221: 
1.648     raeburn  2222: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2223: 
                   2224: Returns a string containing a <select> element int multiple mode
                   2225: 
                   2226: 
                   2227: Args:
                   2228:   $name - name of the <select> element
1.506     raeburn  2229:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2230:   $size - number of rows long the select element is
1.283     albertel 2231:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2232:           (shown text should already have been &mt())
1.506     raeburn  2233:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2234: 
1.282     albertel 2235: =cut
                   2236: 
                   2237: #-------------------------------------------
1.169     www      2238: sub multiple_select_form {
1.284     albertel 2239:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2240:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2241:     my $output='';
1.191     matthew  2242:     if (! defined($size)) {
                   2243:         $size = 4;
1.283     albertel 2244:         if (scalar(keys(%$hash))<4) {
                   2245:             $size = scalar(keys(%$hash));
1.191     matthew  2246:         }
                   2247:     }
1.734     bisitz   2248:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2249:     my @order;
1.506     raeburn  2250:     if (ref($order) eq 'ARRAY')  {
                   2251:         @order = @{$order};
                   2252:     } else {
                   2253:         @order = sort(keys(%$hash));
1.501     banghart 2254:     }
                   2255:     if (exists($$hash{'select_form_order'})) {
                   2256:         @order = @{$$hash{'select_form_order'}};
                   2257:     }
                   2258:         
1.284     albertel 2259:     foreach my $key (@order) {
1.356     albertel 2260:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2261:         $output.='selected="selected" ' if ($selected{$key});
                   2262:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2263:     }
                   2264:     $output.="</select>\n";
                   2265:     return $output;
                   2266: }
                   2267: 
1.88      www      2268: #-------------------------------------------
                   2269: 
                   2270: =pod
                   2271: 
1.1075.2.115  raeburn  2272: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2273: 
                   2274: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2275: allow a user to select options from a ref to a hash containing:
                   2276: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2277: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2278: An optional arg -- $readonly -- if true will cause the select form
                   2279: to be disabled, e.g., for the case where an instructor has a section-
                   2280: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2281: 
1.88      www      2282: See lonrights.pm for an example invocation and use.
                   2283: 
                   2284: =cut
                   2285: 
                   2286: #-------------------------------------------
                   2287: sub select_form {
1.1075.2.115  raeburn  2288:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2289:     return unless (ref($hashref) eq 'HASH');
                   2290:     if ($onchange) {
                   2291:         $onchange = ' onchange="'.$onchange.'"';
                   2292:     }
1.1075.2.129  raeburn  2293:     my $disabled;
                   2294:     if ($readonly) {
                   2295:         $disabled = ' disabled="disabled"';
                   2296:     }
                   2297:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2298:     my @keys;
1.970     raeburn  2299:     if (exists($hashref->{'select_form_order'})) {
                   2300: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2301:     } else {
1.970     raeburn  2302: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2303:     }
1.356     albertel 2304:     foreach my $key (@keys) {
                   2305:         $selectform.=
                   2306: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2307:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2308:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2309:     }
                   2310:     $selectform.="</select>";
                   2311:     return $selectform;
                   2312: }
                   2313: 
1.475     www      2314: # For display filters
                   2315: 
                   2316: sub display_filter {
1.1074    raeburn  2317:     my ($context) = @_;
1.475     www      2318:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2319:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2320:     my $phraseinput = 'hidden';
                   2321:     my $includeinput = 'hidden';
                   2322:     my ($checked,$includetypestext);
                   2323:     if ($env{'form.displayfilter'} eq 'containing') {
                   2324:         $phraseinput = 'text'; 
                   2325:         if ($context eq 'parmslog') {
                   2326:             $includeinput = 'checkbox';
                   2327:             if ($env{'form.includetypes'}) {
                   2328:                 $checked = ' checked="checked"';
                   2329:             }
                   2330:             $includetypestext = &mt('Include parameter types');
                   2331:         }
                   2332:     } else {
                   2333:         $includetypestext = '&nbsp;';
                   2334:     }
                   2335:     my ($additional,$secondid,$thirdid);
                   2336:     if ($context eq 'parmslog') {
                   2337:         $additional = 
                   2338:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2339:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2340:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2341:             '</label>';
                   2342:         $secondid = 'includetypes';
                   2343:         $thirdid = 'includetypestext';
                   2344:     }
                   2345:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2346:                                                     '$secondid','$thirdid')";
                   2347:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2348: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2349: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2350: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2351:            &mt('Filter: [_1]',
1.477     www      2352: 	   &select_form($env{'form.displayfilter'},
                   2353: 			'displayfilter',
1.970     raeburn  2354: 			{'currentfolder' => 'Current folder/page',
1.477     www      2355: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2356: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2357: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2358:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2359:                          '" />'.$additional;
                   2360: }
                   2361: 
                   2362: sub display_filter_js {
                   2363:     my $includetext = &mt('Include parameter types');
                   2364:     return <<"ENDJS";
                   2365:   
                   2366: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2367:     var firstType = 'hidden';
                   2368:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2369:         firstType = 'text';
                   2370:     }
                   2371:     firstObject = document.getElementById(firstid);
                   2372:     if (typeof(firstObject) == 'object') {
                   2373:         if (firstObject.type != firstType) {
                   2374:             changeInputType(firstObject,firstType);
                   2375:         }
                   2376:     }
                   2377:     if (context == 'parmslog') {
                   2378:         var secondType = 'hidden';
                   2379:         if (firstType == 'text') {
                   2380:             secondType = 'checkbox';
                   2381:         }
                   2382:         secondObject = document.getElementById(secondid);  
                   2383:         if (typeof(secondObject) == 'object') {
                   2384:             if (secondObject.type != secondType) {
                   2385:                 changeInputType(secondObject,secondType);
                   2386:             }
                   2387:         }
                   2388:         var textItem = document.getElementById(thirdid);
                   2389:         var currtext = textItem.innerHTML;
                   2390:         var newtext;
                   2391:         if (firstType == 'text') {
                   2392:             newtext = '$includetext';
                   2393:         } else {
                   2394:             newtext = '&nbsp;';
                   2395:         }
                   2396:         if (currtext != newtext) {
                   2397:             textItem.innerHTML = newtext;
                   2398:         }
                   2399:     }
                   2400:     return;
                   2401: }
                   2402: 
                   2403: function changeInputType(oldObject,newType) {
                   2404:     var newObject = document.createElement('input');
                   2405:     newObject.type = newType;
                   2406:     if (oldObject.size) {
                   2407:         newObject.size = oldObject.size;
                   2408:     }
                   2409:     if (oldObject.value) {
                   2410:         newObject.value = oldObject.value;
                   2411:     }
                   2412:     if (oldObject.name) {
                   2413:         newObject.name = oldObject.name;
                   2414:     }
                   2415:     if (oldObject.id) {
                   2416:         newObject.id = oldObject.id;
                   2417:     }
                   2418:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2419:     return;
                   2420: }
                   2421: 
                   2422: ENDJS
1.475     www      2423: }
                   2424: 
1.167     www      2425: sub gradeleveldescription {
                   2426:     my $gradelevel=shift;
                   2427:     my %gradelevels=(0 => 'Not specified',
                   2428: 		     1 => 'Grade 1',
                   2429: 		     2 => 'Grade 2',
                   2430: 		     3 => 'Grade 3',
                   2431: 		     4 => 'Grade 4',
                   2432: 		     5 => 'Grade 5',
                   2433: 		     6 => 'Grade 6',
                   2434: 		     7 => 'Grade 7',
                   2435: 		     8 => 'Grade 8',
                   2436: 		     9 => 'Grade 9',
                   2437: 		     10 => 'Grade 10',
                   2438: 		     11 => 'Grade 11',
                   2439: 		     12 => 'Grade 12',
                   2440: 		     13 => 'Grade 13',
                   2441: 		     14 => '100 Level',
                   2442: 		     15 => '200 Level',
                   2443: 		     16 => '300 Level',
                   2444: 		     17 => '400 Level',
                   2445: 		     18 => 'Graduate Level');
                   2446:     return &mt($gradelevels{$gradelevel});
                   2447: }
                   2448: 
1.163     www      2449: sub select_level_form {
                   2450:     my ($deflevel,$name)=@_;
                   2451:     unless ($deflevel) { $deflevel=0; }
1.167     www      2452:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2453:     for (my $i=0; $i<=18; $i++) {
                   2454:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2455:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2456:                 ">".&gradeleveldescription($i)."</option>\n";
                   2457:     }
                   2458:     $selectform.="</select>";
                   2459:     return $selectform;
1.163     www      2460: }
1.167     www      2461: 
1.35      matthew  2462: #-------------------------------------------
                   2463: 
1.45      matthew  2464: =pod
                   2465: 
1.1075.2.115  raeburn  2466: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2467: 
                   2468: Returns a string containing a <select name='$name' size='1'> form to 
                   2469: allow a user to select the domain to preform an operation in.  
                   2470: See loncreateuser.pm for an example invocation and use.
                   2471: 
1.90      www      2472: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2473: selected");
                   2474: 
1.743     raeburn  2475: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2476: 
1.910     raeburn  2477: 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.
                   2478: 
1.1075.2.36  raeburn  2479: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2480: 
1.1075.2.115  raeburn  2481: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2482: 
                   2483: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2484: 
1.35      matthew  2485: =cut
                   2486: 
                   2487: #-------------------------------------------
1.34      matthew  2488: sub select_dom_form {
1.1075.2.115  raeburn  2489:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2490:     if ($onchange) {
1.874     raeburn  2491:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2492:     }
1.1075.2.115  raeburn  2493:     if ($disabled) {
                   2494:         $disabled = ' disabled="disabled"';
                   2495:     }
1.1075.2.36  raeburn  2496:     my (@domains,%exclude);
1.910     raeburn  2497:     if (ref($incdoms) eq 'ARRAY') {
                   2498:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2499:     } else {
                   2500:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2501:     }
1.90      www      2502:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2503:     if (ref($excdoms) eq 'ARRAY') {
                   2504:         map { $exclude{$_} = 1; } @{$excdoms};
                   2505:     }
1.1075.2.115  raeburn  2506:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2507:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2508:         next if ($exclude{$dom});
1.356     albertel 2509:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2510:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2511:         if ($showdomdesc) {
                   2512:             if ($dom ne '') {
                   2513:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2514:                 if ($domdesc ne '') {
                   2515:                     $selectdomain .= ' ('.$domdesc.')';
                   2516:                 }
                   2517:             } 
                   2518:         }
                   2519:         $selectdomain .= "</option>\n";
1.34      matthew  2520:     }
                   2521:     $selectdomain.="</select>";
                   2522:     return $selectdomain;
                   2523: }
                   2524: 
1.35      matthew  2525: #-------------------------------------------
                   2526: 
1.45      matthew  2527: =pod
                   2528: 
1.648     raeburn  2529: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2530: 
1.586     raeburn  2531: input: 4 arguments (two required, two optional) - 
                   2532:     $domain - domain of new user
                   2533:     $name - name of form element
                   2534:     $default - Value of 'default' causes a default item to be first 
                   2535:                             option, and selected by default. 
                   2536:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2537:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2538: output: returns 2 items: 
1.586     raeburn  2539: (a) form element which contains either:
                   2540:    (i) <select name="$name">
                   2541:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2542:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2543:        </select>
                   2544:        form item if there are multiple library servers in $domain, or
                   2545:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2546:        if there is only one library server in $domain.
                   2547: 
                   2548: (b) number of library servers found.
                   2549: 
                   2550: See loncreateuser.pm for example of use.
1.35      matthew  2551: 
                   2552: =cut
                   2553: 
                   2554: #-------------------------------------------
1.586     raeburn  2555: sub home_server_form_item {
                   2556:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2557:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2558:     my $result;
                   2559:     my $numlib = keys(%servers);
                   2560:     if ($numlib > 1) {
                   2561:         $result .= '<select name="'.$name.'" />'."\n";
                   2562:         if ($default) {
1.804     bisitz   2563:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2564:                        '</option>'."\n";
                   2565:         }
                   2566:         foreach my $hostid (sort(keys(%servers))) {
                   2567:             $result.= '<option value="'.$hostid.'">'.
                   2568: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2569:         }
                   2570:         $result .= '</select>'."\n";
                   2571:     } elsif ($numlib == 1) {
                   2572:         my $hostid;
                   2573:         foreach my $item (keys(%servers)) {
                   2574:             $hostid = $item;
                   2575:         }
                   2576:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2577:                    $hostid.'" />';
                   2578:                    if (!$hide) {
                   2579:                        $result .= $hostid.' '.$servers{$hostid};
                   2580:                    }
                   2581:                    $result .= "\n";
                   2582:     } elsif ($default) {
                   2583:         $result .= '<input type="hidden" name="'.$name.
                   2584:                    '" value="default" />';
                   2585:                    if (!$hide) {
                   2586:                        $result .= &mt('default');
                   2587:                    }
                   2588:                    $result .= "\n";
1.33      matthew  2589:     }
1.586     raeburn  2590:     return ($result,$numlib);
1.33      matthew  2591: }
1.112     bowersj2 2592: 
                   2593: =pod
                   2594: 
1.534     albertel 2595: =back 
                   2596: 
1.112     bowersj2 2597: =cut
1.87      matthew  2598: 
                   2599: ###############################################################
1.112     bowersj2 2600: ##                  Decoding User Agent                      ##
1.87      matthew  2601: ###############################################################
                   2602: 
                   2603: =pod
                   2604: 
1.112     bowersj2 2605: =head1 Decoding the User Agent
                   2606: 
                   2607: =over 4
                   2608: 
                   2609: =item * &decode_user_agent()
1.87      matthew  2610: 
                   2611: Inputs: $r
                   2612: 
                   2613: Outputs:
                   2614: 
                   2615: =over 4
                   2616: 
1.112     bowersj2 2617: =item * $httpbrowser
1.87      matthew  2618: 
1.112     bowersj2 2619: =item * $clientbrowser
1.87      matthew  2620: 
1.112     bowersj2 2621: =item * $clientversion
1.87      matthew  2622: 
1.112     bowersj2 2623: =item * $clientmathml
1.87      matthew  2624: 
1.112     bowersj2 2625: =item * $clientunicode
1.87      matthew  2626: 
1.112     bowersj2 2627: =item * $clientos
1.87      matthew  2628: 
1.1075.2.42  raeburn  2629: =item * $clientmobile
                   2630: 
                   2631: =item * $clientinfo
                   2632: 
1.1075.2.77  raeburn  2633: =item * $clientosversion
                   2634: 
1.87      matthew  2635: =back
                   2636: 
1.157     matthew  2637: =back 
                   2638: 
1.87      matthew  2639: =cut
                   2640: 
                   2641: ###############################################################
                   2642: ###############################################################
                   2643: sub decode_user_agent {
1.247     albertel 2644:     my ($r)=@_;
1.87      matthew  2645:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2646:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2647:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2648:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2649:     my $clientbrowser='unknown';
                   2650:     my $clientversion='0';
                   2651:     my $clientmathml='';
                   2652:     my $clientunicode='0';
1.1075.2.42  raeburn  2653:     my $clientmobile=0;
1.1075.2.77  raeburn  2654:     my $clientosversion='';
1.87      matthew  2655:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2656:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2657: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2658: 	    $clientbrowser=$bname;
                   2659:             $httpbrowser=~/$vreg/i;
                   2660: 	    $clientversion=$1;
                   2661:             $clientmathml=($clientversion>=$minv);
                   2662:             $clientunicode=($clientversion>=$univ);
                   2663: 	}
                   2664:     }
                   2665:     my $clientos='unknown';
1.1075.2.42  raeburn  2666:     my $clientinfo;
1.87      matthew  2667:     if (($httpbrowser=~/linux/i) ||
                   2668:         ($httpbrowser=~/unix/i) ||
                   2669:         ($httpbrowser=~/ux/i) ||
                   2670:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2671:     if (($httpbrowser=~/vax/i) ||
                   2672:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2673:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2674:     if (($httpbrowser=~/mac/i) ||
                   2675:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2676:     if ($httpbrowser=~/win/i) {
                   2677:         $clientos='win';
                   2678:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2679:             $clientosversion = $1;
                   2680:         }
                   2681:     }
1.87      matthew  2682:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2683:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2684:         $clientmobile=lc($1);
                   2685:     }
                   2686:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2687:         $clientinfo = 'firefox-'.$1;
                   2688:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2689:         $clientinfo = 'chromeframe-'.$1;
                   2690:     }
1.87      matthew  2691:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2692:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2693:             $clientosversion);
1.87      matthew  2694: }
                   2695: 
1.32      matthew  2696: ###############################################################
                   2697: ##    Authentication changing form generation subroutines    ##
                   2698: ###############################################################
                   2699: ##
                   2700: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2701: ## hash, and have reasonable default values.
                   2702: ##
                   2703: ##    formname = the name given in the <form> tag.
1.35      matthew  2704: #-------------------------------------------
                   2705: 
1.45      matthew  2706: =pod
                   2707: 
1.112     bowersj2 2708: =head1 Authentication Routines
                   2709: 
                   2710: =over 4
                   2711: 
1.648     raeburn  2712: =item * &authform_xxxxxx()
1.35      matthew  2713: 
                   2714: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2715: handle some of the conveniences required for authentication forms.  
                   2716: This is not an optimal method, but it works.  
                   2717: 
                   2718: =over 4
                   2719: 
1.112     bowersj2 2720: =item * authform_header
1.35      matthew  2721: 
1.112     bowersj2 2722: =item * authform_authorwarning
1.35      matthew  2723: 
1.112     bowersj2 2724: =item * authform_nochange
1.35      matthew  2725: 
1.112     bowersj2 2726: =item * authform_kerberos
1.35      matthew  2727: 
1.112     bowersj2 2728: =item * authform_internal
1.35      matthew  2729: 
1.112     bowersj2 2730: =item * authform_filesystem
1.35      matthew  2731: 
                   2732: =back
                   2733: 
1.648     raeburn  2734: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2735: 
1.35      matthew  2736: =cut
                   2737: 
                   2738: #-------------------------------------------
1.32      matthew  2739: sub authform_header{  
                   2740:     my %in = (
                   2741:         formname => 'cu',
1.80      albertel 2742:         kerb_def_dom => '',
1.32      matthew  2743:         @_,
                   2744:     );
                   2745:     $in{'formname'} = 'document.' . $in{'formname'};
                   2746:     my $result='';
1.80      albertel 2747: 
                   2748: #---------------------------------------------- Code for upper case translation
                   2749:     my $Javascript_toUpperCase;
                   2750:     unless ($in{kerb_def_dom}) {
                   2751:         $Javascript_toUpperCase =<<"END";
                   2752:         switch (choice) {
                   2753:            case 'krb': currentform.elements[choicearg].value =
                   2754:                currentform.elements[choicearg].value.toUpperCase();
                   2755:                break;
                   2756:            default:
                   2757:         }
                   2758: END
                   2759:     } else {
                   2760:         $Javascript_toUpperCase = "";
                   2761:     }
                   2762: 
1.165     raeburn  2763:     my $radioval = "'nochange'";
1.591     raeburn  2764:     if (defined($in{'curr_authtype'})) {
                   2765:         if ($in{'curr_authtype'} ne '') {
                   2766:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2767:         }
1.174     matthew  2768:     }
1.165     raeburn  2769:     my $argfield = 'null';
1.591     raeburn  2770:     if (defined($in{'mode'})) {
1.165     raeburn  2771:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2772:             if (defined($in{'curr_autharg'})) {
                   2773:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2774:                     $argfield = "'$in{'curr_autharg'}'";
                   2775:                 }
                   2776:             }
                   2777:         }
                   2778:     }
                   2779: 
1.32      matthew  2780:     $result.=<<"END";
                   2781: var current = new Object();
1.165     raeburn  2782: current.radiovalue = $radioval;
                   2783: current.argfield = $argfield;
1.32      matthew  2784: 
                   2785: function changed_radio(choice,currentform) {
                   2786:     var choicearg = choice + 'arg';
                   2787:     // If a radio button in changed, we need to change the argfield
                   2788:     if (current.radiovalue != choice) {
                   2789:         current.radiovalue = choice;
                   2790:         if (current.argfield != null) {
                   2791:             currentform.elements[current.argfield].value = '';
                   2792:         }
                   2793:         if (choice == 'nochange') {
                   2794:             current.argfield = null;
                   2795:         } else {
                   2796:             current.argfield = choicearg;
                   2797:             switch(choice) {
                   2798:                 case 'krb': 
                   2799:                     currentform.elements[current.argfield].value = 
                   2800:                         "$in{'kerb_def_dom'}";
                   2801:                 break;
                   2802:               default:
                   2803:                 break;
                   2804:             }
                   2805:         }
                   2806:     }
                   2807:     return;
                   2808: }
1.22      www      2809: 
1.32      matthew  2810: function changed_text(choice,currentform) {
                   2811:     var choicearg = choice + 'arg';
                   2812:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2813:         $Javascript_toUpperCase
1.32      matthew  2814:         // clear old field
                   2815:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2816:             currentform.elements[current.argfield].value = '';
                   2817:         }
                   2818:         current.argfield = choicearg;
                   2819:     }
                   2820:     set_auth_radio_buttons(choice,currentform);
                   2821:     return;
1.20      www      2822: }
1.32      matthew  2823: 
                   2824: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2825:     var numauthchoices = currentform.login.length;
                   2826:     if (typeof numauthchoices  == "undefined") {
                   2827:         return;
                   2828:     } 
1.32      matthew  2829:     var i=0;
1.986     raeburn  2830:     while (i < numauthchoices) {
1.32      matthew  2831:         if (currentform.login[i].value == newvalue) { break; }
                   2832:         i++;
                   2833:     }
1.986     raeburn  2834:     if (i == numauthchoices) {
1.32      matthew  2835:         return;
                   2836:     }
                   2837:     current.radiovalue = newvalue;
                   2838:     currentform.login[i].checked = true;
                   2839:     return;
                   2840: }
                   2841: END
                   2842:     return $result;
                   2843: }
                   2844: 
1.1075.2.20  raeburn  2845: sub authform_authorwarning {
1.32      matthew  2846:     my $result='';
1.144     matthew  2847:     $result='<i>'.
                   2848:         &mt('As a general rule, only authors or co-authors should be '.
                   2849:             'filesystem authenticated '.
                   2850:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2851:     return $result;
                   2852: }
                   2853: 
1.1075.2.20  raeburn  2854: sub authform_nochange {
1.32      matthew  2855:     my %in = (
                   2856:               formname => 'document.cu',
                   2857:               kerb_def_dom => 'MSU.EDU',
                   2858:               @_,
                   2859:           );
1.1075.2.20  raeburn  2860:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2861:     my $result;
1.1075.2.20  raeburn  2862:     if (!$authnum) {
                   2863:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2864:     } else {
                   2865:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2866:                   '<input type="radio" name="login" value="nochange" '.
                   2867:                   'checked="checked" onclick="'.
1.281     albertel 2868:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2869: 	    '</label>';
1.586     raeburn  2870:     }
1.32      matthew  2871:     return $result;
                   2872: }
                   2873: 
1.591     raeburn  2874: sub authform_kerberos {
1.32      matthew  2875:     my %in = (
                   2876:               formname => 'document.cu',
                   2877:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2878:               kerb_def_auth => 'krb4',
1.32      matthew  2879:               @_,
                   2880:               );
1.586     raeburn  2881:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2882:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2883:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2884:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2885:        $check5 = ' checked="checked"';
1.80      albertel 2886:     } else {
1.772     bisitz   2887:        $check4 = ' checked="checked"';
1.80      albertel 2888:     }
1.1075.2.117  raeburn  2889:     if ($in{'readonly'}) {
                   2890:         $disabled = ' disabled="disabled"';
                   2891:     }
1.165     raeburn  2892:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2893:     if (defined($in{'curr_authtype'})) {
                   2894:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2895:             $krbcheck = ' checked="checked"';
1.623     raeburn  2896:             if (defined($in{'mode'})) {
                   2897:                 if ($in{'mode'} eq 'modifyuser') {
                   2898:                     $krbcheck = '';
                   2899:                 }
                   2900:             }
1.591     raeburn  2901:             if (defined($in{'curr_kerb_ver'})) {
                   2902:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2903:                     $check5 = ' checked="checked"';
1.591     raeburn  2904:                     $check4 = '';
                   2905:                 } else {
1.772     bisitz   2906:                     $check4 = ' checked="checked"';
1.591     raeburn  2907:                     $check5 = '';
                   2908:                 }
1.586     raeburn  2909:             }
1.591     raeburn  2910:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2911:                 $krbarg = $in{'curr_autharg'};
                   2912:             }
1.586     raeburn  2913:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2914:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2915:                     $result = 
                   2916:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2917:         $in{'curr_autharg'},$krbver);
                   2918:                 } else {
                   2919:                     $result =
                   2920:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2921:                 }
                   2922:                 return $result; 
                   2923:             }
                   2924:         }
                   2925:     } else {
                   2926:         if ($authnum == 1) {
1.784     bisitz   2927:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2928:         }
                   2929:     }
1.586     raeburn  2930:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2931:         return;
1.587     raeburn  2932:     } elsif ($authtype eq '') {
1.591     raeburn  2933:         if (defined($in{'mode'})) {
1.587     raeburn  2934:             if ($in{'mode'} eq 'modifycourse') {
                   2935:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2936:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2937:                 }
                   2938:             }
                   2939:         }
1.586     raeburn  2940:     }
                   2941:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2942:     if ($authtype eq '') {
                   2943:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2944:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2945:                     $krbcheck.$disabled.' />';
1.586     raeburn  2946:     }
                   2947:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2948:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2949:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2950:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2951:          $in{'curr_authtype'} eq 'krb4')) {
                   2952:         $result .= &mt
1.144     matthew  2953:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2954:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2955:          '<label>'.$authtype,
1.281     albertel 2956:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2957:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2958:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2959:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2960:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2961: 	 '</label>');
1.586     raeburn  2962:     } elsif ($can_assign{'krb4'}) {
                   2963:         $result .= &mt
                   2964:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2965:          '[_3] Version 4 [_4]',
                   2966:          '<label>'.$authtype,
                   2967:          '</label><input type="text" size="10" name="krbarg" '.
                   2968:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2969:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2970:          '<label><input type="hidden" name="krbver" value="4" />',
                   2971:          '</label>');
                   2972:     } elsif ($can_assign{'krb5'}) {
                   2973:         $result .= &mt
                   2974:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2975:          '[_3] Version 5 [_4]',
                   2976:          '<label>'.$authtype,
                   2977:          '</label><input type="text" size="10" name="krbarg" '.
                   2978:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2979:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2980:          '<label><input type="hidden" name="krbver" value="5" />',
                   2981:          '</label>');
                   2982:     }
1.32      matthew  2983:     return $result;
                   2984: }
                   2985: 
1.1075.2.20  raeburn  2986: sub authform_internal {
1.586     raeburn  2987:     my %in = (
1.32      matthew  2988:                 formname => 'document.cu',
                   2989:                 kerb_def_dom => 'MSU.EDU',
                   2990:                 @_,
                   2991:                 );
1.1075.2.117  raeburn  2992:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2993:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2994:     if ($in{'readonly'}) {
                   2995:         $disabled = ' disabled="disabled"';
                   2996:     }
1.591     raeburn  2997:     if (defined($in{'curr_authtype'})) {
                   2998:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2999:             if ($can_assign{'int'}) {
1.772     bisitz   3000:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3001:                 if (defined($in{'mode'})) {
                   3002:                     if ($in{'mode'} eq 'modifyuser') {
                   3003:                         $intcheck = '';
                   3004:                     }
                   3005:                 }
1.591     raeburn  3006:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3007:                     $intarg = $in{'curr_autharg'};
                   3008:                 }
                   3009:             } else {
                   3010:                 $result = &mt('Currently internally authenticated.');
                   3011:                 return $result;
1.165     raeburn  3012:             }
                   3013:         }
1.586     raeburn  3014:     } else {
                   3015:         if ($authnum == 1) {
1.784     bisitz   3016:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3017:         }
                   3018:     }
                   3019:     if (!$can_assign{'int'}) {
                   3020:         return;
1.587     raeburn  3021:     } elsif ($authtype eq '') {
1.591     raeburn  3022:         if (defined($in{'mode'})) {
1.587     raeburn  3023:             if ($in{'mode'} eq 'modifycourse') {
                   3024:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3025:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3026:                 }
                   3027:             }
                   3028:         }
1.165     raeburn  3029:     }
1.586     raeburn  3030:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3031:     if ($authtype eq '') {
                   3032:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3033:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3034:     }
1.605     bisitz   3035:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3036:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3037:     $result = &mt
1.144     matthew  3038:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3039:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3040:     $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  3041:     return $result;
                   3042: }
                   3043: 
1.1075.2.20  raeburn  3044: sub authform_local {
1.32      matthew  3045:     my %in = (
                   3046:               formname => 'document.cu',
                   3047:               kerb_def_dom => 'MSU.EDU',
                   3048:               @_,
                   3049:               );
1.1075.2.117  raeburn  3050:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3051:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3052:     if ($in{'readonly'}) {
                   3053:         $disabled = ' disabled="disabled"';
                   3054:     }
1.591     raeburn  3055:     if (defined($in{'curr_authtype'})) {
                   3056:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3057:             if ($can_assign{'loc'}) {
1.772     bisitz   3058:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3059:                 if (defined($in{'mode'})) {
                   3060:                     if ($in{'mode'} eq 'modifyuser') {
                   3061:                         $loccheck = '';
                   3062:                     }
                   3063:                 }
1.591     raeburn  3064:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3065:                     $locarg = $in{'curr_autharg'};
                   3066:                 }
                   3067:             } else {
                   3068:                 $result = &mt('Currently using local (institutional) authentication.');
                   3069:                 return $result;
1.165     raeburn  3070:             }
                   3071:         }
1.586     raeburn  3072:     } else {
                   3073:         if ($authnum == 1) {
1.784     bisitz   3074:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3075:         }
                   3076:     }
                   3077:     if (!$can_assign{'loc'}) {
                   3078:         return;
1.587     raeburn  3079:     } elsif ($authtype eq '') {
1.591     raeburn  3080:         if (defined($in{'mode'})) {
1.587     raeburn  3081:             if ($in{'mode'} eq 'modifycourse') {
                   3082:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3083:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3084:                 }
                   3085:             }
                   3086:         }
1.165     raeburn  3087:     }
1.586     raeburn  3088:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3089:     if ($authtype eq '') {
                   3090:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3091:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3092:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3093:     }
                   3094:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3095:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3096:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3097:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3098:     return $result;
                   3099: }
                   3100: 
1.1075.2.20  raeburn  3101: sub authform_filesystem {
1.32      matthew  3102:     my %in = (
                   3103:               formname => 'document.cu',
                   3104:               kerb_def_dom => 'MSU.EDU',
                   3105:               @_,
                   3106:               );
1.1075.2.117  raeburn  3107:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3108:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3109:     if ($in{'readonly'}) {
                   3110:         $disabled = ' disabled="disabled"';
                   3111:     }
1.591     raeburn  3112:     if (defined($in{'curr_authtype'})) {
                   3113:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3114:             if ($can_assign{'fsys'}) {
1.772     bisitz   3115:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3116:                 if (defined($in{'mode'})) {
                   3117:                     if ($in{'mode'} eq 'modifyuser') {
                   3118:                         $fsyscheck = '';
                   3119:                     }
                   3120:                 }
1.586     raeburn  3121:             } else {
                   3122:                 $result = &mt('Currently Filesystem Authenticated.');
                   3123:                 return $result;
                   3124:             }           
                   3125:         }
                   3126:     } else {
                   3127:         if ($authnum == 1) {
1.784     bisitz   3128:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3129:         }
                   3130:     }
                   3131:     if (!$can_assign{'fsys'}) {
                   3132:         return;
1.587     raeburn  3133:     } elsif ($authtype eq '') {
1.591     raeburn  3134:         if (defined($in{'mode'})) {
1.587     raeburn  3135:             if ($in{'mode'} eq 'modifycourse') {
                   3136:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3137:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3138:                 }
                   3139:             }
                   3140:         }
1.586     raeburn  3141:     }
                   3142:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3143:     if ($authtype eq '') {
                   3144:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3145:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3146:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3147:     }
1.1075.2.158  raeburn  3148:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3149:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3150:     $result = &mt
1.144     matthew  3151:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1075.2.158  raeburn  3152:          '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3153:     return $result;
                   3154: }
                   3155: 
1.586     raeburn  3156: sub get_assignable_auth {
                   3157:     my ($dom) = @_;
                   3158:     if ($dom eq '') {
                   3159:         $dom = $env{'request.role.domain'};
                   3160:     }
                   3161:     my %can_assign = (
                   3162:                           krb4 => 1,
                   3163:                           krb5 => 1,
                   3164:                           int  => 1,
                   3165:                           loc  => 1,
                   3166:                      );
                   3167:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3168:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3169:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3170:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3171:             my $context;
                   3172:             if ($env{'request.role'} =~ /^au/) {
                   3173:                 $context = 'author';
1.1075.2.117  raeburn  3174:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3175:                 $context = 'domain';
                   3176:             } elsif ($env{'request.course.id'}) {
                   3177:                 $context = 'course';
                   3178:             }
                   3179:             if ($context) {
                   3180:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3181:                    %can_assign = %{$authhash->{$context}}; 
                   3182:                 }
                   3183:             }
                   3184:         }
                   3185:     }
                   3186:     my $authnum = 0;
                   3187:     foreach my $key (keys(%can_assign)) {
                   3188:         if ($can_assign{$key}) {
                   3189:             $authnum ++;
                   3190:         }
                   3191:     }
                   3192:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3193:         $authnum --;
                   3194:     }
                   3195:     return ($authnum,%can_assign);
                   3196: }
                   3197: 
1.1075.2.137  raeburn  3198: sub check_passwd_rules {
                   3199:     my ($domain,$plainpass) = @_;
                   3200:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3201:     my ($min,$max,@chars,@brokerule,$warning);
1.1075.2.138  raeburn  3202:     $min = $Apache::lonnet::passwdmin;
1.1075.2.137  raeburn  3203:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3204:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1075.2.138  raeburn  3205:             if ($passwdconf{'min'} > $min) {
                   3206:                 $min = $passwdconf{'min'};
                   3207:             }
1.1075.2.137  raeburn  3208:         }
                   3209:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3210:             $max = $passwdconf{'max'};
                   3211:         }
                   3212:         @chars = @{$passwdconf{'chars'}};
                   3213:     }
                   3214:     if (($min) && (length($plainpass) < $min)) {
                   3215:         push(@brokerule,'min');
                   3216:     }
                   3217:     if (($max) && (length($plainpass) > $max)) {
                   3218:         push(@brokerule,'max');
                   3219:     }
                   3220:     if (@chars) {
                   3221:         my %rules;
                   3222:         map { $rules{$_} = 1; } @chars;
                   3223:         if ($rules{'uc'}) {
                   3224:             unless ($plainpass =~ /[A-Z]/) {
                   3225:                 push(@brokerule,'uc');
                   3226:             }
                   3227:         }
                   3228:         if ($rules{'lc'}) {
                   3229:             unless ($plainpass =~ /[a-z]/) {
                   3230:                 push(@brokerule,'lc');
                   3231:             }
                   3232:         }
                   3233:         if ($rules{'num'}) {
                   3234:             unless ($plainpass =~ /\d/) {
                   3235:                 push(@brokerule,'num');
                   3236:             }
                   3237:         }
                   3238:         if ($rules{'spec'}) {
                   3239:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3240:                 push(@brokerule,'spec');
                   3241:             }
                   3242:         }
                   3243:     }
                   3244:     if (@brokerule) {
                   3245:         my %rulenames = &Apache::lonlocal::texthash(
                   3246:             uc   => 'At least one upper case letter',
                   3247:             lc   => 'At least one lower case letter',
                   3248:             num  => 'At least one number',
                   3249:             spec => 'At least one non-alphanumeric',
                   3250:         );
                   3251:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3252:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3253:         $rulenames{'num'} .= ': 0123456789';
                   3254:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3255:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3256:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3257:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1075.2.143  raeburn  3258:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1075.2.137  raeburn  3259:             if (grep(/^$rule$/,@brokerule)) {
                   3260:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3261:             }
                   3262:         }
                   3263:         $warning .= '</ul>';
                   3264:     }
                   3265:     if (wantarray) {
                   3266:         return @brokerule;
                   3267:     }
                   3268:     return $warning;
                   3269: }
                   3270: 
1.1075.2.161.  .5(raebu 3271:22): sub passwd_validation_js {
                   3272:22):     my ($currpasswdval,$domain,$context,$id) = @_;
                   3273:22):     my (%passwdconf,$alertmsg);
                   3274:22):     if ($context eq 'linkprot') {
                   3275:22):         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3276:22):         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3277:22):             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3278:22):                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3279:22):             }
                   3280:22):         }
                   3281:22):         if ($id eq 'add') {
                   3282:22):             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3283:22):         } elsif ($id =~ /^\d+$/) {
                   3284:22):             my $pos = $id+1;
                   3285:22):             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3286:22):         } else {
                   3287:22):             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3288:22):         }
                   3289:22):     } else {
                   3290:22):         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3291:22):         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3292:22):     }
                   3293:22):     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3294:22):     $numrules = 0;
                   3295:22):     $min = $Apache::lonnet::passwdmin;
                   3296:22):     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3297:22):         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3298:22):             if ($passwdconf{'min'} > $min) {
                   3299:22):                 $min = $passwdconf{'min'};
                   3300:22):             }
                   3301:22):         }
                   3302:22):         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3303:22):             $max = $passwdconf{'max'};
                   3304:22):             $numrules ++;
                   3305:22):         }
                   3306:22):         @chars = @{$passwdconf{'chars'}};
                   3307:22):         if (@chars) {
                   3308:22):             $numrules ++;
                   3309:22):         }
                   3310:22):     }
                   3311:22):     if ($min > 0) {
                   3312:22):         $numrules ++;
                   3313:22):     }
                   3314:22):     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3315:22):         if ($min) {
                   3316:22):             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3317:22):         }
                   3318:22):         if ($max) {
                   3319:22):             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3320:22):         }
                   3321:22):         my (@charalerts,@charrules);
                   3322:22):         if (@chars) {
                   3323:22):             if (grep(/^uc$/,@chars)) {
                   3324:22):                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3325:22):                 push(@charrules,'uc');
                   3326:22):             }
                   3327:22):             if (grep(/^lc$/,@chars)) {
                   3328:22):                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3329:22):                 push(@charrules,'lc');
                   3330:22):             }
                   3331:22):             if (grep(/^num$/,@chars)) {
                   3332:22):                 push(@charalerts,&mt('contain at least one number'));
                   3333:22):                 push(@charrules,'num');
                   3334:22):             }
                   3335:22):             if (grep(/^spec$/,@chars)) {
                   3336:22):                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3337:22):                 push(@charrules,'spec');
                   3338:22):             }
                   3339:22):         }
                   3340:22):         $intargjs = qq|            var rulesmsg = '';\n|.
                   3341:22):                     qq|            var currpwval = $currpasswdval;\n|;
                   3342:22):             if ($min) {
                   3343:22):                 $intargjs .= qq|
                   3344:22):             if (currpwval.length < $min) {
                   3345:22):                 rulesmsg += ' - $alert{min}';
                   3346:22):             }
                   3347:22): |;
                   3348:22):             }
                   3349:22):             if ($max) {
                   3350:22):                 $intargjs .= qq|
                   3351:22):             if (currpwval.length > $max) {
                   3352:22):                 rulesmsg += ' - $alert{max}';
                   3353:22):             }
                   3354:22): |;
                   3355:22):             }
                   3356:22):             if (@chars > 0) {
                   3357:22):                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3358:22):                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3359:22):                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3360:22):                              qq|            var charrules = new Array($charrulestr);\n|.
                   3361:22):                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3362:22):                 my %rules;
                   3363:22):                 map { $rules{$_} = 1; } @chars;
                   3364:22):                 if ($rules{'uc'}) {
                   3365:22):                     $intargjs .= qq|
                   3366:22):             var ucRegExp = /[A-Z]/;
                   3367:22):             if (!ucRegExp.test(currpwval)) {
                   3368:22):                 brokerules.push('uc');
                   3369:22):             }
                   3370:22): |;
                   3371:22):                 }
                   3372:22):                 if ($rules{'lc'}) {
                   3373:22):                     $intargjs .= qq|
                   3374:22):             var lcRegExp = /[a-z]/;
                   3375:22):             if (!lcRegExp.test(currpwval)) {
                   3376:22):                 brokerules.push('lc');
                   3377:22):             }
                   3378:22): |;
                   3379:22):                 }
                   3380:22):                 if ($rules{'num'}) {
                   3381:22):                      $intargjs .= qq|
                   3382:22):             var numRegExp = /[0-9]/;
                   3383:22):             if (!numRegExp.test(currpwval)) {
                   3384:22):                 brokerules.push('num');
                   3385:22):             }
                   3386:22): |;
                   3387:22):                 }
                   3388:22):                 if ($rules{'spec'}) {
                   3389:22):                      $intargjs .= q|
                   3390:22):             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3391:22):             if (!specRegExp.test(currpwval)) {
                   3392:22):                 brokerules.push('spec');
                   3393:22):             }
                   3394:22): |;
                   3395:22):                 }
                   3396:22):                 $intargjs .= qq|
                   3397:22):             if (brokerules.length > 0) {
                   3398:22):                 for (var i=0; i<brokerules.length; i++) {
                   3399:22):                     for (var j=0; j<charrules.length; j++) {
                   3400:22):                         if (brokerules[i] == charrules[j]) {
                   3401:22):                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   3402:22):                             break;
                   3403:22):                         }
                   3404:22):                     }
                   3405:22):                 }
                   3406:22):             }
                   3407:22): |;
                   3408:22):             }
                   3409:22):             $intargjs .= qq|
                   3410:22):             if (rulesmsg != '') {
                   3411:22):                 rulesmsg = '$alertmsg'+rulesmsg;
                   3412:22):                 alert(rulesmsg);
                   3413:22):                 return false;
                   3414:22):             }
                   3415:22): |;
                   3416:22):     }
                   3417:22):     return ($numrules,$intargjs);
                   3418:22): }
                   3419:22): 
1.80      albertel 3420: ###############################################################
                   3421: ##    Get Kerberos Defaults for Domain                 ##
                   3422: ###############################################################
                   3423: ##
                   3424: ## Returns default kerberos version and an associated argument
                   3425: ## as listed in file domain.tab. If not listed, provides
                   3426: ## appropriate default domain and kerberos version.
                   3427: ##
                   3428: #-------------------------------------------
                   3429: 
                   3430: =pod
                   3431: 
1.648     raeburn  3432: =item * &get_kerberos_defaults()
1.80      albertel 3433: 
                   3434: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3435: version and domain. If not found, it defaults to version 4 and the 
                   3436: domain of the server.
1.80      albertel 3437: 
1.648     raeburn  3438: =over 4
                   3439: 
1.80      albertel 3440: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3441: 
1.648     raeburn  3442: =back
                   3443: 
                   3444: =back
                   3445: 
1.80      albertel 3446: =cut
                   3447: 
                   3448: #-------------------------------------------
                   3449: sub get_kerberos_defaults {
                   3450:     my $domain=shift;
1.641     raeburn  3451:     my ($krbdef,$krbdefdom);
                   3452:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3453:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3454:         $krbdef = $domdefaults{'auth_def'};
                   3455:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3456:     } else {
1.80      albertel 3457:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3458:         my $krbdefdom=$1;
                   3459:         $krbdefdom=~tr/a-z/A-Z/;
                   3460:         $krbdef = "krb4";
                   3461:     }
                   3462:     return ($krbdef,$krbdefdom);
                   3463: }
1.112     bowersj2 3464: 
1.32      matthew  3465: 
1.46      matthew  3466: ###############################################################
                   3467: ##                Thesaurus Functions                        ##
                   3468: ###############################################################
1.20      www      3469: 
1.46      matthew  3470: =pod
1.20      www      3471: 
1.112     bowersj2 3472: =head1 Thesaurus Functions
                   3473: 
                   3474: =over 4
                   3475: 
1.648     raeburn  3476: =item * &initialize_keywords()
1.46      matthew  3477: 
                   3478: Initializes the package variable %Keywords if it is empty.  Uses the
                   3479: package variable $thesaurus_db_file.
                   3480: 
                   3481: =cut
                   3482: 
                   3483: ###################################################
                   3484: 
                   3485: sub initialize_keywords {
                   3486:     return 1 if (scalar keys(%Keywords));
                   3487:     # If we are here, %Keywords is empty, so fill it up
                   3488:     #   Make sure the file we need exists...
                   3489:     if (! -e $thesaurus_db_file) {
                   3490:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3491:                                  " failed because it does not exist");
                   3492:         return 0;
                   3493:     }
                   3494:     #   Set up the hash as a database
                   3495:     my %thesaurus_db;
                   3496:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3497:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3498:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3499:                                  $thesaurus_db_file);
                   3500:         return 0;
                   3501:     } 
                   3502:     #  Get the average number of appearances of a word.
                   3503:     my $avecount = $thesaurus_db{'average.count'};
                   3504:     #  Put keywords (those that appear > average) into %Keywords
                   3505:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3506:         my ($count,undef) = split /:/,$data;
                   3507:         $Keywords{$word}++ if ($count > $avecount);
                   3508:     }
                   3509:     untie %thesaurus_db;
                   3510:     # Remove special values from %Keywords.
1.356     albertel 3511:     foreach my $value ('total.count','average.count') {
                   3512:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3513:   }
1.46      matthew  3514:     return 1;
                   3515: }
                   3516: 
                   3517: ###################################################
                   3518: 
                   3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &keyword($word)
1.46      matthew  3522: 
                   3523: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3524: than the average number of times in the thesaurus database.  Calls 
                   3525: &initialize_keywords
                   3526: 
                   3527: =cut
                   3528: 
                   3529: ###################################################
1.20      www      3530: 
                   3531: sub keyword {
1.46      matthew  3532:     return if (!&initialize_keywords());
                   3533:     my $word=lc(shift());
                   3534:     $word=~s/\W//g;
                   3535:     return exists($Keywords{$word});
1.20      www      3536: }
1.46      matthew  3537: 
                   3538: ###############################################################
                   3539: 
                   3540: =pod 
1.20      www      3541: 
1.648     raeburn  3542: =item * &get_related_words()
1.46      matthew  3543: 
1.160     matthew  3544: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3545: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3546: will be returned.  The order of the words returned is determined by the
                   3547: database which holds them.
                   3548: 
                   3549: Uses global $thesaurus_db_file.
                   3550: 
1.1057    foxr     3551: 
1.46      matthew  3552: =cut
                   3553: 
                   3554: ###############################################################
                   3555: sub get_related_words {
                   3556:     my $keyword = shift;
                   3557:     my %thesaurus_db;
                   3558:     if (! -e $thesaurus_db_file) {
                   3559:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3560:                                  "failed because the file does not exist");
                   3561:         return ();
                   3562:     }
                   3563:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3564:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3565:         return ();
                   3566:     } 
                   3567:     my @Words=();
1.429     www      3568:     my $count=0;
1.46      matthew  3569:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3570: 	# The first element is the number of times
                   3571: 	# the word appears.  We do not need it now.
1.429     www      3572: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3573: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3574: 	my $threshold=$mostfrequentcount/10;
                   3575:         foreach my $possibleword (@RelatedWords) {
                   3576:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3577:             if ($wordcount>$threshold) {
                   3578: 		push(@Words,$word);
                   3579:                 $count++;
                   3580:                 if ($count>10) { last; }
                   3581: 	    }
1.20      www      3582:         }
                   3583:     }
1.46      matthew  3584:     untie %thesaurus_db;
                   3585:     return @Words;
1.14      harris41 3586: }
1.46      matthew  3587: 
1.112     bowersj2 3588: =pod
                   3589: 
                   3590: =back
                   3591: 
                   3592: =cut
1.61      www      3593: 
                   3594: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3595: =pod
                   3596: 
1.112     bowersj2 3597: =head1 User Name Functions
                   3598: 
                   3599: =over 4
                   3600: 
1.648     raeburn  3601: =item * &plainname($uname,$udom,$first)
1.81      albertel 3602: 
1.112     bowersj2 3603: Takes a users logon name and returns it as a string in
1.226     albertel 3604: "first middle last generation" form 
                   3605: if $first is set to 'lastname' then it returns it as
                   3606: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3607: 
                   3608: =cut
1.61      www      3609: 
1.295     www      3610: 
1.81      albertel 3611: ###############################################################
1.61      www      3612: sub plainname {
1.226     albertel 3613:     my ($uname,$udom,$first)=@_;
1.537     albertel 3614:     return if (!defined($uname) || !defined($udom));
1.295     www      3615:     my %names=&getnames($uname,$udom);
1.226     albertel 3616:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3617: 					  $names{'middlename'},
                   3618: 					  $names{'lastname'},
                   3619: 					  $names{'generation'},$first);
                   3620:     $name=~s/^\s+//;
1.62      www      3621:     $name=~s/\s+$//;
                   3622:     $name=~s/\s+/ /g;
1.353     albertel 3623:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3624:     return $name;
1.61      www      3625: }
1.66      www      3626: 
                   3627: # -------------------------------------------------------------------- Nickname
1.81      albertel 3628: =pod
                   3629: 
1.648     raeburn  3630: =item * &nickname($uname,$udom)
1.81      albertel 3631: 
                   3632: Gets a users name and returns it as a string as
                   3633: 
                   3634: "&quot;nickname&quot;"
1.66      www      3635: 
1.81      albertel 3636: if the user has a nickname or
                   3637: 
                   3638: "first middle last generation"
                   3639: 
                   3640: if the user does not
                   3641: 
                   3642: =cut
1.66      www      3643: 
                   3644: sub nickname {
                   3645:     my ($uname,$udom)=@_;
1.537     albertel 3646:     return if (!defined($uname) || !defined($udom));
1.295     www      3647:     my %names=&getnames($uname,$udom);
1.68      albertel 3648:     my $name=$names{'nickname'};
1.66      www      3649:     if ($name) {
                   3650:        $name='&quot;'.$name.'&quot;'; 
                   3651:     } else {
                   3652:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3653: 	     $names{'lastname'}.' '.$names{'generation'};
                   3654:        $name=~s/\s+$//;
                   3655:        $name=~s/\s+/ /g;
                   3656:     }
                   3657:     return $name;
                   3658: }
                   3659: 
1.295     www      3660: sub getnames {
                   3661:     my ($uname,$udom)=@_;
1.537     albertel 3662:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3663:     if ($udom eq 'public' && $uname eq 'public') {
                   3664: 	return ('lastname' => &mt('Public'));
                   3665:     }
1.295     www      3666:     my $id=$uname.':'.$udom;
                   3667:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3668:     if ($cached) {
                   3669: 	return %{$names};
                   3670:     } else {
                   3671: 	my %loadnames=&Apache::lonnet::get('environment',
                   3672:                     ['firstname','middlename','lastname','generation','nickname'],
                   3673: 					 $udom,$uname);
                   3674: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3675: 	return %loadnames;
                   3676:     }
                   3677: }
1.61      www      3678: 
1.542     raeburn  3679: # -------------------------------------------------------------------- getemails
1.648     raeburn  3680: 
1.542     raeburn  3681: =pod
                   3682: 
1.648     raeburn  3683: =item * &getemails($uname,$udom)
1.542     raeburn  3684: 
                   3685: Gets a user's email information and returns it as a hash with keys:
                   3686: notification, critnotification, permanentemail
                   3687: 
                   3688: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3689: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3690:  
1.648     raeburn  3691: 
1.542     raeburn  3692: =cut
                   3693: 
1.648     raeburn  3694: 
1.466     albertel 3695: sub getemails {
                   3696:     my ($uname,$udom)=@_;
                   3697:     if ($udom eq 'public' && $uname eq 'public') {
                   3698: 	return;
                   3699:     }
1.467     www      3700:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3701:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3702:     my $id=$uname.':'.$udom;
                   3703:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3704:     if ($cached) {
                   3705: 	return %{$names};
                   3706:     } else {
                   3707: 	my %loadnames=&Apache::lonnet::get('environment',
                   3708:                     			   ['notification','critnotification',
                   3709: 					    'permanentemail'],
                   3710: 					   $udom,$uname);
                   3711: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3712: 	return %loadnames;
                   3713:     }
                   3714: }
                   3715: 
1.551     albertel 3716: sub flush_email_cache {
                   3717:     my ($uname,$udom)=@_;
                   3718:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3719:     if (!$uname) { $uname=$env{'user.name'};   }
                   3720:     return if ($udom eq 'public' && $uname eq 'public');
                   3721:     my $id=$uname.':'.$udom;
                   3722:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3723: }
                   3724: 
1.728     raeburn  3725: # -------------------------------------------------------------------- getlangs
                   3726: 
                   3727: =pod
                   3728: 
                   3729: =item * &getlangs($uname,$udom)
                   3730: 
                   3731: Gets a user's language preference and returns it as a hash with key:
                   3732: language.
                   3733: 
                   3734: =cut
                   3735: 
                   3736: 
                   3737: sub getlangs {
                   3738:     my ($uname,$udom) = @_;
                   3739:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3740:     if (!$uname) { $uname=$env{'user.name'};   }
                   3741:     my $id=$uname.':'.$udom;
                   3742:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3743:     if ($cached) {
                   3744:         return %{$langs};
                   3745:     } else {
                   3746:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3747:                                            $udom,$uname);
                   3748:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3749:         return %loadlangs;
                   3750:     }
                   3751: }
                   3752: 
                   3753: sub flush_langs_cache {
                   3754:     my ($uname,$udom)=@_;
                   3755:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3756:     if (!$uname) { $uname=$env{'user.name'};   }
                   3757:     return if ($udom eq 'public' && $uname eq 'public');
                   3758:     my $id=$uname.':'.$udom;
                   3759:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3760: }
                   3761: 
1.61      www      3762: # ------------------------------------------------------------------ Screenname
1.81      albertel 3763: 
                   3764: =pod
                   3765: 
1.648     raeburn  3766: =item * &screenname($uname,$udom)
1.81      albertel 3767: 
                   3768: Gets a users screenname and returns it as a string
                   3769: 
                   3770: =cut
1.61      www      3771: 
                   3772: sub screenname {
                   3773:     my ($uname,$udom)=@_;
1.258     albertel 3774:     if ($uname eq $env{'user.name'} &&
                   3775: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3776:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3777:     return $names{'screenname'};
1.62      www      3778: }
                   3779: 
1.212     albertel 3780: 
1.802     bisitz   3781: # ------------------------------------------------------------- Confirm Wrapper
                   3782: =pod
                   3783: 
1.1075.2.42  raeburn  3784: =item * &confirmwrapper($message)
1.802     bisitz   3785: 
                   3786: Wrap messages about completion of operation in box
                   3787: 
                   3788: =cut
                   3789: 
                   3790: sub confirmwrapper {
                   3791:     my ($message)=@_;
                   3792:     if ($message) {
                   3793:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3794:                .$message."\n"
                   3795:                .'</div>'."\n";
                   3796:     } else {
                   3797:         return $message;
                   3798:     }
                   3799: }
                   3800: 
1.62      www      3801: # ------------------------------------------------------------- Message Wrapper
                   3802: 
                   3803: sub messagewrapper {
1.369     www      3804:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3805:     return 
1.441     albertel 3806:         '<a href="/adm/email?compose=individual&amp;'.
                   3807:         'recname='.$username.'&amp;recdom='.$domain.
                   3808: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3809:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3810: }
1.802     bisitz   3811: 
1.74      www      3812: # --------------------------------------------------------------- Notes Wrapper
                   3813: 
                   3814: sub noteswrapper {
                   3815:     my ($link,$un,$do)=@_;
                   3816:     return 
1.896     amueller 3817: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3818: }
1.802     bisitz   3819: 
1.62      www      3820: # ------------------------------------------------------------- Aboutme Wrapper
                   3821: 
                   3822: sub aboutmewrapper {
1.1070    raeburn  3823:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3824:     if (!defined($username)  && !defined($domain)) {
                   3825:         return;
                   3826:     }
1.1075.2.15  raeburn  3827:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3828: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3829: }
                   3830: 
                   3831: # ------------------------------------------------------------ Syllabus Wrapper
                   3832: 
                   3833: sub syllabuswrapper {
1.707     bisitz   3834:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3835:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3836: }
1.14      harris41 3837: 
1.1075.2.161.  .11(raeb 3838:-22): sub aboutme_on {
                   3839:-22):     my ($uname,$udom)=@_;
                   3840:-22):     unless ($uname) { $uname=$env{'user.name'}; }
                   3841:-22):     unless ($udom)  { $udom=$env{'user.domain'}; }
                   3842:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3843:-22):     my $hashkey=$uname.':'.$udom;
                   3844:-22):     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   3845:-22):     if ($cached) {
                   3846:-22):         return $aboutme;
                   3847:-22):     }
                   3848:-22):     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   3849:-22):     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   3850:-22):     return $aboutme;
                   3851:-22): }
                   3852:-22): 
                   3853:-22): sub devalidate_aboutme_cache {
                   3854:-22):     my ($uname,$udom)=@_;
                   3855:-22):     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3856:-22):     if (!$uname) { $uname=$env{'user.name'};   }
                   3857:-22):     return if ($udom eq 'public' && $uname eq 'public');
                   3858:-22):     my $id=$uname.':'.$udom;
                   3859:-22):     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   3860:-22): }
                   3861:-22): 
1.802     bisitz   3862: # -----------------------------------------------------------------------------
                   3863: 
1.208     matthew  3864: sub track_student_link {
1.887     raeburn  3865:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3866:     my $link ="/adm/trackstudent?";
1.208     matthew  3867:     my $title = 'View recent activity';
                   3868:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3869:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3870:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3871:         $title .= ' of this student';
1.268     albertel 3872:     } 
1.208     matthew  3873:     if (defined($target) && $target !~ /^\s*$/) {
                   3874:         $target = qq{target="$target"};
                   3875:     } else {
                   3876:         $target = '';
                   3877:     }
1.268     albertel 3878:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3879:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3880:     $title = &mt($title);
                   3881:     $linktext = &mt($linktext);
1.448     albertel 3882:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3883: 	&help_open_topic('View_recent_activity');
1.208     matthew  3884: }
                   3885: 
1.781     raeburn  3886: sub slot_reservations_link {
                   3887:     my ($linktext,$sname,$sdom,$target) = @_;
                   3888:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3889:     my $title = 'View slot reservation history';
                   3890:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3891:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3892:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3893:         $title .= ' of this student';
                   3894:     }
                   3895:     if (defined($target) && $target !~ /^\s*$/) {
                   3896:         $target = qq{target="$target"};
                   3897:     } else {
                   3898:         $target = '';
                   3899:     }
                   3900:     $title = &mt($title);
                   3901:     $linktext = &mt($linktext);
                   3902:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3903: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3904: 
                   3905: }
                   3906: 
1.508     www      3907: # ===================================================== Display a student photo
                   3908: 
                   3909: 
1.509     albertel 3910: sub student_image_tag {
1.508     www      3911:     my ($domain,$user)=@_;
                   3912:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3913:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3914: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3915:     } else {
                   3916: 	return '';
                   3917:     }
                   3918: }
                   3919: 
1.112     bowersj2 3920: =pod
                   3921: 
                   3922: =back
                   3923: 
                   3924: =head1 Access .tab File Data
                   3925: 
                   3926: =over 4
                   3927: 
1.648     raeburn  3928: =item * &languageids() 
1.112     bowersj2 3929: 
                   3930: returns list of all language ids
                   3931: 
                   3932: =cut
                   3933: 
1.14      harris41 3934: sub languageids {
1.16      harris41 3935:     return sort(keys(%language));
1.14      harris41 3936: }
                   3937: 
1.112     bowersj2 3938: =pod
                   3939: 
1.648     raeburn  3940: =item * &languagedescription() 
1.112     bowersj2 3941: 
                   3942: returns description of a specified language id
                   3943: 
                   3944: =cut
                   3945: 
1.14      harris41 3946: sub languagedescription {
1.125     www      3947:     my $code=shift;
                   3948:     return  ($supported_language{$code}?'* ':'').
                   3949:             $language{$code}.
1.126     www      3950: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3951: }
                   3952: 
1.1048    foxr     3953: =pod
                   3954: 
                   3955: =item * &plainlanguagedescription
                   3956: 
                   3957: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3958: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3959: 
                   3960: =cut
                   3961: 
1.145     www      3962: sub plainlanguagedescription {
                   3963:     my $code=shift;
                   3964:     return $language{$code};
                   3965: }
                   3966: 
1.1048    foxr     3967: =pod
                   3968: 
                   3969: =item * &supportedlanguagecode
                   3970: 
                   3971: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3972: code.
                   3973: 
                   3974: =cut
                   3975: 
1.145     www      3976: sub supportedlanguagecode {
                   3977:     my $code=shift;
                   3978:     return $supported_language{$code};
1.97      www      3979: }
                   3980: 
1.112     bowersj2 3981: =pod
                   3982: 
1.1048    foxr     3983: =item * &latexlanguage()
                   3984: 
                   3985: Given a language key code returns the correspondnig language to use
                   3986: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3987: is no supported hyphenation for the language code.
                   3988: 
                   3989: =cut
                   3990: 
                   3991: sub latexlanguage {
                   3992:     my $code = shift;
                   3993:     return $latex_language{$code};
                   3994: }
                   3995: 
                   3996: =pod
                   3997: 
                   3998: =item * &latexhyphenation()
                   3999: 
                   4000: Same as above but what's supplied is the language as it might be stored
                   4001: in the metadata.
                   4002: 
                   4003: =cut
                   4004: 
                   4005: sub latexhyphenation {
                   4006:     my $key = shift;
                   4007:     return $latex_language_bykey{$key};
                   4008: }
                   4009: 
                   4010: =pod
                   4011: 
1.648     raeburn  4012: =item * &copyrightids() 
1.112     bowersj2 4013: 
                   4014: returns list of all copyrights
                   4015: 
                   4016: =cut
                   4017: 
                   4018: sub copyrightids {
                   4019:     return sort(keys(%cprtag));
                   4020: }
                   4021: 
                   4022: =pod
                   4023: 
1.648     raeburn  4024: =item * &copyrightdescription() 
1.112     bowersj2 4025: 
                   4026: returns description of a specified copyright id
                   4027: 
                   4028: =cut
                   4029: 
                   4030: sub copyrightdescription {
1.166     www      4031:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4032: }
1.197     matthew  4033: 
                   4034: =pod
                   4035: 
1.648     raeburn  4036: =item * &source_copyrightids() 
1.192     taceyjo1 4037: 
                   4038: returns list of all source copyrights
                   4039: 
                   4040: =cut
                   4041: 
                   4042: sub source_copyrightids {
                   4043:     return sort(keys(%scprtag));
                   4044: }
                   4045: 
                   4046: =pod
                   4047: 
1.648     raeburn  4048: =item * &source_copyrightdescription() 
1.192     taceyjo1 4049: 
                   4050: returns description of a specified source copyright id
                   4051: 
                   4052: =cut
                   4053: 
                   4054: sub source_copyrightdescription {
                   4055:     return &mt($scprtag{shift(@_)});
                   4056: }
1.112     bowersj2 4057: 
                   4058: =pod
                   4059: 
1.648     raeburn  4060: =item * &filecategories() 
1.112     bowersj2 4061: 
                   4062: returns list of all file categories
                   4063: 
                   4064: =cut
                   4065: 
                   4066: sub filecategories {
                   4067:     return sort(keys(%category_extensions));
                   4068: }
                   4069: 
                   4070: =pod
                   4071: 
1.648     raeburn  4072: =item * &filecategorytypes() 
1.112     bowersj2 4073: 
                   4074: returns list of file types belonging to a given file
                   4075: category
                   4076: 
                   4077: =cut
                   4078: 
                   4079: sub filecategorytypes {
1.356     albertel 4080:     my ($cat) = @_;
                   4081:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 4082: }
                   4083: 
                   4084: =pod
                   4085: 
1.648     raeburn  4086: =item * &fileembstyle() 
1.112     bowersj2 4087: 
                   4088: returns embedding style for a specified file type
                   4089: 
                   4090: =cut
                   4091: 
                   4092: sub fileembstyle {
                   4093:     return $fe{lc(shift(@_))};
1.169     www      4094: }
                   4095: 
1.351     www      4096: sub filemimetype {
                   4097:     return $fm{lc(shift(@_))};
                   4098: }
                   4099: 
1.169     www      4100: 
                   4101: sub filecategoryselect {
                   4102:     my ($name,$value)=@_;
1.189     matthew  4103:     return &select_form($value,$name,
1.970     raeburn  4104:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4105: }
                   4106: 
                   4107: =pod
                   4108: 
1.648     raeburn  4109: =item * &filedescription() 
1.112     bowersj2 4110: 
                   4111: returns description for a specified file type
                   4112: 
                   4113: =cut
                   4114: 
                   4115: sub filedescription {
1.188     matthew  4116:     my $file_description = $fd{lc(shift())};
                   4117:     $file_description =~ s:([\[\]]):~$1:g;
                   4118:     return &mt($file_description);
1.112     bowersj2 4119: }
                   4120: 
                   4121: =pod
                   4122: 
1.648     raeburn  4123: =item * &filedescriptionex() 
1.112     bowersj2 4124: 
                   4125: returns description for a specified file type with
                   4126: extra formatting
                   4127: 
                   4128: =cut
                   4129: 
                   4130: sub filedescriptionex {
                   4131:     my $ex=shift;
1.188     matthew  4132:     my $file_description = $fd{lc($ex)};
                   4133:     $file_description =~ s:([\[\]]):~$1:g;
                   4134:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4135: }
                   4136: 
                   4137: # End of .tab access
                   4138: =pod
                   4139: 
                   4140: =back
                   4141: 
                   4142: =cut
                   4143: 
                   4144: # ------------------------------------------------------------------ File Types
                   4145: sub fileextensions {
                   4146:     return sort(keys(%fe));
                   4147: }
                   4148: 
1.97      www      4149: # ----------------------------------------------------------- Display Languages
                   4150: # returns a hash with all desired display languages
                   4151: #
                   4152: 
                   4153: sub display_languages {
                   4154:     my %languages=();
1.695     raeburn  4155:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4156: 	$languages{$lang}=1;
1.97      www      4157:     }
                   4158:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4159:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4160: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4161: 	    $languages{$lang}=1;
1.97      www      4162:         }
                   4163:     }
                   4164:     return %languages;
1.14      harris41 4165: }
                   4166: 
1.582     albertel 4167: sub languages {
                   4168:     my ($possible_langs) = @_;
1.695     raeburn  4169:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4170:     if (!ref($possible_langs)) {
                   4171: 	if( wantarray ) {
                   4172: 	    return @preferred_langs;
                   4173: 	} else {
                   4174: 	    return $preferred_langs[0];
                   4175: 	}
                   4176:     }
                   4177:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4178:     my @preferred_possibilities;
                   4179:     foreach my $preferred_lang (@preferred_langs) {
                   4180: 	if (exists($possibilities{$preferred_lang})) {
                   4181: 	    push(@preferred_possibilities, $preferred_lang);
                   4182: 	}
                   4183:     }
                   4184:     if( wantarray ) {
                   4185: 	return @preferred_possibilities;
                   4186:     }
                   4187:     return $preferred_possibilities[0];
                   4188: }
                   4189: 
1.742     raeburn  4190: sub user_lang {
                   4191:     my ($touname,$toudom,$fromcid) = @_;
                   4192:     my @userlangs;
                   4193:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4194:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4195:                     $env{'course.'.$fromcid.'.languages'}));
                   4196:     } else {
                   4197:         my %langhash = &getlangs($touname,$toudom);
                   4198:         if ($langhash{'languages'} ne '') {
                   4199:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4200:         } else {
                   4201:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4202:             if ($domdefs{'lang_def'} ne '') {
                   4203:                 @userlangs = ($domdefs{'lang_def'});
                   4204:             }
                   4205:         }
                   4206:     }
                   4207:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4208:     my $user_lh = Apache::localize->get_handle(@languages);
                   4209:     return $user_lh;
                   4210: }
                   4211: 
                   4212: 
1.112     bowersj2 4213: ###############################################################
                   4214: ##               Student Answer Attempts                     ##
                   4215: ###############################################################
                   4216: 
                   4217: =pod
                   4218: 
                   4219: =head1 Alternate Problem Views
                   4220: 
                   4221: =over 4
                   4222: 
1.648     raeburn  4223: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  4224:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4225: 
                   4226: Return string with previous attempt on problem. Arguments:
                   4227: 
                   4228: =over 4
                   4229: 
                   4230: =item * $symb: Problem, including path
                   4231: 
                   4232: =item * $username: username of the desired student
                   4233: 
                   4234: =item * $domain: domain of the desired student
1.14      harris41 4235: 
1.112     bowersj2 4236: =item * $course: Course ID
1.14      harris41 4237: 
1.112     bowersj2 4238: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4239:     something
1.14      harris41 4240: 
1.112     bowersj2 4241: =item * $regexp: if string matches this regexp, the string will be
                   4242:     sent to $gradesub
1.14      harris41 4243: 
1.112     bowersj2 4244: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4245: 
1.1075.2.86  raeburn  4246: =item * $usec: section of the desired student
                   4247: 
                   4248: =item * $identifier: counter for student (multiple students one problem) or
                   4249:     problem (one student; whole sequence).
                   4250: 
1.112     bowersj2 4251: =back
1.14      harris41 4252: 
1.112     bowersj2 4253: The output string is a table containing all desired attempts, if any.
1.16      harris41 4254: 
1.112     bowersj2 4255: =cut
1.1       albertel 4256: 
                   4257: sub get_previous_attempt {
1.1075.2.86  raeburn  4258:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4259:   my $prevattempts='';
1.43      ng       4260:   no strict 'refs';
1.1       albertel 4261:   if ($symb) {
1.3       albertel 4262:     my (%returnhash)=
                   4263:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4264:     if ($returnhash{'version'}) {
                   4265:       my %lasthash=();
                   4266:       my $version;
                   4267:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  4268:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4269:             if ($key =~ /\.rawrndseed$/) {
                   4270:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4271:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4272:             } else {
                   4273:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4274:             }
1.19      harris41 4275:         }
1.1       albertel 4276:       }
1.596     albertel 4277:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4278:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4279:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4280:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4281:       foreach my $key (sort(keys(%lasthash))) {
                   4282: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4283: 	if ($#parts > 0) {
1.31      albertel 4284: 	  my $data=$parts[-1];
1.989     raeburn  4285:           next if ($data eq 'foilorder');
1.31      albertel 4286: 	  pop(@parts);
1.1010    www      4287:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4288:           if ($data eq 'type') {
                   4289:               unless ($showsurv) {
                   4290:                   my $id = join(',',@parts);
                   4291:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4292:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4293:                       $lasthidden{$ign.'.'.$id} = 1;
                   4294:                   }
1.945     raeburn  4295:               }
1.1075.2.86  raeburn  4296:               if ($identifier ne '') {
                   4297:                   my $id = join(',',@parts);
                   4298:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4299:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4300:                       $hidestatus{$ign.'.'.$id} = 1;
                   4301:                   }
                   4302:               }
                   4303:           } elsif ($data eq 'regrader') {
                   4304:               if (($identifier ne '') && (@parts)) {
                   4305:                   my $id = join(',',@parts);
                   4306:                   $regraded{$ign.'.'.$id} = 1;
                   4307:               }
1.1010    www      4308:           } 
1.31      albertel 4309: 	} else {
1.41      ng       4310: 	  if ($#parts == 0) {
                   4311: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4312: 	  } else {
                   4313: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4314: 	  }
1.31      albertel 4315: 	}
1.16      harris41 4316:       }
1.596     albertel 4317:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4318:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4319:         my (%solved,%resets,%probstatus);
                   4320:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4321:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4322:                 foreach my $id (keys(%regraded)) {
                   4323:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4324:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4325:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4326:                         push(@{$resets{$id}},$version);
                   4327:                     }
                   4328:                 }
                   4329:             }
                   4330:         }
1.40      ng       4331: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4332:             my (@hidden,@unsolved);
1.945     raeburn  4333:             if (%typeparts) {
                   4334:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4335:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4336:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4337:                         push(@hidden,$id);
1.1075.2.86  raeburn  4338:                     } elsif ($identifier ne '') {
                   4339:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4340:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4341:                                 ($hidestatus{$id})) {
                   4342:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4343:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4344:                                 push(@{$solved{$id}},$version);
                   4345:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4346:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4347:                                 my $skip;
                   4348:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4349:                                     foreach my $reset (@{$resets{$id}}) {
                   4350:                                         if ($reset > $solved{$id}[-1]) {
                   4351:                                             $skip=1;
                   4352:                                             last;
                   4353:                                         }
                   4354:                                     }
                   4355:                                 }
                   4356:                                 unless ($skip) {
                   4357:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4358:                                     push(@unsolved,$partslist);
                   4359:                                 }
                   4360:                             }
                   4361:                         }
1.945     raeburn  4362:                     }
                   4363:                 }
                   4364:             }
                   4365:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4366:                            '<td>'.&mt('Transaction [_1]',$version);
                   4367:             if (@unsolved) {
                   4368:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4369:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4370:                                  &mt('Hide').'</label></span>';
                   4371:             }
                   4372:             $prevattempts .= '</td>';
1.945     raeburn  4373:             if (@hidden) {
                   4374:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4375:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4376:                     my $hide;
                   4377:                     foreach my $id (@hidden) {
                   4378:                         if ($key =~ /^\Q$id\E/) {
                   4379:                             $hide = 1;
                   4380:                             last;
                   4381:                         }
                   4382:                     }
                   4383:                     if ($hide) {
                   4384:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4385:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4386:                             my $value = &format_previous_attempt_value($key,
                   4387:                                              $returnhash{$version.':'.$key});
                   4388:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4389:                         } else {
                   4390:                             $prevattempts.='<td>&nbsp;</td>';
                   4391:                         }
                   4392:                     } else {
                   4393:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4394:                             my $value = $returnhash{$version.':'.$key};
                   4395:                             if ($key =~ /\.rndseed$/) {
                   4396:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4397:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4398:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4399:                                 }
                   4400:                             }
                   4401:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4402:                                            '&nbsp;</td>';
1.945     raeburn  4403:                         } else {
                   4404:                             $prevattempts.='<td>&nbsp;</td>';
                   4405:                         }
                   4406:                     }
                   4407:                 }
                   4408:             } else {
                   4409: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4410:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4411:                     my $value = $returnhash{$version.':'.$key};
                   4412:                     if ($key =~ /\.rndseed$/) {
                   4413:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4414:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4415:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4416:                         }
                   4417:                     }
                   4418:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4419:                                    '&nbsp;</td>';
1.945     raeburn  4420: 	        }
                   4421:             }
                   4422: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4423: 	 }
1.1       albertel 4424:       }
1.945     raeburn  4425:       my @currhidden = keys(%lasthidden);
1.596     albertel 4426:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4427:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4428:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4429:           if (%typeparts) {
                   4430:               my $hidden;
                   4431:               foreach my $id (@currhidden) {
                   4432:                   if ($key =~ /^\Q$id\E/) {
                   4433:                       $hidden = 1;
                   4434:                       last;
                   4435:                   }
                   4436:               }
                   4437:               if ($hidden) {
                   4438:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4439:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4440:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4441:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4442:                           $value = &$gradesub($value);
                   4443:                       }
                   4444:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4445:                   } else {
                   4446:                       $prevattempts.='<td>&nbsp;</td>';
                   4447:                   }
                   4448:               } else {
                   4449:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4450:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4451:                       $value = &$gradesub($value);
                   4452:                   }
                   4453:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4454:               }
                   4455:           } else {
                   4456: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4457: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4458:                   $value = &$gradesub($value);
                   4459:               }
                   4460: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4461:           }
1.16      harris41 4462:       }
1.596     albertel 4463:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4464:     } else {
1.596     albertel 4465:       $prevattempts=
                   4466: 	  &start_data_table().&start_data_table_row().
                   4467: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4468: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4469:     }
                   4470:   } else {
1.596     albertel 4471:     $prevattempts=
                   4472: 	  &start_data_table().&start_data_table_row().
                   4473: 	  '<td>'.&mt('No data.').'</td>'.
                   4474: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4475:   }
1.10      albertel 4476: }
                   4477: 
1.581     albertel 4478: sub format_previous_attempt_value {
                   4479:     my ($key,$value) = @_;
1.1011    www      4480:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4481: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4482:     } elsif (ref($value) eq 'ARRAY') {
                   4483: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4484:     } elsif ($key =~ /answerstring$/) {
                   4485:         my %answers = &Apache::lonnet::str2hash($value);
                   4486:         my @anskeys = sort(keys(%answers));
                   4487:         if (@anskeys == 1) {
                   4488:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4489:             if ($answer =~ m{\0}) {
                   4490:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4491:             }
                   4492:             my $tag_internal_answer_name = 'INTERNAL';
                   4493:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4494:                 $value = $answer; 
                   4495:             } else {
                   4496:                 $value = $anskeys[0].'='.$answer;
                   4497:             }
                   4498:         } else {
                   4499:             foreach my $ans (@anskeys) {
                   4500:                 my $answer = $answers{$ans};
1.1001    raeburn  4501:                 if ($answer =~ m{\0}) {
                   4502:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4503:                 }
                   4504:                 $value .=  $ans.'='.$answer.'<br />';;
                   4505:             } 
                   4506:         }
1.581     albertel 4507:     } else {
                   4508: 	$value = &unescape($value);
                   4509:     }
                   4510:     return $value;
                   4511: }
                   4512: 
                   4513: 
1.107     albertel 4514: sub relative_to_absolute {
                   4515:     my ($url,$output)=@_;
                   4516:     my $parser=HTML::TokeParser->new(\$output);
                   4517:     my $token;
                   4518:     my $thisdir=$url;
                   4519:     my @rlinks=();
                   4520:     while ($token=$parser->get_token) {
                   4521: 	if ($token->[0] eq 'S') {
                   4522: 	    if ($token->[1] eq 'a') {
                   4523: 		if ($token->[2]->{'href'}) {
                   4524: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4525: 		}
                   4526: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4527: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4528: 	    } elsif ($token->[1] eq 'base') {
                   4529: 		$thisdir=$token->[2]->{'href'};
                   4530: 	    }
                   4531: 	}
                   4532:     }
                   4533:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4534:     foreach my $link (@rlinks) {
1.726     raeburn  4535: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4536: 		($link=~/^\//) ||
                   4537: 		($link=~/^javascript:/i) ||
                   4538: 		($link=~/^mailto:/i) ||
                   4539: 		($link=~/^\#/)) {
                   4540: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4541: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4542: 	}
                   4543:     }
                   4544: # -------------------------------------------------- Deal with Applet codebases
                   4545:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4546:     return $output;
                   4547: }
                   4548: 
1.112     bowersj2 4549: =pod
                   4550: 
1.648     raeburn  4551: =item * &get_student_view()
1.112     bowersj2 4552: 
                   4553: show a snapshot of what student was looking at
                   4554: 
                   4555: =cut
                   4556: 
1.10      albertel 4557: sub get_student_view {
1.186     albertel 4558:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4559:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4560:   my (%form);
1.10      albertel 4561:   my @elements=('symb','courseid','domain','username');
                   4562:   foreach my $element (@elements) {
1.186     albertel 4563:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4564:   }
1.186     albertel 4565:   if (defined($moreenv)) {
                   4566:       %form=(%form,%{$moreenv});
                   4567:   }
1.236     albertel 4568:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4569:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4570:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4571:   $userview=~s/\<body[^\>]*\>//gi;
                   4572:   $userview=~s/\<\/body\>//gi;
                   4573:   $userview=~s/\<html\>//gi;
                   4574:   $userview=~s/\<\/html\>//gi;
                   4575:   $userview=~s/\<head\>//gi;
                   4576:   $userview=~s/\<\/head\>//gi;
                   4577:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4578:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4579:   if (wantarray) {
                   4580:      return ($userview,$response);
                   4581:   } else {
                   4582:      return $userview;
                   4583:   }
                   4584: }
                   4585: 
                   4586: sub get_student_view_with_retries {
                   4587:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4588: 
                   4589:     my $ok = 0;                 # True if we got a good response.
                   4590:     my $content;
                   4591:     my $response;
                   4592: 
                   4593:     # Try to get the student_view done. within the retries count:
                   4594:     
                   4595:     do {
                   4596:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4597:          $ok      = $response->is_success;
                   4598:          if (!$ok) {
                   4599:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4600:          }
                   4601:          $retries--;
                   4602:     } while (!$ok && ($retries > 0));
                   4603:     
                   4604:     if (!$ok) {
                   4605:        $content = '';          # On error return an empty content.
                   4606:     }
1.651     www      4607:     if (wantarray) {
                   4608:        return ($content, $response);
                   4609:     } else {
                   4610:        return $content;
                   4611:     }
1.11      albertel 4612: }
                   4613: 
1.1075.2.149  raeburn  4614: sub css_links {
                   4615:     my ($currsymb,$level) = @_;
                   4616:     my ($links,@symbs,%cssrefs,%httpref);
                   4617:     if ($level eq 'map') {
                   4618:         my $navmap = Apache::lonnavmaps::navmap->new();
                   4619:         if (ref($navmap)) {
                   4620:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   4621:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   4622:             foreach my $res (@resources) {
                   4623:                 if (ref($res) && $res->symb()) {
                   4624:                     push(@symbs,$res->symb());
                   4625:                 }
                   4626:             }
                   4627:         }
                   4628:     } else {
                   4629:         @symbs = ($currsymb);
                   4630:     }
                   4631:     foreach my $symb (@symbs) {
                   4632:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   4633:         if ($css_href =~ /\S/) {
                   4634:             unless ($css_href =~ m{https?://}) {
                   4635:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   4636:                 my $proburl =  &Apache::lonnet::clutter($url);
                   4637:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   4638:                 unless ($css_href =~ m{^/}) {
                   4639:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   4640:                 }
                   4641:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   4642:                     unless (($httpref{'httpref.'.$css_href}) ||
                   4643:                             (&Apache::lonnet::is_on_map($css_href))) {
                   4644:                         my $thisurl = $proburl;
                   4645:                         if ($env{'httpref.'.$proburl}) {
                   4646:                             $thisurl = $env{'httpref.'.$proburl};
                   4647:                         }
                   4648:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   4649:                     }
                   4650:                 }
                   4651:             }
                   4652:             $cssrefs{$css_href} = 1;
                   4653:         }
                   4654:     }
                   4655:     if (keys(%httpref)) {
                   4656:         &Apache::lonnet::appenv(\%httpref);
                   4657:     }
                   4658:     if (keys(%cssrefs)) {
                   4659:         foreach my $css_href (keys(%cssrefs)) {
                   4660:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   4661:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   4662:         }
                   4663:     }
                   4664:     return $links;
                   4665: }
                   4666: 
1.112     bowersj2 4667: =pod
                   4668: 
1.648     raeburn  4669: =item * &get_student_answers() 
1.112     bowersj2 4670: 
                   4671: show a snapshot of how student was answering problem
                   4672: 
                   4673: =cut
                   4674: 
1.11      albertel 4675: sub get_student_answers {
1.100     sakharuk 4676:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4677:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4678:   my (%moreenv);
1.11      albertel 4679:   my @elements=('symb','courseid','domain','username');
                   4680:   foreach my $element (@elements) {
1.186     albertel 4681:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4682:   }
1.186     albertel 4683:   $moreenv{'grade_target'}='answer';
                   4684:   %moreenv=(%form,%moreenv);
1.497     raeburn  4685:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4686:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4687:   return $userview;
1.1       albertel 4688: }
1.116     albertel 4689: 
                   4690: =pod
                   4691: 
                   4692: =item * &submlink()
                   4693: 
1.242     albertel 4694: Inputs: $text $uname $udom $symb $target
1.116     albertel 4695: 
                   4696: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4697: 
                   4698: =cut
                   4699: 
                   4700: ###############################################
                   4701: sub submlink {
1.242     albertel 4702:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4703:     if (!($uname && $udom)) {
                   4704: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4705: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4706: 	if (!$symb) { $symb=$cursymb; }
                   4707:     }
1.254     matthew  4708:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4709:     $symb=&escape($symb);
1.960     bisitz   4710:     if ($target) { $target=" target=\"$target\""; }
                   4711:     return
                   4712:         '<a href="/adm/grades?command=submission'.
                   4713:         '&amp;symb='.$symb.
                   4714:         '&amp;student='.$uname.
                   4715:         '&amp;userdom='.$udom.'"'.
                   4716:         $target.'>'.$text.'</a>';
1.242     albertel 4717: }
                   4718: ##############################################
                   4719: 
                   4720: =pod
                   4721: 
                   4722: =item * &pgrdlink()
                   4723: 
                   4724: Inputs: $text $uname $udom $symb $target
                   4725: 
                   4726: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4727: 
                   4728: =cut
                   4729: 
                   4730: ###############################################
                   4731: sub pgrdlink {
                   4732:     my $link=&submlink(@_);
                   4733:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4734:     return $link;
                   4735: }
                   4736: ##############################################
                   4737: 
                   4738: =pod
                   4739: 
                   4740: =item * &pprmlink()
                   4741: 
                   4742: Inputs: $text $uname $udom $symb $target
                   4743: 
                   4744: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4745: student and a specific resource
1.242     albertel 4746: 
                   4747: =cut
                   4748: 
                   4749: ###############################################
                   4750: sub pprmlink {
                   4751:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4752:     if (!($uname && $udom)) {
                   4753: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4754: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4755: 	if (!$symb) { $symb=$cursymb; }
                   4756:     }
1.254     matthew  4757:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4758:     $symb=&escape($symb);
1.242     albertel 4759:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4760:     return '<a href="/adm/parmset?command=set&amp;'.
                   4761: 	'symb='.$symb.'&amp;uname='.$uname.
                   4762: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4763: }
                   4764: ##############################################
1.37      matthew  4765: 
1.112     bowersj2 4766: =pod
                   4767: 
                   4768: =back
                   4769: 
                   4770: =cut
                   4771: 
1.37      matthew  4772: ###############################################
1.51      www      4773: 
                   4774: 
                   4775: sub timehash {
1.687     raeburn  4776:     my ($thistime) = @_;
                   4777:     my $timezone = &Apache::lonlocal::gettimezone();
                   4778:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4779:                      ->set_time_zone($timezone);
                   4780:     my $wday = $dt->day_of_week();
                   4781:     if ($wday == 7) { $wday = 0; }
                   4782:     return ( 'second' => $dt->second(),
                   4783:              'minute' => $dt->minute(),
                   4784:              'hour'   => $dt->hour(),
                   4785:              'day'     => $dt->day_of_month(),
                   4786:              'month'   => $dt->month(),
                   4787:              'year'    => $dt->year(),
                   4788:              'weekday' => $wday,
                   4789:              'dayyear' => $dt->day_of_year(),
                   4790:              'dlsav'   => $dt->is_dst() );
1.51      www      4791: }
                   4792: 
1.370     www      4793: sub utc_string {
                   4794:     my ($date)=@_;
1.371     www      4795:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4796: }
                   4797: 
1.51      www      4798: sub maketime {
                   4799:     my %th=@_;
1.687     raeburn  4800:     my ($epoch_time,$timezone,$dt);
                   4801:     $timezone = &Apache::lonlocal::gettimezone();
                   4802:     eval {
                   4803:         $dt = DateTime->new( year   => $th{'year'},
                   4804:                              month  => $th{'month'},
                   4805:                              day    => $th{'day'},
                   4806:                              hour   => $th{'hour'},
                   4807:                              minute => $th{'minute'},
                   4808:                              second => $th{'second'},
                   4809:                              time_zone => $timezone,
                   4810:                          );
                   4811:     };
                   4812:     if (!$@) {
                   4813:         $epoch_time = $dt->epoch;
                   4814:         if ($epoch_time) {
                   4815:             return $epoch_time;
                   4816:         }
                   4817:     }
1.51      www      4818:     return POSIX::mktime(
                   4819:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4820:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4821: }
                   4822: 
                   4823: #########################################
1.51      www      4824: 
                   4825: sub findallcourses {
1.482     raeburn  4826:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4827:     my %roles;
                   4828:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4829:     my %courses;
1.51      www      4830:     my $now=time;
1.482     raeburn  4831:     if (!defined($uname)) {
                   4832:         $uname = $env{'user.name'};
                   4833:     }
                   4834:     if (!defined($udom)) {
                   4835:         $udom = $env{'user.domain'};
                   4836:     }
                   4837:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4838:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4839:         if (!%roles) {
                   4840:             %roles = (
                   4841:                        cc => 1,
1.907     raeburn  4842:                        co => 1,
1.482     raeburn  4843:                        in => 1,
                   4844:                        ep => 1,
                   4845:                        ta => 1,
                   4846:                        cr => 1,
                   4847:                        st => 1,
                   4848:              );
                   4849:         }
                   4850:         foreach my $entry (keys(%roleshash)) {
                   4851:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4852:             if ($trole =~ /^cr/) { 
                   4853:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4854:             } else {
                   4855:                 next if (!exists($roles{$trole}));
                   4856:             }
                   4857:             if ($tend) {
                   4858:                 next if ($tend < $now);
                   4859:             }
                   4860:             if ($tstart) {
                   4861:                 next if ($tstart > $now);
                   4862:             }
1.1058    raeburn  4863:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4864:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4865:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4866:             if ($secpart eq '') {
                   4867:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4868:                 $sec = 'none';
1.1058    raeburn  4869:                 $value .= $cnum.'/';
1.482     raeburn  4870:             } else {
                   4871:                 $cnum = $cnumpart;
                   4872:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4873:                 $value .= $cnum.'/'.$sec;
                   4874:             }
                   4875:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4876:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4877:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4878:                 }
                   4879:             } else {
                   4880:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4881:             }
1.482     raeburn  4882:         }
                   4883:     } else {
                   4884:         foreach my $key (keys(%env)) {
1.483     albertel 4885: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4886:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4887: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4888: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4889: 	        next if (%roles && !exists($roles{$role}));
                   4890: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4891:                 my $active=1;
                   4892:                 if ($starttime) {
                   4893: 		    if ($now<$starttime) { $active=0; }
                   4894:                 }
                   4895:                 if ($endtime) {
                   4896:                     if ($now>$endtime) { $active=0; }
                   4897:                 }
                   4898:                 if ($active) {
1.1058    raeburn  4899:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4900:                     if ($sec eq '') {
                   4901:                         $sec = 'none';
1.1058    raeburn  4902:                     } else {
                   4903:                         $value .= $sec;
                   4904:                     }
                   4905:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4906:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4907:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4908:                         }
                   4909:                     } else {
                   4910:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4911:                     }
1.474     raeburn  4912:                 }
                   4913:             }
1.51      www      4914:         }
                   4915:     }
1.474     raeburn  4916:     return %courses;
1.51      www      4917: }
1.37      matthew  4918: 
1.54      www      4919: ###############################################
1.474     raeburn  4920: 
                   4921: sub blockcheck {
1.1075.2.158  raeburn  4922:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.490     raeburn  4923: 
1.1075.2.161.  .4(raebu 4924:22):     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
1.1075.2.158  raeburn  4925:         my ($has_evb,$check_ipaccess);
                   4926:         my $dom = $env{'user.domain'};
                   4927:         if ($env{'request.course.id'}) {
                   4928:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4929:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4930:             my $checkrole = "cm./$cdom/$cnum";
                   4931:             my $sec = $env{'request.course.sec'};
                   4932:             if ($sec ne '') {
                   4933:                 $checkrole .= "/$sec";
                   4934:             }
                   4935:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   4936:                 ($env{'request.role'} !~ /^st/)) {
                   4937:                 $has_evb = 1;
                   4938:             }
                   4939:             unless ($has_evb) {
                   4940:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   4941:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   4942:                     if ($udom eq $cdom) {
                   4943:                         $check_ipaccess = 1;
                   4944:                     }
                   4945:                 }
                   4946:             }
1.1075.2.161.  .3(raebu 4947:22):         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   4948:22):                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   4949:22):             my $checkrole;
                   4950:22):             if ($env{'request.role.domain'} eq '') {
                   4951:22):                 $checkrole = "cm./$env{'user.domain'}/";
                   4952:22):             } else {
                   4953:22):                 $checkrole = "cm./$env{'request.role.domain'}/";
                   4954:22):             }
                   4955:22):             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   4956:22):                 $has_evb = 1;
                   4957:22):             }
1.1075.2.158  raeburn  4958:         }
                   4959:         unless ($has_evb || $check_ipaccess) {
                   4960:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   4961:             if (($dom eq 'public') && ($activity eq 'port')) {
                   4962:                 $dom = $udom;
                   4963:             }
                   4964:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   4965:                 $check_ipaccess = 1;
                   4966:             } else {
                   4967:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   4968:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   4969:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   4970:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   4971:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   4972:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   4973:                         $check_ipaccess = 1;
                   4974:                     }
                   4975:                 }
                   4976:             }
                   4977:         }
                   4978:         if ($check_ipaccess) {
                   4979:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   4980:             unless (defined($cached)) {
                   4981:                 my %domconfig =
                   4982:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   4983:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   4984:             }
                   4985:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   4986:                 foreach my $id (keys(%{$ipaccessref})) {
                   4987:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   4988:                         my $range = $ipaccessref->{$id}->{'ip'};
                   4989:                         if ($range) {
                   4990:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   4991:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   4992:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   4993:                                         return ('','','',$id,$dom);
                   4994:                                         last;
                   4995:                                     }
                   4996:                                 }
                   4997:                             }
                   4998:                         }
                   4999:                     }
                   5000:                 }
                   5001:             }
                   5002:         }
1.1075.2.161.  .4(raebu 5003:22):         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5004:22):             return ();
                   5005:22):         }
1.1075.2.158  raeburn  5006:     }
1.1075.2.73  raeburn  5007:     if (defined($udom) && defined($uname)) {
                   5008:         # If uname and udom are for a course, check for blocks in the course.
                   5009:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5010:             my ($startblock,$endblock,$triggerblock) =
1.1075.2.147  raeburn  5011:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1075.2.73  raeburn  5012:             return ($startblock,$endblock,$triggerblock);
                   5013:         }
                   5014:     } else {
1.490     raeburn  5015:         $udom = $env{'user.domain'};
                   5016:         $uname = $env{'user.name'};
                   5017:     }
                   5018: 
1.502     raeburn  5019:     my $startblock = 0;
                   5020:     my $endblock = 0;
1.1062    raeburn  5021:     my $triggerblock = '';
1.1075.2.160  raeburn  5022:     my %live_courses;
                   5023:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5024:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5025:     }
1.474     raeburn  5026: 
1.490     raeburn  5027:     # If uname is for a user, and activity is course-specific, i.e.,
                   5028:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5029: 
1.490     raeburn  5030:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.161.  .1(raebu 5031:21):          $activity eq 'groups' || $activity eq 'printout' ||
                   5032:21):          $activity eq 'search' || $activity eq 'reinit' ||
                   5033:21):          $activity eq 'alert') && ($env{'request.course.id'})) {
1.490     raeburn  5034:         foreach my $key (keys(%live_courses)) {
                   5035:             if ($key ne $env{'request.course.id'}) {
                   5036:                 delete($live_courses{$key});
                   5037:             }
                   5038:         }
                   5039:     }
                   5040: 
                   5041:     my $otheruser = 0;
                   5042:     my %own_courses;
                   5043:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5044:         # Resource belongs to user other than current user.
                   5045:         $otheruser = 1;
                   5046:         # Gather courses for current user
                   5047:         %own_courses = 
                   5048:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5049:     }
                   5050: 
                   5051:     # Gather active course roles - course coordinator, instructor, 
                   5052:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5053: 
                   5054:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5055:         my ($cdom,$cnum);
                   5056:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5057:             $cdom = $env{'course.'.$course.'.domain'};
                   5058:             $cnum = $env{'course.'.$course.'.num'};
                   5059:         } else {
1.490     raeburn  5060:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5061:         }
                   5062:         my $no_ownblock = 0;
                   5063:         my $no_userblock = 0;
1.533     raeburn  5064:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5065:             # Check if current user has 'evb' priv for this
                   5066:             if (defined($own_courses{$course})) {
                   5067:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5068:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5069:                     if ($sec ne 'none') {
                   5070:                         $checkrole .= '/'.$sec;
                   5071:                     }
                   5072:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5073:                         $no_ownblock = 1;
                   5074:                         last;
                   5075:                     }
                   5076:                 }
                   5077:             }
                   5078:             # if they have 'evb' priv and are currently not playing student
                   5079:             next if (($no_ownblock) &&
                   5080:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5081:         }
1.474     raeburn  5082:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5083:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5084:             if ($sec ne 'none') {
1.482     raeburn  5085:                 $checkrole .= '/'.$sec;
1.474     raeburn  5086:             }
1.490     raeburn  5087:             if ($otheruser) {
                   5088:                 # Resource belongs to user other than current user.
                   5089:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5090:                 my (%allroles,%userroles);
                   5091:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5092:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5093:                         my ($trole,$tdom,$tnum,$tsec);
                   5094:                         if ($entry =~ /^cr/) {
                   5095:                             ($trole,$tdom,$tnum,$tsec) = 
                   5096:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5097:                         } else {
                   5098:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5099:                         }
                   5100:                         my ($spec,$area,$trest);
                   5101:                         $area = '/'.$tdom.'/'.$tnum;
                   5102:                         $trest = $tnum;
                   5103:                         if ($tsec ne '') {
                   5104:                             $area .= '/'.$tsec;
                   5105:                             $trest .= '/'.$tsec;
                   5106:                         }
                   5107:                         $spec = $trole.'.'.$area;
                   5108:                         if ($trole =~ /^cr/) {
                   5109:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5110:                                                               $tdom,$spec,$trest,$area);
                   5111:                         } else {
                   5112:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5113:                                                                 $tdom,$spec,$trest,$area);
                   5114:                         }
                   5115:                     }
1.1075.2.124  raeburn  5116:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5117:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5118:                         if ($1) {
                   5119:                             $no_userblock = 1;
                   5120:                             last;
                   5121:                         }
1.486     raeburn  5122:                     }
                   5123:                 }
1.490     raeburn  5124:             } else {
                   5125:                 # Resource belongs to current user
                   5126:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5127:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5128:                     $no_ownblock = 1;
                   5129:                     last;
                   5130:                 }
1.474     raeburn  5131:             }
                   5132:         }
                   5133:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5134:         next if (($no_ownblock) &&
1.491     albertel 5135:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5136:         next if ($no_userblock);
1.474     raeburn  5137: 
1.1075.2.128  raeburn  5138:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5139:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  5140:         
1.1062    raeburn  5141:         my ($start,$end,$trigger) = 
1.1075.2.147  raeburn  5142:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5143:         if (($start != 0) && 
                   5144:             (($startblock == 0) || ($startblock > $start))) {
                   5145:             $startblock = $start;
1.1062    raeburn  5146:             if ($trigger ne '') {
                   5147:                 $triggerblock = $trigger;
                   5148:             }
1.502     raeburn  5149:         }
                   5150:         if (($end != 0)  &&
                   5151:             (($endblock == 0) || ($endblock < $end))) {
                   5152:             $endblock = $end;
1.1062    raeburn  5153:             if ($trigger ne '') {
                   5154:                 $triggerblock = $trigger;
                   5155:             }
1.502     raeburn  5156:         }
1.490     raeburn  5157:     }
1.1062    raeburn  5158:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5159: }
                   5160: 
                   5161: sub get_blocks {
1.1075.2.147  raeburn  5162:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5163:     my $startblock = 0;
                   5164:     my $endblock = 0;
1.1062    raeburn  5165:     my $triggerblock = '';
1.490     raeburn  5166:     my $course = $cdom.'_'.$cnum;
                   5167:     $setters->{$course} = {};
                   5168:     $setters->{$course}{'staff'} = [];
                   5169:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5170:     $setters->{$course}{'triggers'} = [];
                   5171:     my (@blockers,%triggered);
                   5172:     my $now = time;
                   5173:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5174:     if ($activity eq 'docs') {
1.1075.2.148  raeburn  5175:         my ($blocked,$nosymbcache,$noenccheck);
1.1075.2.147  raeburn  5176:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5177:             $blocked = 1;
                   5178:             $nosymbcache = 1;
1.1075.2.148  raeburn  5179:             $noenccheck = 1;
1.1075.2.147  raeburn  5180:         }
1.1075.2.148  raeburn  5181:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5182:         foreach my $block (@blockers) {
                   5183:             if ($block =~ /^firstaccess____(.+)$/) {
                   5184:                 my $item = $1;
                   5185:                 my $type = 'map';
                   5186:                 my $timersymb = $item;
                   5187:                 if ($item eq 'course') {
                   5188:                     $type = 'course';
                   5189:                 } elsif ($item =~ /___\d+___/) {
                   5190:                     $type = 'resource';
                   5191:                 } else {
                   5192:                     $timersymb = &Apache::lonnet::symbread($item);
                   5193:                 }
                   5194:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5195:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5196:                 $triggered{$block} = {
                   5197:                                        start => $start,
                   5198:                                        end   => $end,
                   5199:                                        type  => $type,
                   5200:                                      };
                   5201:             }
                   5202:         }
                   5203:     } else {
                   5204:         foreach my $block (keys(%commblocks)) {
                   5205:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5206:                 my ($start,$end) = ($1,$2);
                   5207:                 if ($start <= time && $end >= time) {
                   5208:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5209:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5210:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5211:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5212:                                     push(@blockers,$block);
                   5213:                                 }
                   5214:                             }
                   5215:                         }
                   5216:                     }
                   5217:                 }
                   5218:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5219:                 my $item = $1;
                   5220:                 my $timersymb = $item; 
                   5221:                 my $type = 'map';
                   5222:                 if ($item eq 'course') {
                   5223:                     $type = 'course';
                   5224:                 } elsif ($item =~ /___\d+___/) {
                   5225:                     $type = 'resource';
                   5226:                 } else {
                   5227:                     $timersymb = &Apache::lonnet::symbread($item);
                   5228:                 }
                   5229:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5230:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5231:                 if ($start && $end) {
                   5232:                     if (($start <= time) && ($end >= time)) {
1.1075.2.158  raeburn  5233:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5234:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5235:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5236:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5237:                                         push(@blockers,$block);
                   5238:                                         $triggered{$block} = {
                   5239:                                                                start => $start,
                   5240:                                                                end   => $end,
                   5241:                                                                type  => $type,
                   5242:                                                              };
                   5243:                                     }
                   5244:                                 }
                   5245:                             }
1.1062    raeburn  5246:                         }
                   5247:                     }
1.490     raeburn  5248:                 }
1.1062    raeburn  5249:             }
                   5250:         }
                   5251:     }
                   5252:     foreach my $blocker (@blockers) {
                   5253:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5254:             &parse_block_record($commblocks{$blocker});
                   5255:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5256:         my ($start,$end,$triggertype);
                   5257:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5258:             ($start,$end) = ($1,$2);
                   5259:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5260:             $start = $triggered{$blocker}{'start'};
                   5261:             $end = $triggered{$blocker}{'end'};
                   5262:             $triggertype = $triggered{$blocker}{'type'};
                   5263:         }
                   5264:         if ($start) {
                   5265:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5266:             if ($triggertype) {
                   5267:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5268:             } else {
                   5269:                 push(@{$$setters{$course}{'triggers'}},0);
                   5270:             }
                   5271:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5272:                 $startblock = $start;
                   5273:                 if ($triggertype) {
                   5274:                     $triggerblock = $blocker;
1.474     raeburn  5275:                 }
                   5276:             }
1.1062    raeburn  5277:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5278:                $endblock = $end;
                   5279:                if ($triggertype) {
                   5280:                    $triggerblock = $blocker;
                   5281:                }
                   5282:             }
1.474     raeburn  5283:         }
                   5284:     }
1.1062    raeburn  5285:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5286: }
                   5287: 
                   5288: sub parse_block_record {
                   5289:     my ($record) = @_;
                   5290:     my ($setuname,$setudom,$title,$blocks);
                   5291:     if (ref($record) eq 'HASH') {
                   5292:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5293:         $title = &unescape($record->{'event'});
                   5294:         $blocks = $record->{'blocks'};
                   5295:     } else {
                   5296:         my @data = split(/:/,$record,3);
                   5297:         if (scalar(@data) eq 2) {
                   5298:             $title = $data[1];
                   5299:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5300:         } else {
                   5301:             ($setuname,$setudom,$title) = @data;
                   5302:         }
                   5303:         $blocks = { 'com' => 'on' };
                   5304:     }
                   5305:     return ($setuname,$setudom,$title,$blocks);
                   5306: }
                   5307: 
1.854     kalberla 5308: sub blocking_status {
1.1075.2.158  raeburn  5309:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5310:     my %setters;
1.890     droeschl 5311: 
1.1061    raeburn  5312: # check for active blocking
1.1075.2.158  raeburn  5313:     if ($clientip eq '') {
                   5314:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5315:     }
                   5316:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5317:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5318:     my $blocked = 0;
1.1075.2.158  raeburn  5319:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5320:         $blocked = 1;
                   5321:     }
1.890     droeschl 5322: 
1.1061    raeburn  5323: # caller just wants to know whether a block is active
                   5324:     if (!wantarray) { return $blocked; }
                   5325: 
                   5326: # build a link to a popup window containing the details
                   5327:     my $querystring  = "?activity=$activity";
1.1075.2.158  raeburn  5328: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   5329:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1075.2.97  raeburn  5330:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   5331:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  5332:     } elsif ($activity eq 'docs') {
1.1075.2.147  raeburn  5333:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   5334:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   5335:         if ($symb) {
                   5336:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   5337:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   5338:         }
1.1062    raeburn  5339:     }
1.1061    raeburn  5340: 
                   5341:     my $output .= <<'END_MYBLOCK';
                   5342: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   5343:     var options = "width=" + w + ",height=" + h + ",";
                   5344:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   5345:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   5346:     var newWin = window.open(url, wdwName, options);
                   5347:     newWin.focus();
                   5348: }
1.890     droeschl 5349: END_MYBLOCK
1.854     kalberla 5350: 
1.1061    raeburn  5351:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 5352:   
1.1061    raeburn  5353:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  5354:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  5355:     my $class = 'LC_comblock';
1.1062    raeburn  5356:     if ($activity eq 'docs') {
                   5357:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  5358:         $class = '';
1.1063    raeburn  5359:     } elsif ($activity eq 'printout') {
                   5360:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  5361:     } elsif ($activity eq 'passwd') {
                   5362:         $text = &mt('Password Changing Blocked');
1.1075.2.158  raeburn  5363:     } elsif ($activity eq 'grades') {
                   5364:         $text = &mt('Gradebook Blocked');
                   5365:     } elsif ($activity eq 'search') {
                   5366:         $text = &mt('Search Blocked');
1.1075.2.161.  .1(raebu 5367:21):     } elsif ($activity eq 'alert') {
                   5368:21):         $text = &mt('Checking Critical Messages Blocked');
                   5369:21):     } elsif ($activity eq 'reinit') {
                   5370:21):         $text = &mt('Checking Course Update Blocked');
1.1075.2.158  raeburn  5371:     } elsif ($activity eq 'about') {
                   5372:         $text = &mt('Access to User Information Pages Blocked');
1.1075.2.160  raeburn  5373:     } elsif ($activity eq 'wishlist') {
                   5374:         $text = &mt('Access to Stored Links Blocked');
                   5375:     } elsif ($activity eq 'annotate') {
                   5376:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  5377:     }
1.1061    raeburn  5378:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  5379: <div class='$class'>
1.869     kalberla 5380:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 5381:   title='$text'>
                   5382:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 5383:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 5384:   title='$text'>$text</a>
1.867     kalberla 5385: </div>
                   5386: 
                   5387: END_BLOCK
1.474     raeburn  5388: 
1.1061    raeburn  5389:     return ($blocked, $output);
1.854     kalberla 5390: }
1.490     raeburn  5391: 
1.60      matthew  5392: ###############################################
                   5393: 
1.682     raeburn  5394: sub check_ip_acc {
1.1075.2.105  raeburn  5395:     my ($acc,$clientip)=@_;
1.682     raeburn  5396:     &Apache::lonxml::debug("acc is $acc");
                   5397:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   5398:         return 1;
                   5399:     }
                   5400:     my $allowed=0;
1.1075.2.144  raeburn  5401:     my $ip;
                   5402:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   5403:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   5404:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   5405:     } else {
1.1075.2.150  raeburn  5406:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   5407:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1075.2.144  raeburn  5408:     }
1.682     raeburn  5409: 
                   5410:     my $name;
1.1075.2.161.  .1(raebu 5411:21):     my %access = (
                   5412:21):                      allowfrom => 1,
                   5413:21):                      denyfrom  => 0,
                   5414:21):                  );
                   5415:21):     my @allows;
                   5416:21):     my @denies;
                   5417:21):     foreach my $item (split(',',$acc)) {
                   5418:21):         $item =~ s/^\s*//;
                   5419:21):         $item =~ s/\s*$//;
                   5420:21):         if ($item =~ /^\!(.+)$/) {
                   5421:21):             push(@denies,$1);
                   5422:21):         } else {
                   5423:21):             push(@allows,$item);
                   5424:21):         }
                   5425:21):     }
                   5426:21):     my $numdenies = scalar(@denies);
                   5427:21):     my $numallows = scalar(@allows);
                   5428:21):     my $count = 0;
                   5429:21):     foreach my $pattern (@denies,@allows) {
                   5430:21):         $count ++;
                   5431:21):         my $acctype = 'allowfrom';
                   5432:21):         if ($count <= $numdenies) {
                   5433:21):             $acctype = 'denyfrom';
                   5434:21):         }
1.682     raeburn  5435:         if ($pattern =~ /\*$/) {
                   5436:             #35.8.*
                   5437:             $pattern=~s/\*//;
1.1075.2.161.  .1(raebu 5438:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5439:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5440:             #35.8.3.[34-56]
                   5441:             my $low=$2;
                   5442:             my $high=$3;
                   5443:             $pattern=$1;
                   5444:             if ($ip =~ /^\Q$pattern\E/) {
                   5445:                 my $last=(split(/\./,$ip))[3];
1.1075.2.161.  .1(raebu 5446:21):                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  5447:             }
                   5448:         } elsif ($pattern =~ /^\*/) {
                   5449:             #*.msu.edu
                   5450:             $pattern=~s/\*//;
                   5451:             if (!defined($name)) {
                   5452:                 use Socket;
                   5453:                 my $netaddr=inet_aton($ip);
                   5454:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5455:             }
1.1075.2.161.  .1(raebu 5456:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  5457:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5458:             #127.0.0.1
1.1075.2.161.  .1(raebu 5459:21):             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  5460:         } else {
                   5461:             #some.name.com
                   5462:             if (!defined($name)) {
                   5463:                 use Socket;
                   5464:                 my $netaddr=inet_aton($ip);
                   5465:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5466:             }
1.1075.2.161.  .1(raebu 5467:21):             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   5468:21):         }
                   5469:21):         if ($allowed =~ /^(0|1)$/) { last; }
                   5470:21):     }
                   5471:21):     if ($allowed eq '') {
                   5472:21):         if ($numdenies && !$numallows) {
                   5473:21):             $allowed = 1;
                   5474:21):         } else {
                   5475:21):             $allowed = 0;
1.682     raeburn  5476:         }
                   5477:     }
                   5478:     return $allowed;
                   5479: }
                   5480: 
                   5481: ###############################################
                   5482: 
1.60      matthew  5483: =pod
                   5484: 
1.112     bowersj2 5485: =head1 Domain Template Functions
                   5486: 
                   5487: =over 4
                   5488: 
                   5489: =item * &determinedomain()
1.60      matthew  5490: 
                   5491: Inputs: $domain (usually will be undef)
                   5492: 
1.63      www      5493: Returns: Determines which domain should be used for designs
1.60      matthew  5494: 
                   5495: =cut
1.54      www      5496: 
1.60      matthew  5497: ###############################################
1.63      www      5498: sub determinedomain {
                   5499:     my $domain=shift;
1.531     albertel 5500:     if (! $domain) {
1.60      matthew  5501:         # Determine domain if we have not been given one
1.893     raeburn  5502:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5503:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5504:         if ($env{'request.role.domain'}) { 
                   5505:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5506:         }
                   5507:     }
1.63      www      5508:     return $domain;
                   5509: }
                   5510: ###############################################
1.517     raeburn  5511: 
1.518     albertel 5512: sub devalidate_domconfig_cache {
                   5513:     my ($udom)=@_;
                   5514:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5515: }
                   5516: 
                   5517: # ---------------------- Get domain configuration for a domain
                   5518: sub get_domainconf {
                   5519:     my ($udom) = @_;
                   5520:     my $cachetime=1800;
                   5521:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5522:     if (defined($cached)) { return %{$result}; }
                   5523: 
                   5524:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5525: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5526:     my (%designhash,%legacy);
1.518     albertel 5527:     if (keys(%domconfig) > 0) {
                   5528:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5529:             if (keys(%{$domconfig{'login'}})) {
                   5530:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5531:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5532:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5533:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5534:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5535:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5536:                                         if ($key eq 'loginvia') {
                   5537:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5538:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5539:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5540:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5541:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5542:                                                 } else {
                   5543:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5544:                                                 }
1.948     raeburn  5545:                                             }
1.1075.2.87  raeburn  5546:                                         } elsif ($key eq 'headtag') {
                   5547:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5548:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5549:                                             }
1.946     raeburn  5550:                                         }
1.1075.2.87  raeburn  5551:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5552:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5553:                                         }
1.946     raeburn  5554:                                     }
                   5555:                                 }
                   5556:                             }
1.1075.2.158  raeburn  5557:                         } elsif ($key eq 'saml') {
                   5558:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5559:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   5560:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   5561:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1075.2.161.  .9(raebu 5562:22):                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1075.2.158  raeburn  5563:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   5564:                                         }
                   5565:                                     }
                   5566:                                 }
                   5567:                             }
1.946     raeburn  5568:                         } else {
                   5569:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5570:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5571:                                     $domconfig{'login'}{$key}{$img};
                   5572:                             }
1.699     raeburn  5573:                         }
                   5574:                     } else {
                   5575:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5576:                     }
1.632     raeburn  5577:                 }
                   5578:             } else {
                   5579:                 $legacy{'login'} = 1;
1.518     albertel 5580:             }
1.632     raeburn  5581:         } else {
                   5582:             $legacy{'login'} = 1;
1.518     albertel 5583:         }
                   5584:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5585:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5586:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5587:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5588:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5589:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5590:                         }
1.518     albertel 5591:                     }
                   5592:                 }
1.632     raeburn  5593:             } else {
                   5594:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5595:             }
1.632     raeburn  5596:         } else {
                   5597:             $legacy{'rolecolors'} = 1;
1.518     albertel 5598:         }
1.948     raeburn  5599:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5600:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5601:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5602:             }
                   5603:         }
1.632     raeburn  5604:         if (keys(%legacy) > 0) {
                   5605:             my %legacyhash = &get_legacy_domconf($udom);
                   5606:             foreach my $item (keys(%legacyhash)) {
                   5607:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5608:                     if ($legacy{'login'}) { 
                   5609:                         $designhash{$item} = $legacyhash{$item};
                   5610:                     }
                   5611:                 } else {
                   5612:                     if ($legacy{'rolecolors'}) {
                   5613:                         $designhash{$item} = $legacyhash{$item};
                   5614:                     }
1.518     albertel 5615:                 }
                   5616:             }
                   5617:         }
1.632     raeburn  5618:     } else {
                   5619:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5620:     }
                   5621:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5622: 				  $cachetime);
                   5623:     return %designhash;
                   5624: }
                   5625: 
1.632     raeburn  5626: sub get_legacy_domconf {
                   5627:     my ($udom) = @_;
                   5628:     my %legacyhash;
                   5629:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5630:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5631:     if (-e $designfile) {
1.1075.2.128  raeburn  5632:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5633:             while (my $line = <$fh>) {
                   5634:                 next if ($line =~ /^\#/);
                   5635:                 chomp($line);
                   5636:                 my ($key,$val)=(split(/\=/,$line));
                   5637:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5638:             }
                   5639:             close($fh);
                   5640:         }
                   5641:     }
1.1026    raeburn  5642:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5643:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5644:     }
                   5645:     return %legacyhash;
                   5646: }
                   5647: 
1.63      www      5648: =pod
                   5649: 
1.112     bowersj2 5650: =item * &domainlogo()
1.63      www      5651: 
                   5652: Inputs: $domain (usually will be undef)
                   5653: 
                   5654: Returns: A link to a domain logo, if the domain logo exists.
                   5655: If the domain logo does not exist, a description of the domain.
                   5656: 
                   5657: =cut
1.112     bowersj2 5658: 
1.63      www      5659: ###############################################
                   5660: sub domainlogo {
1.517     raeburn  5661:     my $domain = &determinedomain(shift);
1.518     albertel 5662:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5663:     # See if there is a logo
                   5664:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5665:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5666:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5667: 	    if ($imgsrc =~ m{^/res/}) {
                   5668: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5669: 		&Apache::lonnet::repcopy($local_name);
                   5670: 	    }
                   5671: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1075.2.161.  .2(raebu 5672:22):         }
                   5673:22):         my $alttext = $domain;
                   5674:22):         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   5675:22):             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   5676:22):         }
                   5677:22):         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 5678:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5679:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5680:     } else {
1.60      matthew  5681:         return '';
1.59      www      5682:     }
                   5683: }
1.63      www      5684: ##############################################
                   5685: 
                   5686: =pod
                   5687: 
1.112     bowersj2 5688: =item * &designparm()
1.63      www      5689: 
                   5690: Inputs: $which parameter; $domain (usually will be undef)
                   5691: 
                   5692: Returns: value of designparamter $which
                   5693: 
                   5694: =cut
1.112     bowersj2 5695: 
1.397     albertel 5696: 
1.400     albertel 5697: ##############################################
1.397     albertel 5698: sub designparm {
                   5699:     my ($which,$domain)=@_;
                   5700:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5701:         return $env{'environment.color.'.$which};
1.96      www      5702:     }
1.63      www      5703:     $domain=&determinedomain($domain);
1.1016    raeburn  5704:     my %domdesign;
                   5705:     unless ($domain eq 'public') {
                   5706:         %domdesign = &get_domainconf($domain);
                   5707:     }
1.520     raeburn  5708:     my $output;
1.517     raeburn  5709:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5710:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5711:     } else {
1.520     raeburn  5712:         $output = $defaultdesign{$which};
                   5713:     }
                   5714:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5715:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5716:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5717:             if ($output =~ m{^/res/}) {
                   5718:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5719:                 &Apache::lonnet::repcopy($local_name);
                   5720:             }
1.520     raeburn  5721:             $output = &lonhttpdurl($output);
                   5722:         }
1.63      www      5723:     }
1.520     raeburn  5724:     return $output;
1.63      www      5725: }
1.59      www      5726: 
1.822     bisitz   5727: ##############################################
                   5728: =pod
                   5729: 
1.832     bisitz   5730: =item * &authorspace()
                   5731: 
1.1028    raeburn  5732: Inputs: $url (usually will be undef).
1.832     bisitz   5733: 
1.1075.2.40  raeburn  5734: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5735:          directory being viewed (or for which action is being taken). 
                   5736:          If $url is provided, and begins /priv/<domain>/<uname>
                   5737:          the path will be that portion of the $context argument.
                   5738:          Otherwise the path will be for the author space of the current
                   5739:          user when the current role is author, or for that of the 
                   5740:          co-author/assistant co-author space when the current role 
                   5741:          is co-author or assistant co-author.
1.832     bisitz   5742: 
                   5743: =cut
                   5744: 
                   5745: sub authorspace {
1.1028    raeburn  5746:     my ($url) = @_;
                   5747:     if ($url ne '') {
                   5748:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5749:            return $1;
                   5750:         }
                   5751:     }
1.832     bisitz   5752:     my $caname = '';
1.1024    www      5753:     my $cadom = '';
1.1028    raeburn  5754:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5755:         ($cadom,$caname) =
1.832     bisitz   5756:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5757:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5758:         $caname = $env{'user.name'};
1.1024    www      5759:         $cadom = $env{'user.domain'};
1.832     bisitz   5760:     }
1.1028    raeburn  5761:     if (($caname ne '') && ($cadom ne '')) {
                   5762:         return "/priv/$cadom/$caname/";
                   5763:     }
                   5764:     return;
1.832     bisitz   5765: }
                   5766: 
                   5767: ##############################################
                   5768: =pod
                   5769: 
1.822     bisitz   5770: =item * &head_subbox()
                   5771: 
                   5772: Inputs: $content (contains HTML code with page functions, etc.)
                   5773: 
                   5774: Returns: HTML div with $content
                   5775:          To be included in page header
                   5776: 
                   5777: =cut
                   5778: 
                   5779: sub head_subbox {
                   5780:     my ($content)=@_;
                   5781:     my $output =
1.993     raeburn  5782:         '<div class="LC_head_subbox">'
1.822     bisitz   5783:        .$content
                   5784:        .'</div>'
                   5785: }
                   5786: 
                   5787: ##############################################
                   5788: =pod
                   5789: 
                   5790: =item * &CSTR_pageheader()
                   5791: 
1.1026    raeburn  5792: Input: (optional) filename from which breadcrumb trail is built.
                   5793:        In most cases no input as needed, as $env{'request.filename'}
                   5794:        is appropriate for use in building the breadcrumb trail.
1.1075.2.161.  .6(raebu 5795:22):        frameset flag
                   5796:22):        If page header is being requested for use in a frameset, then
                   5797:22):        the second (option) argument -- frameset will be true, and
                   5798:22):        the target attribute set for links should be target="_parent".
1.822     bisitz   5799: 
                   5800: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5801:          To be included on Authoring Space pages
1.822     bisitz   5802: 
                   5803: =cut
                   5804: 
                   5805: sub CSTR_pageheader {
1.1075.2.161.  .6(raebu 5806:22):     my ($trailfile,$frameset) = @_;
1.1026    raeburn  5807:     if ($trailfile eq '') {
                   5808:         $trailfile = $env{'request.filename'};
                   5809:     }
                   5810: 
                   5811: # this is for resources; directories have customtitle, and crumbs
                   5812: # and select recent are created in lonpubdir.pm
                   5813: 
                   5814:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5815:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5816:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5817:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5818:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5819: 
                   5820:     my $parentpath = '';
                   5821:     my $lastitem = '';
                   5822:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5823:         $parentpath = $1;
                   5824:         $lastitem = $2;
                   5825:     } else {
                   5826:         $lastitem = $thisdisfn;
                   5827:     }
1.921     bisitz   5828: 
1.1075.2.161.  .6(raebu 5829:22):     my ($target,$crumbtarget) = (' target="_top"','_top');
                   5830:22):     if ($frameset) {
                   5831:22):         $target = ' target="_parent"';
                   5832:22):         $crumbtarget = '_parent';
                   5833:22):     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
                   5834:22):         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   5835:22):         $crumbtarget = $env{'request.deeplink.target'};
                   5836:22):     }
                   5837:22): 
1.921     bisitz   5838:     my $output =
1.822     bisitz   5839:          '<div>'
                   5840:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5841:         .'<b>'.&mt('Authoring Space:').'</b> '
1.1075.2.161.  .6(raebu 5842:22):         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   5843:22):         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   5844: 
                   5845:     if ($lastitem) {
                   5846:         $output .=
                   5847:              '<span class="LC_filename">'
                   5848:             .$lastitem
                   5849:             .'</span>';
                   5850:     }
                   5851:     $output .=
                   5852:          '<br />'
1.1075.2.161.  .6(raebu 5853:22):         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.822     bisitz   5854:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5855:         .'</form>'
1.1075.2.161.  .6(raebu 5856:22):         .&Apache::lonmenu::constspaceform($frameset)
1.822     bisitz   5857:         .'</div>';
1.921     bisitz   5858: 
                   5859:     return $output;
1.822     bisitz   5860: }
                   5861: 
1.60      matthew  5862: ###############################################
                   5863: ###############################################
                   5864: 
                   5865: =pod
                   5866: 
1.112     bowersj2 5867: =back
                   5868: 
1.549     albertel 5869: =head1 HTML Helpers
1.112     bowersj2 5870: 
                   5871: =over 4
                   5872: 
                   5873: =item * &bodytag()
1.60      matthew  5874: 
                   5875: Returns a uniform header for LON-CAPA web pages.
                   5876: 
                   5877: Inputs: 
                   5878: 
1.112     bowersj2 5879: =over 4
                   5880: 
                   5881: =item * $title, A title to be displayed on the page.
                   5882: 
                   5883: =item * $function, the current role (can be undef).
                   5884: 
                   5885: =item * $addentries, extra parameters for the <body> tag.
                   5886: 
                   5887: =item * $bodyonly, if defined, only return the <body> tag.
                   5888: 
                   5889: =item * $domain, if defined, force a given domain.
                   5890: 
                   5891: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5892:             text interface only)
1.60      matthew  5893: 
1.814     bisitz   5894: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5895:                      navigational links
1.317     albertel 5896: 
1.338     albertel 5897: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5898: 
1.1075.2.12  raeburn  5899: =item * $no_inline_link, if true and in remote mode, don't show the
                   5900:          'Switch To Inline Menu' link
                   5901: 
1.460     albertel 5902: =item * $args, optional argument valid values are
                   5903:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133  raeburn  5904:             use_absolute     -> for external resource or syllabus, this will
                   5905:                                 contain https://<hostname> if server uses
                   5906:                                 https (as per hosts.tab), but request is for http
                   5907:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5908: 
1.1075.2.15  raeburn  5909: =item * $advtoolsref, optional argument, ref to an array containing
                   5910:             inlineremote items to be added in "Functions" menu below
                   5911:             breadcrumbs.
                   5912: 
1.1075.2.161.  .1(raebu 5913:21): =item * $ltiscope, optional argument, will be one of: resource, map or
                   5914:21):             course, if LON-CAPA is in LTI Provider context. Value is
                   5915:21):             the scope of use, i.e., launch was for access to a single, a map
                   5916:21):             or the entire course.
                   5917:21): 
                   5918:21): =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   5919:21):             context, this will contain the URL for the landing item in
                   5920:21):             the course, after launch from an LTI Consumer
                   5921:21): 
                   5922:21): =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   5923:21):             context, this will contain a reference to hash of items
                   5924:21):             to be included in the page header and/or inline menu.
                   5925:21): 
          .8(raebu 5926:22): =item * $menucoll, optional argument, if specific menu collection is in
                   5927:22):             effect, either set as the default for the course, or set for
                   5928:22):             the deeplink paramater for $env{'request.deeplink.login'}
                   5929:22):             then $menucoll will be the number of that collection.
                   5930:22): 
                   5931:22): =item * $menuref, optional argument, reference to a hash, containing the
                   5932:22):             menu options included for the menu in effect, based on the
                   5933:22):             configuration for the numbered menu collection in use.
                   5934:22): 
                   5935:22): =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   5936:22):             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   5937:22):             if so, $showncrumbsref is set there to 1, and will propagate back
                   5938:22):             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   5939:22):             being called a second time.
                   5940:22): 
1.112     bowersj2 5941: =back
                   5942: 
1.60      matthew  5943: Returns: A uniform header for LON-CAPA web pages.  
                   5944: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5945: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5946: other decorations will be returned.
                   5947: 
                   5948: =cut
                   5949: 
1.54      www      5950: sub bodytag {
1.831     bisitz   5951:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.161.  .1(raebu 5952:21):         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
          .8(raebu 5953:22):         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 5954: 
1.954     raeburn  5955:     my $public;
                   5956:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5957:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5958:         $public = 1;
                   5959:     }
1.460     albertel 5960:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5961:     my $httphost = $args->{'use_absolute'};
1.1075.2.133  raeburn  5962:     my $hostname = $args->{'hostname'};
1.339     albertel 5963: 
1.183     matthew  5964:     $function = &get_users_function() if (!$function);
1.339     albertel 5965:     my $img =    &designparm($function.'.img',$domain);
                   5966:     my $font =   &designparm($function.'.font',$domain);
                   5967:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5968: 
1.803     bisitz   5969:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5970: 		   'bgcolor' => $pgbg,
1.339     albertel 5971: 		   'text'    => $font,
                   5972:                    'alink'   => &designparm($function.'.alink',$domain),
                   5973: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5974: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5975:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5976: 
1.63      www      5977:  # role and realm
1.1075.2.68  raeburn  5978:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5979:     if ($realm) {
                   5980:         $realm = '/'.$realm;
                   5981:     }
1.1075.2.159  raeburn  5982:     if ($role eq 'ca') {
1.479     albertel 5983:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5984:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5985:     } 
1.55      www      5986: # realm
1.1075.2.158  raeburn  5987:     my ($cid,$sec);
1.258     albertel 5988:     if ($env{'request.course.id'}) {
1.1075.2.158  raeburn  5989:         $cid = $env{'request.course.id'};
                   5990:         if ($env{'request.course.sec'}) {
                   5991:             $sec = $env{'request.course.sec'};
                   5992:         }
                   5993:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   5994:         if (&Apache::lonnet::is_course($1,$2)) {
                   5995:             $cid = $1.'_'.$2;
                   5996:             $sec = $3;
                   5997:         }
                   5998:     }
                   5999:     if ($cid) {
1.378     raeburn  6000:         if ($env{'request.role'} !~ /^cr/) {
                   6001:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  6002:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  6003:             if ($env{'request.role.desc'}) {
                   6004:                 $role = $env{'request.role.desc'};
                   6005:             } else {
                   6006:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6007:             }
1.1075.2.115  raeburn  6008:         } else {
                   6009:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  6010:         }
1.1075.2.158  raeburn  6011:         if ($sec) {
                   6012:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6013:         }   
1.1075.2.158  raeburn  6014: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6015:     } else {
                   6016:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6017:     }
1.433     albertel 6018: 
1.359     albertel 6019:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6020: 
1.438     albertel 6021:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6022: 
1.101     www      6023: # construct main body tag
1.359     albertel 6024:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  6025: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6026: 
1.1075.2.38  raeburn  6027:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6028: 
                   6029:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6030:         return $bodytag;
1.1075.2.38  raeburn  6031:     }
1.359     albertel 6032: 
1.954     raeburn  6033:     if ($public) {
1.433     albertel 6034: 	undef($role);
                   6035:     }
1.1075.2.158  raeburn  6036: 
1.1075.2.161.  .1(raebu 6037:21):     my $showcrstitle = 1;
                   6038:21):     if (($cid) && ($env{'request.lti.login'})) {
                   6039:21):         if (ref($ltimenu) eq 'HASH') {
                   6040:21):             unless ($ltimenu->{'role'}) {
                   6041:21):                 undef($role);
                   6042:21):             }
                   6043:21):             unless ($ltimenu->{'coursetitle'}) {
                   6044:21):                 $realm='&nbsp;';
                   6045:21):                 $showcrstitle = 0;
                   6046:21):             }
                   6047:21):         }
                   6048:21):     } elsif (($cid) && ($menucoll)) {
                   6049:21):         if (ref($menuref) eq 'HASH') {
                   6050:21):             unless ($menuref->{'role'}) {
                   6051:21):                 undef($role);
                   6052:21):             }
                   6053:21):             unless ($menuref->{'crs'}) {
                   6054:21):                 $realm='&nbsp;';
                   6055:21):                 $showcrstitle = 0;
                   6056:21):             }
                   6057:21):         }
                   6058:21):     }
                   6059:21): 
1.762     bisitz   6060:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6061:     #
                   6062:     # Extra info if you are the DC
                   6063:     my $dc_info = '';
1.1075.2.161.  .1(raebu 6064:21):     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1075.2.158  raeburn  6065:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6066:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6067:         $dc_info =~ s/\s+$//;
1.359     albertel 6068:     }
                   6069: 
1.1075.2.161.  .1(raebu 6070:21):     my $crstype;
                   6071:21):     if ($cid) {
                   6072:21):         $crstype = $env{'course.'.$cid.'.type'};
                   6073:21):     } elsif ($args->{'crstype'}) {
                   6074:21):         $crstype = $args->{'crstype'};
                   6075:21):     }
                   6076:21): 
1.1075.2.108  raeburn  6077:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 6078: 
1.1075.2.13  raeburn  6079:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6080: 
1.1075.2.38  raeburn  6081: 
                   6082: 
1.1075.2.21  raeburn  6083:     my $funclist;
                   6084:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  6085:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  6086:                     Apache::lonmenu::serverform();
                   6087:         my $forbodytag;
                   6088:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6089:                                             $forcereg,$args->{'group'},
                   6090:                                             $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6091:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  6092:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6093:             $funclist = $forbodytag;
                   6094:         }
                   6095:     } else {
1.903     droeschl 6096: 
                   6097:         #    if ($env{'request.state'} eq 'construct') {
                   6098:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6099:         #    }
                   6100: 
1.1075.2.38  raeburn  6101:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6102:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6103: 
1.1075.2.161.  .1(raebu 6104:21):         unless ($args->{'no_primary_menu'}) {
          .4(raebu 6105:22):             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
          .6(raebu 6106:22):                                                               $args->{'links_disabled'},
                   6107:22):                                                               $args->{'links_target'});
          .1(raebu 6108:21):             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6109:21):                 if ($dc_info) {
                   6110:21):                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6111:21):                 }
                   6112:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6113:21):                                <em>$realm</em> $dc_info</div>|;
                   6114:21):                 return $bodytag;
1.1075.2.1  raeburn  6115:             }
1.894     droeschl 6116: 
1.1075.2.161.  .1(raebu 6117:21):             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6118:21):                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6119:21):             }
1.916     droeschl 6120: 
1.1075.2.161.  .1(raebu 6121:21):             $bodytag .= $right;
1.852     droeschl 6122: 
1.1075.2.161.  .1(raebu 6123:21):             if ($dc_info) {
                   6124:21):                 $dc_info = &dc_courseid_toggle($dc_info);
                   6125:21):             }
                   6126:21):             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6127:         }
1.916     droeschl 6128: 
1.1075.2.61  raeburn  6129:         #if directed to not display the secondary menu, don't.
                   6130:         if ($args->{'no_secondary_menu'}) {
                   6131:             return $bodytag;
                   6132:         }
1.903     droeschl 6133:         #don't show menus for public users
1.954     raeburn  6134:         if (!$public){
1.1075.2.161.  .1(raebu 6135:21):             unless ($args->{'no_inline_menu'}) {
                   6136:21):                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
                   6137:21):                                                             $args->{'no_primary_menu'},
                   6138:21):                                                             $menucoll,$menuref,
          .6(raebu 6139:22):                                                             $args->{'links_disabled'},
                   6140:22):                                                             $args->{'links_target'});
          .1(raebu 6141:21):             }
1.903     droeschl 6142:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6143:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6144:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6145:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.161.  .8(raebu 6146:22):                                 $args->{'bread_crumbs'},'','',$hostname,
                   6147:22):                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.116  raeburn  6148:             } elsif ($forcereg) {
1.1075.2.22  raeburn  6149:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.161.  .8(raebu 6150:22):                                 $args->{'group'},$args->{'hide_buttons'},
                   6151:22):                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1075.2.15  raeburn  6152:             } else {
1.1075.2.21  raeburn  6153:                 my $forbodytag;
                   6154:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6155:                                                     $forcereg,$args->{'group'},
                   6156:                                                     $args->{'bread_crumbs'},
1.1075.2.133  raeburn  6157:                                                     $advtoolsref,'',$hostname,
                   6158:                                                     \$forbodytag);
1.1075.2.21  raeburn  6159:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   6160:                     $bodytag .= $forbodytag;
                   6161:                 }
1.920     raeburn  6162:             }
1.903     droeschl 6163:         }else{
                   6164:             # this is to seperate menu from content when there's no secondary
                   6165:             # menu. Especially needed for public accessible ressources.
                   6166:             $bodytag .= '<hr style="clear:both" />';
                   6167:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6168:         }
1.903     droeschl 6169: 
1.235     raeburn  6170:         return $bodytag;
1.1075.2.12  raeburn  6171:     }
                   6172: 
                   6173: #
                   6174: # Top frame rendering, Remote is up
                   6175: #
                   6176: 
                   6177:     my $imgsrc = $img;
                   6178:     if ($img =~ /^\/adm/) {
                   6179:         $imgsrc = &lonhttpdurl($img);
                   6180:     }
                   6181:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   6182: 
1.1075.2.60  raeburn  6183:     my $help=($no_inline_link?''
                   6184:               :&Apache::loncommon::top_nav_help('Help'));
                   6185: 
1.1075.2.12  raeburn  6186:     # Explicit link to get inline menu
                   6187:     my $menu= ($no_inline_link?''
                   6188:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   6189: 
                   6190:     if ($dc_info) {
                   6191:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   6192:     }
                   6193: 
1.1075.2.38  raeburn  6194:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   6195:     unless ($public) {
                   6196:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   6197:                                 undef,'LC_menubuttons_link');
                   6198:     }
                   6199: 
1.1075.2.12  raeburn  6200:     unless ($env{'form.inhibitmenu'}) {
                   6201:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  6202:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  6203:                        <li>$help</li>
1.1075.2.12  raeburn  6204:                        <li>$menu</li>
                   6205:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   6206:     }
1.1075.2.13  raeburn  6207:     if ($env{'request.state'} eq 'construct') {
                   6208:         if (!$public){
                   6209:             if ($env{'request.state'} eq 'construct') {
                   6210:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  6211:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  6212:                             &Apache::lonhtmlcommon::scripttag('','end').
                   6213:                             &Apache::lonmenu::innerregister($forcereg,
                   6214:                                                             $args->{'bread_crumbs'});
                   6215:             }
                   6216:         }
                   6217:     }
1.1075.2.21  raeburn  6218:     return $bodytag."\n".$funclist;
1.182     matthew  6219: }
                   6220: 
1.917     raeburn  6221: sub dc_courseid_toggle {
                   6222:     my ($dc_info) = @_;
1.980     raeburn  6223:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6224:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6225:            &mt('(More ...)').'</a></span>'.
                   6226:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6227: }
                   6228: 
1.330     albertel 6229: sub make_attr_string {
                   6230:     my ($register,$attr_ref) = @_;
                   6231: 
                   6232:     if ($attr_ref && !ref($attr_ref)) {
                   6233: 	die("addentries Must be a hash ref ".
                   6234: 	    join(':',caller(1))." ".
                   6235: 	    join(':',caller(0))." ");
                   6236:     }
                   6237: 
                   6238:     if ($register) {
1.339     albertel 6239: 	my ($on_load,$on_unload);
                   6240: 	foreach my $key (keys(%{$attr_ref})) {
                   6241: 	    if      (lc($key) eq 'onload') {
                   6242: 		$on_load.=$attr_ref->{$key}.';';
                   6243: 		delete($attr_ref->{$key});
                   6244: 
                   6245: 	    } elsif (lc($key) eq 'onunload') {
                   6246: 		$on_unload.=$attr_ref->{$key}.';';
                   6247: 		delete($attr_ref->{$key});
                   6248: 	    }
                   6249: 	}
1.1075.2.12  raeburn  6250:         if ($env{'environment.remote'} eq 'on') {
                   6251:             $attr_ref->{'onload'}  =
                   6252:                 &Apache::lonmenu::loadevents().  $on_load;
                   6253:             $attr_ref->{'onunload'}=
                   6254:                 &Apache::lonmenu::unloadevents().$on_unload;
                   6255:         } else {  
                   6256: 	    $attr_ref->{'onload'}  = $on_load;
                   6257: 	    $attr_ref->{'onunload'}= $on_unload;
                   6258:         }
1.330     albertel 6259:     }
1.339     albertel 6260: 
1.330     albertel 6261:     my $attr_string;
1.1075.2.56  raeburn  6262:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 6263: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   6264:     }
                   6265:     return $attr_string;
                   6266: }
                   6267: 
                   6268: 
1.182     matthew  6269: ###############################################
1.251     albertel 6270: ###############################################
                   6271: 
                   6272: =pod
                   6273: 
                   6274: =item * &endbodytag()
                   6275: 
                   6276: Returns a uniform footer for LON-CAPA web pages.
                   6277: 
1.635     raeburn  6278: Inputs: 1 - optional reference to an args hash
                   6279: If in the hash, key for noredirectlink has a value which evaluates to true,
                   6280: a 'Continue' link is not displayed if the page contains an
                   6281: internal redirect in the <head></head> section,
                   6282: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 6283: 
                   6284: =cut
                   6285: 
                   6286: sub endbodytag {
1.635     raeburn  6287:     my ($args) = @_;
1.1075.2.6  raeburn  6288:     my $endbodytag;
                   6289:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   6290:         $endbodytag='</body>';
                   6291:     }
1.315     albertel 6292:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  6293:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1075.2.161.  .9(raebu 6294:22):             my ($endbodyjs,$idattr);
                   6295:22):             if ($env{'internal.head.to_opener'}) {
                   6296:22):                 my $linkid = 'LC_continue_link';
                   6297:22):                 $idattr = ' id="'.$linkid.'"';
                   6298:22):                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   6299:22):                 $endbodyjs=<<ENDJS;
                   6300:22): <script type="text/javascript">
                   6301:22): // <![CDATA[
                   6302:22): function ebFunction(evt) {
                   6303:22):     evt.preventDefault();
                   6304:22):     var dest = '$redirect_for_js';
                   6305:22):     if (window.opener != null && !window.opener.closed) {
                   6306:22):         window.opener.location.href=dest;
                   6307:22):         window.close();
                   6308:22):     } else {
                   6309:22):         window.location.href=dest;
                   6310:22):     }
                   6311:22):     return false;
                   6312:22): }
                   6313:22): 
                   6314:22): \$(document).ready(function () {
                   6315:22):   if (document.getElementById('$linkid')) {
                   6316:22):     var clickelem = document.getElementById('$linkid');
                   6317:22):     clickelem.addEventListener('click',ebFunction,false);
                   6318:22):   }
                   6319:22): });
                   6320:22): // ]]>
                   6321:22): </script>
                   6322:22): ENDJS
                   6323:22):             }
1.635     raeburn  6324: 	    $endbodytag=
1.1075.2.161.  .9(raebu 6325:22): 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  6326: 	        &mt('Continue').'</a>'.
                   6327: 	        $endbodytag;
                   6328:         }
1.315     albertel 6329:     }
1.251     albertel 6330:     return $endbodytag;
                   6331: }
                   6332: 
1.352     albertel 6333: =pod
                   6334: 
                   6335: =item * &standard_css()
                   6336: 
                   6337: Returns a style sheet
                   6338: 
                   6339: Inputs: (all optional)
                   6340:             domain         -> force to color decorate a page for a specific
                   6341:                                domain
                   6342:             function       -> force usage of a specific rolish color scheme
                   6343:             bgcolor        -> override the default page bgcolor
                   6344: 
                   6345: =cut
                   6346: 
1.343     albertel 6347: sub standard_css {
1.345     albertel 6348:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 6349:     $function  = &get_users_function() if (!$function);
                   6350:     my $img    = &designparm($function.'.img',   $domain);
                   6351:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   6352:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 6353:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 6354: #second colour for later usage
1.345     albertel 6355:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 6356:     my $pgbg_or_bgcolor =
                   6357: 	         $bgcolor ||
1.352     albertel 6358: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 6359:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 6360:     my $alink  = &designparm($function.'.alink', $domain);
                   6361:     my $vlink  = &designparm($function.'.vlink', $domain);
                   6362:     my $link   = &designparm($function.'.link',  $domain);
                   6363: 
1.602     albertel 6364:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 6365:     my $mono                 = 'monospace';
1.850     bisitz   6366:     my $data_table_head      = $sidebg;
                   6367:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   6368:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 6369:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 6370:     my $data_table_highlight = '#FFFF00';
1.352     albertel 6371:     my $mail_new             = '#FFBB77';
                   6372:     my $mail_new_hover       = '#DD9955';
                   6373:     my $mail_read            = '#BBBB77';
                   6374:     my $mail_read_hover      = '#999944';
                   6375:     my $mail_replied         = '#AAAA88';
                   6376:     my $mail_replied_hover   = '#888855';
                   6377:     my $mail_other           = '#99BBBB';
                   6378:     my $mail_other_hover     = '#669999';
1.391     albertel 6379:     my $table_header         = '#DDDDDD';
1.489     raeburn  6380:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   6381:     my $lg_border_color      = '#C8C8C8';
1.952     onken    6382:     my $button_hover         = '#BF2317';
1.392     albertel 6383: 
1.608     albertel 6384:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   6385:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   6386:                                              : '0 3px 0 4px';
1.448     albertel 6387: 
1.523     albertel 6388: 
1.343     albertel 6389:     return <<END;
1.947     droeschl 6390: 
                   6391: /* needed for iframe to allow 100% height in FF */
                   6392: body, html { 
                   6393:     margin: 0;
                   6394:     padding: 0 0.5%;
                   6395:     height: 99%; /* to avoid scrollbars */
                   6396: }
                   6397: 
1.795     www      6398: body {
1.911     bisitz   6399:   font-family: $sans;
                   6400:   line-height:130%;
                   6401:   font-size:0.83em;
                   6402:   color:$font;
1.795     www      6403: }
                   6404: 
1.959     onken    6405: a:focus,
                   6406: a:focus img {
1.795     www      6407:   color: red;
                   6408: }
1.698     harmsja  6409: 
1.911     bisitz   6410: form, .inline {
                   6411:   display: inline;
1.795     www      6412: }
1.721     harmsja  6413: 
1.795     www      6414: .LC_right {
1.911     bisitz   6415:   text-align:right;
1.795     www      6416: }
                   6417: 
                   6418: .LC_middle {
1.911     bisitz   6419:   vertical-align:middle;
1.795     www      6420: }
1.721     harmsja  6421: 
1.1075.2.38  raeburn  6422: .LC_floatleft {
                   6423:   float: left;
                   6424: }
                   6425: 
                   6426: .LC_floatright {
                   6427:   float: right;
                   6428: }
                   6429: 
1.911     bisitz   6430: .LC_400Box {
                   6431:   width:400px;
                   6432: }
1.721     harmsja  6433: 
1.947     droeschl 6434: .LC_iframecontainer {
                   6435:     width: 98%;
                   6436:     margin: 0;
                   6437:     position: fixed;
                   6438:     top: 8.5em;
                   6439:     bottom: 0;
                   6440: }
                   6441: 
                   6442: .LC_iframecontainer iframe{
                   6443:     border: none;
                   6444:     width: 100%;
                   6445:     height: 100%;
                   6446: }
                   6447: 
1.778     bisitz   6448: .LC_filename {
                   6449:   font-family: $mono;
                   6450:   white-space:pre;
1.921     bisitz   6451:   font-size: 120%;
1.778     bisitz   6452: }
                   6453: 
                   6454: .LC_fileicon {
                   6455:   border: none;
                   6456:   height: 1.3em;
                   6457:   vertical-align: text-bottom;
                   6458:   margin-right: 0.3em;
                   6459:   text-decoration:none;
                   6460: }
                   6461: 
1.1008    www      6462: .LC_setting {
                   6463:   text-decoration:underline;
                   6464: }
                   6465: 
1.350     albertel 6466: .LC_error {
                   6467:   color: red;
                   6468: }
1.795     www      6469: 
1.1075.2.15  raeburn  6470: .LC_warning {
                   6471:   color: darkorange;
                   6472: }
                   6473: 
1.457     albertel 6474: .LC_diff_removed {
1.733     bisitz   6475:   color: red;
1.394     albertel 6476: }
1.532     albertel 6477: 
                   6478: .LC_info,
1.457     albertel 6479: .LC_success,
                   6480: .LC_diff_added {
1.350     albertel 6481:   color: green;
                   6482: }
1.795     www      6483: 
1.802     bisitz   6484: div.LC_confirm_box {
                   6485:   background-color: #FAFAFA;
                   6486:   border: 1px solid $lg_border_color;
                   6487:   margin-right: 0;
                   6488:   padding: 5px;
                   6489: }
                   6490: 
                   6491: div.LC_confirm_box .LC_error img,
                   6492: div.LC_confirm_box .LC_success img {
                   6493:   vertical-align: middle;
                   6494: }
                   6495: 
1.1075.2.108  raeburn  6496: .LC_maxwidth {
                   6497:   max-width: 100%;
                   6498:   height: auto;
                   6499: }
                   6500: 
                   6501: .LC_textsize_mobile {
                   6502:   \@media only screen and (max-device-width: 480px) {
                   6503:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   6504:   }
                   6505: }
                   6506: 
1.440     albertel 6507: .LC_icon {
1.771     droeschl 6508:   border: none;
1.790     droeschl 6509:   vertical-align: middle;
1.771     droeschl 6510: }
                   6511: 
1.543     albertel 6512: .LC_docs_spacer {
                   6513:   width: 25px;
                   6514:   height: 1px;
1.771     droeschl 6515:   border: none;
1.543     albertel 6516: }
1.346     albertel 6517: 
1.532     albertel 6518: .LC_internal_info {
1.735     bisitz   6519:   color: #999999;
1.532     albertel 6520: }
                   6521: 
1.794     www      6522: .LC_discussion {
1.1050    www      6523:   background: $data_table_dark;
1.911     bisitz   6524:   border: 1px solid black;
                   6525:   margin: 2px;
1.794     www      6526: }
                   6527: 
                   6528: .LC_disc_action_left {
1.1050    www      6529:   background: $sidebg;
1.911     bisitz   6530:   text-align: left;
1.1050    www      6531:   padding: 4px;
                   6532:   margin: 2px;
1.794     www      6533: }
                   6534: 
                   6535: .LC_disc_action_right {
1.1050    www      6536:   background: $sidebg;
1.911     bisitz   6537:   text-align: right;
1.1050    www      6538:   padding: 4px;
                   6539:   margin: 2px;
1.794     www      6540: }
                   6541: 
                   6542: .LC_disc_new_item {
1.911     bisitz   6543:   background: white;
                   6544:   border: 2px solid red;
1.1050    www      6545:   margin: 4px;
                   6546:   padding: 4px;
1.794     www      6547: }
                   6548: 
                   6549: .LC_disc_old_item {
1.911     bisitz   6550:   background: white;
1.1050    www      6551:   margin: 4px;
                   6552:   padding: 4px;
1.794     www      6553: }
                   6554: 
1.458     albertel 6555: table.LC_pastsubmission {
                   6556:   border: 1px solid black;
                   6557:   margin: 2px;
                   6558: }
                   6559: 
1.924     bisitz   6560: table#LC_menubuttons {
1.345     albertel 6561:   width: 100%;
                   6562:   background: $pgbg;
1.392     albertel 6563:   border: 2px;
1.402     albertel 6564:   border-collapse: separate;
1.803     bisitz   6565:   padding: 0;
1.345     albertel 6566: }
1.392     albertel 6567: 
1.801     tempelho 6568: table#LC_title_bar a {
                   6569:   color: $fontmenu;
                   6570: }
1.836     bisitz   6571: 
1.807     droeschl 6572: table#LC_title_bar {
1.819     tempelho 6573:   clear: both;
1.836     bisitz   6574:   display: none;
1.807     droeschl 6575: }
                   6576: 
1.795     www      6577: table#LC_title_bar,
1.933     droeschl 6578: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 6579: table#LC_title_bar.LC_with_remote {
1.359     albertel 6580:   width: 100%;
1.392     albertel 6581:   border-color: $pgbg;
                   6582:   border-style: solid;
                   6583:   border-width: $border;
1.379     albertel 6584:   background: $pgbg;
1.801     tempelho 6585:   color: $fontmenu;
1.392     albertel 6586:   border-collapse: collapse;
1.803     bisitz   6587:   padding: 0;
1.819     tempelho 6588:   margin: 0;
1.359     albertel 6589: }
1.795     www      6590: 
1.933     droeschl 6591: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 6592:     margin: 0;
                   6593:     padding: 0;
1.933     droeschl 6594:     position: relative;
                   6595:     list-style: none;
1.913     droeschl 6596: }
1.933     droeschl 6597: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 6598:     display: inline;
                   6599: }
1.933     droeschl 6600: 
                   6601: .LC_breadcrumb_tools_navigation {
1.913     droeschl 6602:     padding: 0;
1.933     droeschl 6603:     margin: 0;
                   6604:     float: left;
1.913     droeschl 6605: }
1.933     droeschl 6606: .LC_breadcrumb_tools_tools {
                   6607:     padding: 0;
                   6608:     margin: 0;
1.913     droeschl 6609:     float: right;
                   6610: }
                   6611: 
1.359     albertel 6612: table#LC_title_bar td {
                   6613:   background: $tabbg;
                   6614: }
1.795     www      6615: 
1.911     bisitz   6616: table#LC_menubuttons img {
1.803     bisitz   6617:   border: none;
1.346     albertel 6618: }
1.795     www      6619: 
1.842     droeschl 6620: .LC_breadcrumbs_component {
1.911     bisitz   6621:   float: right;
                   6622:   margin: 0 1em;
1.357     albertel 6623: }
1.842     droeschl 6624: .LC_breadcrumbs_component img {
1.911     bisitz   6625:   vertical-align: middle;
1.777     tempelho 6626: }
1.795     www      6627: 
1.1075.2.108  raeburn  6628: .LC_breadcrumbs_hoverable {
                   6629:   background: $sidebg;
                   6630: }
                   6631: 
1.383     albertel 6632: td.LC_table_cell_checkbox {
                   6633:   text-align: center;
                   6634: }
1.795     www      6635: 
                   6636: .LC_fontsize_small {
1.911     bisitz   6637:   font-size: 70%;
1.705     tempelho 6638: }
                   6639: 
1.844     bisitz   6640: #LC_breadcrumbs {
1.911     bisitz   6641:   clear:both;
                   6642:   background: $sidebg;
                   6643:   border-bottom: 1px solid $lg_border_color;
                   6644:   line-height: 2.5em;
1.933     droeschl 6645:   overflow: hidden;
1.911     bisitz   6646:   margin: 0;
                   6647:   padding: 0;
1.995     raeburn  6648:   text-align: left;
1.819     tempelho 6649: }
1.862     bisitz   6650: 
1.1075.2.16  raeburn  6651: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6652:   clear:both;
                   6653:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6654:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6655:   margin: 0 0 10px 0;
1.966     bisitz   6656:   padding: 3px;
1.995     raeburn  6657:   text-align: left;
1.822     bisitz   6658: }
                   6659: 
1.795     www      6660: .LC_fontsize_medium {
1.911     bisitz   6661:   font-size: 85%;
1.705     tempelho 6662: }
                   6663: 
1.795     www      6664: .LC_fontsize_large {
1.911     bisitz   6665:   font-size: 120%;
1.705     tempelho 6666: }
                   6667: 
1.346     albertel 6668: .LC_menubuttons_inline_text {
                   6669:   color: $font;
1.698     harmsja  6670:   font-size: 90%;
1.701     harmsja  6671:   padding-left:3px;
1.346     albertel 6672: }
                   6673: 
1.934     droeschl 6674: .LC_menubuttons_inline_text img{
                   6675:   vertical-align: middle;
                   6676: }
                   6677: 
1.1051    www      6678: li.LC_menubuttons_inline_text img {
1.951     onken    6679:   cursor:pointer;
1.1002    droeschl 6680:   text-decoration: none;
1.951     onken    6681: }
                   6682: 
1.526     www      6683: .LC_menubuttons_link {
                   6684:   text-decoration: none;
                   6685: }
1.795     www      6686: 
1.522     albertel 6687: .LC_menubuttons_category {
1.521     www      6688:   color: $font;
1.526     www      6689:   background: $pgbg;
1.521     www      6690:   font-size: larger;
                   6691:   font-weight: bold;
                   6692: }
                   6693: 
1.346     albertel 6694: td.LC_menubuttons_text {
1.911     bisitz   6695:   color: $font;
1.346     albertel 6696: }
1.706     harmsja  6697: 
1.346     albertel 6698: .LC_current_location {
                   6699:   background: $tabbg;
                   6700: }
1.795     www      6701: 
1.1075.2.134  raeburn  6702: td.LC_zero_height {
                   6703:   line-height: 0;
                   6704:   cellpadding: 0;
                   6705: }
                   6706: 
1.938     bisitz   6707: table.LC_data_table {
1.347     albertel 6708:   border: 1px solid #000000;
1.402     albertel 6709:   border-collapse: separate;
1.426     albertel 6710:   border-spacing: 1px;
1.610     albertel 6711:   background: $pgbg;
1.347     albertel 6712: }
1.795     www      6713: 
1.422     albertel 6714: .LC_data_table_dense {
                   6715:   font-size: small;
                   6716: }
1.795     www      6717: 
1.507     raeburn  6718: table.LC_nested_outer {
                   6719:   border: 1px solid #000000;
1.589     raeburn  6720:   border-collapse: collapse;
1.803     bisitz   6721:   border-spacing: 0;
1.507     raeburn  6722:   width: 100%;
                   6723: }
1.795     www      6724: 
1.879     raeburn  6725: table.LC_innerpickbox,
1.507     raeburn  6726: table.LC_nested {
1.803     bisitz   6727:   border: none;
1.589     raeburn  6728:   border-collapse: collapse;
1.803     bisitz   6729:   border-spacing: 0;
1.507     raeburn  6730:   width: 100%;
                   6731: }
1.795     www      6732: 
1.911     bisitz   6733: table.LC_data_table tr th,
                   6734: table.LC_calendar tr th,
1.879     raeburn  6735: table.LC_prior_tries tr th,
                   6736: table.LC_innerpickbox tr th {
1.349     albertel 6737:   font-weight: bold;
                   6738:   background-color: $data_table_head;
1.801     tempelho 6739:   color:$fontmenu;
1.701     harmsja  6740:   font-size:90%;
1.347     albertel 6741: }
1.795     www      6742: 
1.879     raeburn  6743: table.LC_innerpickbox tr th,
                   6744: table.LC_innerpickbox tr td {
                   6745:   vertical-align: top;
                   6746: }
                   6747: 
1.711     raeburn  6748: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6749:   background-color: #CCCCCC;
1.711     raeburn  6750:   font-weight: bold;
                   6751:   text-align: left;
                   6752: }
1.795     www      6753: 
1.912     bisitz   6754: table.LC_data_table tr.LC_odd_row > td {
                   6755:   background-color: $data_table_light;
                   6756:   padding: 2px;
                   6757:   vertical-align: top;
                   6758: }
                   6759: 
1.809     bisitz   6760: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6761:   background-color: $data_table_light;
1.912     bisitz   6762:   vertical-align: top;
                   6763: }
                   6764: 
                   6765: table.LC_data_table tr.LC_even_row > td {
                   6766:   background-color: $data_table_dark;
1.425     albertel 6767:   padding: 2px;
1.900     bisitz   6768:   vertical-align: top;
1.347     albertel 6769: }
1.795     www      6770: 
1.809     bisitz   6771: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6772:   background-color: $data_table_dark;
1.900     bisitz   6773:   vertical-align: top;
1.347     albertel 6774: }
1.795     www      6775: 
1.425     albertel 6776: table.LC_data_table tr.LC_data_table_highlight td {
                   6777:   background-color: $data_table_darker;
                   6778: }
1.795     www      6779: 
1.639     raeburn  6780: table.LC_data_table tr td.LC_leftcol_header {
                   6781:   background-color: $data_table_head;
                   6782:   font-weight: bold;
                   6783: }
1.795     www      6784: 
1.451     albertel 6785: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6786: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6787:   font-weight: bold;
                   6788:   font-style: italic;
                   6789:   text-align: center;
                   6790:   padding: 8px;
1.347     albertel 6791: }
1.795     www      6792: 
1.1075.2.30  raeburn  6793: table.LC_data_table tr.LC_empty_row td,
                   6794: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6795:   background-color: $sidebg;
                   6796: }
                   6797: 
                   6798: table.LC_nested tr.LC_empty_row td {
                   6799:   background-color: #FFFFFF;
                   6800: }
                   6801: 
1.890     droeschl 6802: table.LC_caption {
                   6803: }
                   6804: 
1.507     raeburn  6805: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6806:   padding: 4ex
                   6807: }
1.795     www      6808: 
1.507     raeburn  6809: table.LC_nested_outer tr th {
                   6810:   font-weight: bold;
1.801     tempelho 6811:   color:$fontmenu;
1.507     raeburn  6812:   background-color: $data_table_head;
1.701     harmsja  6813:   font-size: small;
1.507     raeburn  6814:   border-bottom: 1px solid #000000;
                   6815: }
1.795     www      6816: 
1.507     raeburn  6817: table.LC_nested_outer tr td.LC_subheader {
                   6818:   background-color: $data_table_head;
                   6819:   font-weight: bold;
                   6820:   font-size: small;
                   6821:   border-bottom: 1px solid #000000;
                   6822:   text-align: right;
1.451     albertel 6823: }
1.795     www      6824: 
1.507     raeburn  6825: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6826:   background-color: #CCCCCC;
1.451     albertel 6827:   font-weight: bold;
                   6828:   font-size: small;
1.507     raeburn  6829:   text-align: center;
                   6830: }
1.795     www      6831: 
1.589     raeburn  6832: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6833: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6834:   text-align: left;
1.451     albertel 6835: }
1.795     www      6836: 
1.507     raeburn  6837: table.LC_nested td {
1.735     bisitz   6838:   background-color: #FFFFFF;
1.451     albertel 6839:   font-size: small;
1.507     raeburn  6840: }
1.795     www      6841: 
1.507     raeburn  6842: table.LC_nested_outer tr th.LC_right_item,
                   6843: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6844: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6845: table.LC_nested tr td.LC_right_item {
1.451     albertel 6846:   text-align: right;
                   6847: }
                   6848: 
1.507     raeburn  6849: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6850:   background-color: #EEEEEE;
1.451     albertel 6851: }
                   6852: 
1.473     raeburn  6853: table.LC_createuser {
                   6854: }
                   6855: 
                   6856: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6857:   font-size: small;
1.473     raeburn  6858: }
                   6859: 
                   6860: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6861:   background-color: #CCCCCC;
1.473     raeburn  6862:   font-weight: bold;
                   6863:   text-align: center;
                   6864: }
                   6865: 
1.349     albertel 6866: table.LC_calendar {
                   6867:   border: 1px solid #000000;
                   6868:   border-collapse: collapse;
1.917     raeburn  6869:   width: 98%;
1.349     albertel 6870: }
1.795     www      6871: 
1.349     albertel 6872: table.LC_calendar_pickdate {
                   6873:   font-size: xx-small;
                   6874: }
1.795     www      6875: 
1.349     albertel 6876: table.LC_calendar tr td {
                   6877:   border: 1px solid #000000;
                   6878:   vertical-align: top;
1.917     raeburn  6879:   width: 14%;
1.349     albertel 6880: }
1.795     www      6881: 
1.349     albertel 6882: table.LC_calendar tr td.LC_calendar_day_empty {
                   6883:   background-color: $data_table_dark;
                   6884: }
1.795     www      6885: 
1.779     bisitz   6886: table.LC_calendar tr td.LC_calendar_day_current {
                   6887:   background-color: $data_table_highlight;
1.777     tempelho 6888: }
1.795     www      6889: 
1.938     bisitz   6890: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6891:   background-color: $mail_new;
                   6892: }
1.795     www      6893: 
1.938     bisitz   6894: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6895:   background-color: $mail_new_hover;
                   6896: }
1.795     www      6897: 
1.938     bisitz   6898: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6899:   background-color: $mail_read;
                   6900: }
1.795     www      6901: 
1.938     bisitz   6902: /*
                   6903: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6904:   background-color: $mail_read_hover;
                   6905: }
1.938     bisitz   6906: */
1.795     www      6907: 
1.938     bisitz   6908: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6909:   background-color: $mail_replied;
                   6910: }
1.795     www      6911: 
1.938     bisitz   6912: /*
                   6913: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6914:   background-color: $mail_replied_hover;
                   6915: }
1.938     bisitz   6916: */
1.795     www      6917: 
1.938     bisitz   6918: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6919:   background-color: $mail_other;
                   6920: }
1.795     www      6921: 
1.938     bisitz   6922: /*
                   6923: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6924:   background-color: $mail_other_hover;
                   6925: }
1.938     bisitz   6926: */
1.494     raeburn  6927: 
1.777     tempelho 6928: table.LC_data_table tr > td.LC_browser_file,
                   6929: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6930:   background: #AAEE77;
1.389     albertel 6931: }
1.795     www      6932: 
1.777     tempelho 6933: table.LC_data_table tr > td.LC_browser_file_locked,
                   6934: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6935:   background: #FFAA99;
1.387     albertel 6936: }
1.795     www      6937: 
1.777     tempelho 6938: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6939:   background: #888888;
1.779     bisitz   6940: }
1.795     www      6941: 
1.777     tempelho 6942: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6943: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6944:   background: #F8F866;
1.777     tempelho 6945: }
1.795     www      6946: 
1.696     bisitz   6947: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6948:   background: #E0E8FF;
1.387     albertel 6949: }
1.696     bisitz   6950: 
1.707     bisitz   6951: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6952:   /* background: #77FF77; */
1.707     bisitz   6953: }
1.795     www      6954: 
1.707     bisitz   6955: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6956:   border-right: 8px solid #FFFF77;
1.707     bisitz   6957: }
1.795     www      6958: 
1.707     bisitz   6959: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6960:   border-right: 8px solid #FFAA77;
1.707     bisitz   6961: }
1.795     www      6962: 
1.707     bisitz   6963: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6964:   border-right: 8px solid #FF7777;
1.707     bisitz   6965: }
1.795     www      6966: 
1.707     bisitz   6967: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6968:   border-right: 8px solid #AAFF77;
1.707     bisitz   6969: }
1.795     www      6970: 
1.707     bisitz   6971: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6972:   border-right: 8px solid #11CC55;
1.707     bisitz   6973: }
                   6974: 
1.388     albertel 6975: span.LC_current_location {
1.701     harmsja  6976:   font-size:larger;
1.388     albertel 6977:   background: $pgbg;
                   6978: }
1.387     albertel 6979: 
1.1029    www      6980: span.LC_current_nav_location {
                   6981:   font-weight:bold;
                   6982:   background: $sidebg;
                   6983: }
                   6984: 
1.395     albertel 6985: span.LC_parm_menu_item {
                   6986:   font-size: larger;
                   6987: }
1.795     www      6988: 
1.395     albertel 6989: span.LC_parm_scope_all {
                   6990:   color: red;
                   6991: }
1.795     www      6992: 
1.395     albertel 6993: span.LC_parm_scope_folder {
                   6994:   color: green;
                   6995: }
1.795     www      6996: 
1.395     albertel 6997: span.LC_parm_scope_resource {
                   6998:   color: orange;
                   6999: }
1.795     www      7000: 
1.395     albertel 7001: span.LC_parm_part {
                   7002:   color: blue;
                   7003: }
1.795     www      7004: 
1.911     bisitz   7005: span.LC_parm_folder,
                   7006: span.LC_parm_symb {
1.395     albertel 7007:   font-size: x-small;
                   7008:   font-family: $mono;
                   7009:   color: #AAAAAA;
                   7010: }
                   7011: 
1.977     bisitz   7012: ul.LC_parm_parmlist li {
                   7013:   display: inline-block;
                   7014:   padding: 0.3em 0.8em;
                   7015:   vertical-align: top;
                   7016:   width: 150px;
                   7017:   border-top:1px solid $lg_border_color;
                   7018: }
                   7019: 
1.795     www      7020: td.LC_parm_overview_level_menu,
                   7021: td.LC_parm_overview_map_menu,
                   7022: td.LC_parm_overview_parm_selectors,
                   7023: td.LC_parm_overview_restrictions  {
1.396     albertel 7024:   border: 1px solid black;
                   7025:   border-collapse: collapse;
                   7026: }
1.795     www      7027: 
1.396     albertel 7028: table.LC_parm_overview_restrictions td {
                   7029:   border-width: 1px 4px 1px 4px;
                   7030:   border-style: solid;
                   7031:   border-color: $pgbg;
                   7032:   text-align: center;
                   7033: }
1.795     www      7034: 
1.396     albertel 7035: table.LC_parm_overview_restrictions th {
                   7036:   background: $tabbg;
                   7037:   border-width: 1px 4px 1px 4px;
                   7038:   border-style: solid;
                   7039:   border-color: $pgbg;
                   7040: }
1.795     www      7041: 
1.398     albertel 7042: table#LC_helpmenu {
1.803     bisitz   7043:   border: none;
1.398     albertel 7044:   height: 55px;
1.803     bisitz   7045:   border-spacing: 0;
1.398     albertel 7046: }
                   7047: 
                   7048: table#LC_helpmenu fieldset legend {
                   7049:   font-size: larger;
                   7050: }
1.795     www      7051: 
1.397     albertel 7052: table#LC_helpmenu_links {
                   7053:   width: 100%;
                   7054:   border: 1px solid black;
                   7055:   background: $pgbg;
1.803     bisitz   7056:   padding: 0;
1.397     albertel 7057:   border-spacing: 1px;
                   7058: }
1.795     www      7059: 
1.397     albertel 7060: table#LC_helpmenu_links tr td {
                   7061:   padding: 1px;
                   7062:   background: $tabbg;
1.399     albertel 7063:   text-align: center;
                   7064:   font-weight: bold;
1.397     albertel 7065: }
1.396     albertel 7066: 
1.795     www      7067: table#LC_helpmenu_links a:link,
                   7068: table#LC_helpmenu_links a:visited,
1.397     albertel 7069: table#LC_helpmenu_links a:active {
                   7070:   text-decoration: none;
                   7071:   color: $font;
                   7072: }
1.795     www      7073: 
1.397     albertel 7074: table#LC_helpmenu_links a:hover {
                   7075:   text-decoration: underline;
                   7076:   color: $vlink;
                   7077: }
1.396     albertel 7078: 
1.417     albertel 7079: .LC_chrt_popup_exists {
                   7080:   border: 1px solid #339933;
                   7081:   margin: -1px;
                   7082: }
1.795     www      7083: 
1.417     albertel 7084: .LC_chrt_popup_up {
                   7085:   border: 1px solid yellow;
                   7086:   margin: -1px;
                   7087: }
1.795     www      7088: 
1.417     albertel 7089: .LC_chrt_popup {
                   7090:   border: 1px solid #8888FF;
                   7091:   background: #CCCCFF;
                   7092: }
1.795     www      7093: 
1.421     albertel 7094: table.LC_pick_box {
                   7095:   border-collapse: separate;
                   7096:   background: white;
                   7097:   border: 1px solid black;
                   7098:   border-spacing: 1px;
                   7099: }
1.795     www      7100: 
1.421     albertel 7101: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7102:   background: $sidebg;
1.421     albertel 7103:   font-weight: bold;
1.900     bisitz   7104:   text-align: left;
1.740     bisitz   7105:   vertical-align: top;
1.421     albertel 7106:   width: 184px;
                   7107:   padding: 8px;
                   7108: }
1.795     www      7109: 
1.579     raeburn  7110: table.LC_pick_box td.LC_pick_box_value {
                   7111:   text-align: left;
                   7112:   padding: 8px;
                   7113: }
1.795     www      7114: 
1.579     raeburn  7115: table.LC_pick_box td.LC_pick_box_select {
                   7116:   text-align: left;
                   7117:   padding: 8px;
                   7118: }
1.795     www      7119: 
1.424     albertel 7120: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7121:   padding: 0;
1.421     albertel 7122:   height: 1px;
                   7123:   background: black;
                   7124: }
1.795     www      7125: 
1.421     albertel 7126: table.LC_pick_box td.LC_pick_box_submit {
                   7127:   text-align: right;
                   7128: }
1.795     www      7129: 
1.579     raeburn  7130: table.LC_pick_box td.LC_evenrow_value {
                   7131:   text-align: left;
                   7132:   padding: 8px;
                   7133:   background-color: $data_table_light;
                   7134: }
1.795     www      7135: 
1.579     raeburn  7136: table.LC_pick_box td.LC_oddrow_value {
                   7137:   text-align: left;
                   7138:   padding: 8px;
                   7139:   background-color: $data_table_light;
                   7140: }
1.795     www      7141: 
1.579     raeburn  7142: span.LC_helpform_receipt_cat {
                   7143:   font-weight: bold;
                   7144: }
1.795     www      7145: 
1.424     albertel 7146: table.LC_group_priv_box {
                   7147:   background: white;
                   7148:   border: 1px solid black;
                   7149:   border-spacing: 1px;
                   7150: }
1.795     www      7151: 
1.424     albertel 7152: table.LC_group_priv_box td.LC_pick_box_title {
                   7153:   background: $tabbg;
                   7154:   font-weight: bold;
                   7155:   text-align: right;
                   7156:   width: 184px;
                   7157: }
1.795     www      7158: 
1.424     albertel 7159: table.LC_group_priv_box td.LC_groups_fixed {
                   7160:   background: $data_table_light;
                   7161:   text-align: center;
                   7162: }
1.795     www      7163: 
1.424     albertel 7164: table.LC_group_priv_box td.LC_groups_optional {
                   7165:   background: $data_table_dark;
                   7166:   text-align: center;
                   7167: }
1.795     www      7168: 
1.424     albertel 7169: table.LC_group_priv_box td.LC_groups_functionality {
                   7170:   background: $data_table_darker;
                   7171:   text-align: center;
                   7172:   font-weight: bold;
                   7173: }
1.795     www      7174: 
1.424     albertel 7175: table.LC_group_priv td {
                   7176:   text-align: left;
1.803     bisitz   7177:   padding: 0;
1.424     albertel 7178: }
                   7179: 
                   7180: .LC_navbuttons {
                   7181:   margin: 2ex 0ex 2ex 0ex;
                   7182: }
1.795     www      7183: 
1.423     albertel 7184: .LC_topic_bar {
                   7185:   font-weight: bold;
                   7186:   background: $tabbg;
1.918     wenzelju 7187:   margin: 1em 0em 1em 2em;
1.805     bisitz   7188:   padding: 3px;
1.918     wenzelju 7189:   font-size: 1.2em;
1.423     albertel 7190: }
1.795     www      7191: 
1.423     albertel 7192: .LC_topic_bar span {
1.918     wenzelju 7193:   left: 0.5em;
                   7194:   position: absolute;
1.423     albertel 7195:   vertical-align: middle;
1.918     wenzelju 7196:   font-size: 1.2em;
1.423     albertel 7197: }
1.795     www      7198: 
1.423     albertel 7199: table.LC_course_group_status {
                   7200:   margin: 20px;
                   7201: }
1.795     www      7202: 
1.423     albertel 7203: table.LC_status_selector td {
                   7204:   vertical-align: top;
                   7205:   text-align: center;
1.424     albertel 7206:   padding: 4px;
                   7207: }
1.795     www      7208: 
1.599     albertel 7209: div.LC_feedback_link {
1.616     albertel 7210:   clear: both;
1.829     kalberla 7211:   background: $sidebg;
1.779     bisitz   7212:   width: 100%;
1.829     kalberla 7213:   padding-bottom: 10px;
                   7214:   border: 1px $tabbg solid;
1.833     kalberla 7215:   height: 22px;
                   7216:   line-height: 22px;
                   7217:   padding-top: 5px;
                   7218: }
                   7219: 
                   7220: div.LC_feedback_link img {
                   7221:   height: 22px;
1.867     kalberla 7222:   vertical-align:middle;
1.829     kalberla 7223: }
                   7224: 
1.911     bisitz   7225: div.LC_feedback_link a {
1.829     kalberla 7226:   text-decoration: none;
1.489     raeburn  7227: }
1.795     www      7228: 
1.867     kalberla 7229: div.LC_comblock {
1.911     bisitz   7230:   display:inline;
1.867     kalberla 7231:   color:$font;
                   7232:   font-size:90%;
                   7233: }
                   7234: 
                   7235: div.LC_feedback_link div.LC_comblock {
                   7236:   padding-left:5px;
                   7237: }
                   7238: 
                   7239: div.LC_feedback_link div.LC_comblock a {
                   7240:   color:$font;
                   7241: }
                   7242: 
1.489     raeburn  7243: span.LC_feedback_link {
1.858     bisitz   7244:   /* background: $feedback_link_bg; */
1.599     albertel 7245:   font-size: larger;
                   7246: }
1.795     www      7247: 
1.599     albertel 7248: span.LC_message_link {
1.858     bisitz   7249:   /* background: $feedback_link_bg; */
1.599     albertel 7250:   font-size: larger;
                   7251:   position: absolute;
                   7252:   right: 1em;
1.489     raeburn  7253: }
1.421     albertel 7254: 
1.515     albertel 7255: table.LC_prior_tries {
1.524     albertel 7256:   border: 1px solid #000000;
                   7257:   border-collapse: separate;
                   7258:   border-spacing: 1px;
1.515     albertel 7259: }
1.523     albertel 7260: 
1.515     albertel 7261: table.LC_prior_tries td {
1.524     albertel 7262:   padding: 2px;
1.515     albertel 7263: }
1.523     albertel 7264: 
                   7265: .LC_answer_correct {
1.795     www      7266:   background: lightgreen;
                   7267:   color: darkgreen;
                   7268:   padding: 6px;
1.523     albertel 7269: }
1.795     www      7270: 
1.523     albertel 7271: .LC_answer_charged_try {
1.797     www      7272:   background: #FFAAAA;
1.795     www      7273:   color: darkred;
                   7274:   padding: 6px;
1.523     albertel 7275: }
1.795     www      7276: 
1.779     bisitz   7277: .LC_answer_not_charged_try,
1.523     albertel 7278: .LC_answer_no_grade,
                   7279: .LC_answer_late {
1.795     www      7280:   background: lightyellow;
1.523     albertel 7281:   color: black;
1.795     www      7282:   padding: 6px;
1.523     albertel 7283: }
1.795     www      7284: 
1.523     albertel 7285: .LC_answer_previous {
1.795     www      7286:   background: lightblue;
                   7287:   color: darkblue;
                   7288:   padding: 6px;
1.523     albertel 7289: }
1.795     www      7290: 
1.779     bisitz   7291: .LC_answer_no_message {
1.777     tempelho 7292:   background: #FFFFFF;
                   7293:   color: black;
1.795     www      7294:   padding: 6px;
1.779     bisitz   7295: }
1.795     www      7296: 
1.1075.2.140  raeburn  7297: .LC_answer_unknown,
                   7298: .LC_answer_warning {
1.779     bisitz   7299:   background: orange;
                   7300:   color: black;
1.795     www      7301:   padding: 6px;
1.777     tempelho 7302: }
1.795     www      7303: 
1.529     albertel 7304: span.LC_prior_numerical,
                   7305: span.LC_prior_string,
                   7306: span.LC_prior_custom,
                   7307: span.LC_prior_reaction,
                   7308: span.LC_prior_math {
1.925     bisitz   7309:   font-family: $mono;
1.523     albertel 7310:   white-space: pre;
                   7311: }
                   7312: 
1.525     albertel 7313: span.LC_prior_string {
1.925     bisitz   7314:   font-family: $mono;
1.525     albertel 7315:   white-space: pre;
                   7316: }
                   7317: 
1.523     albertel 7318: table.LC_prior_option {
                   7319:   width: 100%;
                   7320:   border-collapse: collapse;
                   7321: }
1.795     www      7322: 
1.911     bisitz   7323: table.LC_prior_rank,
1.795     www      7324: table.LC_prior_match {
1.528     albertel 7325:   border-collapse: collapse;
                   7326: }
1.795     www      7327: 
1.528     albertel 7328: table.LC_prior_option tr td,
                   7329: table.LC_prior_rank tr td,
                   7330: table.LC_prior_match tr td {
1.524     albertel 7331:   border: 1px solid #000000;
1.515     albertel 7332: }
                   7333: 
1.855     bisitz   7334: .LC_nobreak {
1.544     albertel 7335:   white-space: nowrap;
1.519     raeburn  7336: }
                   7337: 
1.576     raeburn  7338: span.LC_cusr_emph {
                   7339:   font-style: italic;
                   7340: }
                   7341: 
1.633     raeburn  7342: span.LC_cusr_subheading {
                   7343:   font-weight: normal;
                   7344:   font-size: 85%;
                   7345: }
                   7346: 
1.861     bisitz   7347: div.LC_docs_entry_move {
1.859     bisitz   7348:   border: 1px solid #BBBBBB;
1.545     albertel 7349:   background: #DDDDDD;
1.861     bisitz   7350:   width: 22px;
1.859     bisitz   7351:   padding: 1px;
                   7352:   margin: 0;
1.545     albertel 7353: }
                   7354: 
1.861     bisitz   7355: table.LC_data_table tr > td.LC_docs_entry_commands,
                   7356: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 7357:   font-size: x-small;
                   7358: }
1.795     www      7359: 
1.861     bisitz   7360: .LC_docs_entry_parameter {
                   7361:   white-space: nowrap;
                   7362: }
                   7363: 
1.544     albertel 7364: .LC_docs_copy {
1.545     albertel 7365:   color: #000099;
1.544     albertel 7366: }
1.795     www      7367: 
1.544     albertel 7368: .LC_docs_cut {
1.545     albertel 7369:   color: #550044;
1.544     albertel 7370: }
1.795     www      7371: 
1.544     albertel 7372: .LC_docs_rename {
1.545     albertel 7373:   color: #009900;
1.544     albertel 7374: }
1.795     www      7375: 
1.544     albertel 7376: .LC_docs_remove {
1.545     albertel 7377:   color: #990000;
                   7378: }
                   7379: 
1.1075.2.134  raeburn  7380: .LC_domprefs_email,
1.547     albertel 7381: .LC_docs_reinit_warn,
                   7382: .LC_docs_ext_edit {
                   7383:   font-size: x-small;
                   7384: }
                   7385: 
1.545     albertel 7386: table.LC_docs_adddocs td,
                   7387: table.LC_docs_adddocs th {
                   7388:   border: 1px solid #BBBBBB;
                   7389:   padding: 4px;
                   7390:   background: #DDDDDD;
1.543     albertel 7391: }
                   7392: 
1.584     albertel 7393: table.LC_sty_begin {
                   7394:   background: #BBFFBB;
                   7395: }
1.795     www      7396: 
1.584     albertel 7397: table.LC_sty_end {
                   7398:   background: #FFBBBB;
                   7399: }
                   7400: 
1.589     raeburn  7401: table.LC_double_column {
1.803     bisitz   7402:   border-width: 0;
1.589     raeburn  7403:   border-collapse: collapse;
                   7404:   width: 100%;
                   7405:   padding: 2px;
                   7406: }
                   7407: 
                   7408: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  7409:   top: 2px;
1.589     raeburn  7410:   left: 2px;
                   7411:   width: 47%;
                   7412:   vertical-align: top;
                   7413: }
                   7414: 
                   7415: table.LC_double_column tr td.LC_right_col {
                   7416:   top: 2px;
1.779     bisitz   7417:   right: 2px;
1.589     raeburn  7418:   width: 47%;
                   7419:   vertical-align: top;
                   7420: }
                   7421: 
1.591     raeburn  7422: div.LC_left_float {
                   7423:   float: left;
                   7424:   padding-right: 5%;
1.597     albertel 7425:   padding-bottom: 4px;
1.591     raeburn  7426: }
                   7427: 
                   7428: div.LC_clear_float_header {
1.597     albertel 7429:   padding-bottom: 2px;
1.591     raeburn  7430: }
                   7431: 
                   7432: div.LC_clear_float_footer {
1.597     albertel 7433:   padding-top: 10px;
1.591     raeburn  7434:   clear: both;
                   7435: }
                   7436: 
1.597     albertel 7437: div.LC_grade_show_user {
1.941     bisitz   7438: /*  border-left: 5px solid $sidebg; */
                   7439:   border-top: 5px solid #000000;
                   7440:   margin: 50px 0 0 0;
1.936     bisitz   7441:   padding: 15px 0 5px 10px;
1.597     albertel 7442: }
1.795     www      7443: 
1.936     bisitz   7444: div.LC_grade_show_user_odd_row {
1.941     bisitz   7445: /*  border-left: 5px solid #000000; */
                   7446: }
                   7447: 
                   7448: div.LC_grade_show_user div.LC_Box {
                   7449:   margin-right: 50px;
1.597     albertel 7450: }
                   7451: 
                   7452: div.LC_grade_submissions,
                   7453: div.LC_grade_message_center,
1.936     bisitz   7454: div.LC_grade_info_links {
1.597     albertel 7455:   margin: 5px;
                   7456:   width: 99%;
                   7457:   background: #FFFFFF;
                   7458: }
1.795     www      7459: 
1.597     albertel 7460: div.LC_grade_submissions_header,
1.936     bisitz   7461: div.LC_grade_message_center_header {
1.705     tempelho 7462:   font-weight: bold;
                   7463:   font-size: large;
1.597     albertel 7464: }
1.795     www      7465: 
1.597     albertel 7466: div.LC_grade_submissions_body,
1.936     bisitz   7467: div.LC_grade_message_center_body {
1.597     albertel 7468:   border: 1px solid black;
                   7469:   width: 99%;
                   7470:   background: #FFFFFF;
                   7471: }
1.795     www      7472: 
1.613     albertel 7473: table.LC_scantron_action {
                   7474:   width: 100%;
                   7475: }
1.795     www      7476: 
1.613     albertel 7477: table.LC_scantron_action tr th {
1.698     harmsja  7478:   font-weight:bold;
                   7479:   font-style:normal;
1.613     albertel 7480: }
1.795     www      7481: 
1.779     bisitz   7482: .LC_edit_problem_header,
1.614     albertel 7483: div.LC_edit_problem_footer {
1.705     tempelho 7484:   font-weight: normal;
                   7485:   font-size:  medium;
1.602     albertel 7486:   margin: 2px;
1.1060    bisitz   7487:   background-color: $sidebg;
1.600     albertel 7488: }
1.795     www      7489: 
1.600     albertel 7490: div.LC_edit_problem_header,
1.602     albertel 7491: div.LC_edit_problem_header div,
1.614     albertel 7492: div.LC_edit_problem_footer,
                   7493: div.LC_edit_problem_footer div,
1.602     albertel 7494: div.LC_edit_problem_editxml_header,
                   7495: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  7496:   z-index: 100;
1.600     albertel 7497: }
1.795     www      7498: 
1.600     albertel 7499: div.LC_edit_problem_header_title {
1.705     tempelho 7500:   font-weight: bold;
                   7501:   font-size: larger;
1.602     albertel 7502:   background: $tabbg;
                   7503:   padding: 3px;
1.1060    bisitz   7504:   margin: 0 0 5px 0;
1.602     albertel 7505: }
1.795     www      7506: 
1.602     albertel 7507: table.LC_edit_problem_header_title {
                   7508:   width: 100%;
1.600     albertel 7509:   background: $tabbg;
1.602     albertel 7510: }
                   7511: 
1.1075.2.112  raeburn  7512: div.LC_edit_actionbar {
                   7513:     background-color: $sidebg;
                   7514:     margin: 0;
                   7515:     padding: 0;
                   7516:     line-height: 200%;
1.602     albertel 7517: }
1.795     www      7518: 
1.1075.2.112  raeburn  7519: div.LC_edit_actionbar div{
                   7520:     padding: 0;
                   7521:     margin: 0;
                   7522:     display: inline-block;
1.600     albertel 7523: }
1.795     www      7524: 
1.1075.2.34  raeburn  7525: .LC_edit_opt {
                   7526:   padding-left: 1em;
                   7527:   white-space: nowrap;
                   7528: }
                   7529: 
1.1075.2.57  raeburn  7530: .LC_edit_problem_latexhelper{
                   7531:     text-align: right;
                   7532: }
                   7533: 
                   7534: #LC_edit_problem_colorful div{
                   7535:     margin-left: 40px;
                   7536: }
                   7537: 
1.1075.2.112  raeburn  7538: #LC_edit_problem_codemirror div{
                   7539:     margin-left: 0px;
                   7540: }
                   7541: 
1.911     bisitz   7542: img.stift {
1.803     bisitz   7543:   border-width: 0;
                   7544:   vertical-align: middle;
1.677     riegler  7545: }
1.680     riegler  7546: 
1.923     bisitz   7547: table td.LC_mainmenu_col_fieldset {
1.680     riegler  7548:   vertical-align: top;
1.777     tempelho 7549: }
1.795     www      7550: 
1.716     raeburn  7551: div.LC_createcourse {
1.911     bisitz   7552:   margin: 10px 10px 10px 10px;
1.716     raeburn  7553: }
                   7554: 
1.917     raeburn  7555: .LC_dccid {
1.1075.2.38  raeburn  7556:   float: right;
1.917     raeburn  7557:   margin: 0.2em 0 0 0;
                   7558:   padding: 0;
                   7559:   font-size: 90%;
                   7560:   display:none;
                   7561: }
                   7562: 
1.897     wenzelju 7563: ol.LC_primary_menu a:hover,
1.721     harmsja  7564: ol#LC_MenuBreadcrumbs a:hover,
                   7565: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 7566: ul#LC_secondary_menu a:hover,
1.721     harmsja  7567: .LC_FormSectionClearButton input:hover
1.795     www      7568: ul.LC_TabContent   li:hover a {
1.952     onken    7569:   color:$button_hover;
1.911     bisitz   7570:   text-decoration:none;
1.693     droeschl 7571: }
                   7572: 
1.779     bisitz   7573: h1 {
1.911     bisitz   7574:   padding: 0;
                   7575:   line-height:130%;
1.693     droeschl 7576: }
1.698     harmsja  7577: 
1.911     bisitz   7578: h2,
                   7579: h3,
                   7580: h4,
                   7581: h5,
                   7582: h6 {
                   7583:   margin: 5px 0 5px 0;
                   7584:   padding: 0;
                   7585:   line-height:130%;
1.693     droeschl 7586: }
1.795     www      7587: 
                   7588: .LC_hcell {
1.911     bisitz   7589:   padding:3px 15px 3px 15px;
                   7590:   margin: 0;
                   7591:   background-color:$tabbg;
                   7592:   color:$fontmenu;
                   7593:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 7594: }
1.795     www      7595: 
1.840     bisitz   7596: .LC_Box > .LC_hcell {
1.911     bisitz   7597:   margin: 0 -10px 10px -10px;
1.835     bisitz   7598: }
                   7599: 
1.721     harmsja  7600: .LC_noBorder {
1.911     bisitz   7601:   border: 0;
1.698     harmsja  7602: }
1.693     droeschl 7603: 
1.721     harmsja  7604: .LC_FormSectionClearButton input {
1.911     bisitz   7605:   background-color:transparent;
                   7606:   border: none;
                   7607:   cursor:pointer;
                   7608:   text-decoration:underline;
1.693     droeschl 7609: }
1.763     bisitz   7610: 
                   7611: .LC_help_open_topic {
1.911     bisitz   7612:   color: #FFFFFF;
                   7613:   background-color: #EEEEFF;
                   7614:   margin: 1px;
                   7615:   padding: 4px;
                   7616:   border: 1px solid #000033;
                   7617:   white-space: nowrap;
                   7618:   /* vertical-align: middle; */
1.759     neumanie 7619: }
1.693     droeschl 7620: 
1.911     bisitz   7621: dl,
                   7622: ul,
                   7623: div,
                   7624: fieldset {
                   7625:   margin: 10px 10px 10px 0;
                   7626:   /* overflow: hidden; */
1.693     droeschl 7627: }
1.795     www      7628: 
1.1075.2.90  raeburn  7629: article.geogebraweb div {
                   7630:     margin: 0;
                   7631: }
                   7632: 
1.838     bisitz   7633: fieldset > legend {
1.911     bisitz   7634:   font-weight: bold;
                   7635:   padding: 0 5px 0 5px;
1.838     bisitz   7636: }
                   7637: 
1.813     bisitz   7638: #LC_nav_bar {
1.911     bisitz   7639:   float: left;
1.995     raeburn  7640:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7641:   margin: 0 0 2px 0;
1.807     droeschl 7642: }
                   7643: 
1.916     droeschl 7644: #LC_realm {
                   7645:   margin: 0.2em 0 0 0;
                   7646:   padding: 0;
                   7647:   font-weight: bold;
                   7648:   text-align: center;
1.995     raeburn  7649:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7650: }
                   7651: 
1.911     bisitz   7652: #LC_nav_bar em {
                   7653:   font-weight: bold;
                   7654:   font-style: normal;
1.807     droeschl 7655: }
                   7656: 
1.897     wenzelju 7657: ol.LC_primary_menu {
1.934     droeschl 7658:   margin: 0;
1.1075.2.2  raeburn  7659:   padding: 0;
1.807     droeschl 7660: }
                   7661: 
1.852     droeschl 7662: ol#LC_PathBreadcrumbs {
1.911     bisitz   7663:   margin: 0;
1.693     droeschl 7664: }
                   7665: 
1.897     wenzelju 7666: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7667:   color: RGB(80, 80, 80);
                   7668:   vertical-align: middle;
                   7669:   text-align: left;
                   7670:   list-style: none;
1.1075.2.112  raeburn  7671:   position: relative;
1.1075.2.2  raeburn  7672:   float: left;
1.1075.2.112  raeburn  7673:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7674:   line-height: 1.5em;
1.1075.2.2  raeburn  7675: }
                   7676: 
1.1075.2.113  raeburn  7677: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7678: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7679:   display: block;
                   7680:   margin: 0;
                   7681:   padding: 0 5px 0 10px;
                   7682:   text-decoration: none;
                   7683: }
                   7684: 
1.1075.2.112  raeburn  7685: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7686:   display: inline-block;
                   7687:   width: 95%;
                   7688:   text-align: left;
                   7689: }
                   7690: 
                   7691: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7692:   display: inline-block;
                   7693:   width: 5%;
                   7694:   float: right;
                   7695:   text-align: right;
                   7696:   font-size: 70%;
                   7697: }
                   7698: 
                   7699: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7700:   display: none;
1.1075.2.112  raeburn  7701:   width: 15em;
1.1075.2.2  raeburn  7702:   background-color: $data_table_light;
1.1075.2.112  raeburn  7703:   position: absolute;
                   7704:   top: 100%;
                   7705: }
                   7706: 
                   7707: ol.LC_primary_menu ul ul {
                   7708:   left: 100%;
                   7709:   top: 0;
1.1075.2.2  raeburn  7710: }
                   7711: 
1.1075.2.112  raeburn  7712: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7713:   display: block;
                   7714:   position: absolute;
                   7715:   margin: 0;
                   7716:   padding: 0;
1.1075.2.5  raeburn  7717:   z-index: 2;
1.1075.2.2  raeburn  7718: }
                   7719: 
                   7720: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7721: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7722:   font-size: 90%;
1.911     bisitz   7723:   vertical-align: top;
1.1075.2.2  raeburn  7724:   float: none;
1.1075.2.5  raeburn  7725:   border-left: 1px solid black;
                   7726:   border-right: 1px solid black;
1.1075.2.112  raeburn  7727: /* A dark bottom border to visualize different menu options;
                   7728: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7729:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7730: }
                   7731: 
1.1075.2.112  raeburn  7732: ol.LC_primary_menu li li p:hover {
                   7733:   color:$button_hover;
                   7734:   text-decoration:none;
                   7735:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7736: }
                   7737: 
                   7738: ol.LC_primary_menu li li a:hover {
                   7739:    color:$button_hover;
                   7740:    background-color:$data_table_dark;
1.693     droeschl 7741: }
                   7742: 
1.1075.2.112  raeburn  7743: /* Font-size equal to the size of the predecessors*/
                   7744: ol.LC_primary_menu li:hover li li {
                   7745:   font-size: 100%;
                   7746: }
                   7747: 
1.897     wenzelju 7748: ol.LC_primary_menu li img {
1.911     bisitz   7749:   vertical-align: bottom;
1.934     droeschl 7750:   height: 1.1em;
1.1075.2.3  raeburn  7751:   margin: 0.2em 0 0 0;
1.693     droeschl 7752: }
                   7753: 
1.897     wenzelju 7754: ol.LC_primary_menu a {
1.911     bisitz   7755:   color: RGB(80, 80, 80);
                   7756:   text-decoration: none;
1.693     droeschl 7757: }
1.795     www      7758: 
1.949     droeschl 7759: ol.LC_primary_menu a.LC_new_message {
                   7760:   font-weight:bold;
                   7761:   color: darkred;
                   7762: }
                   7763: 
1.975     raeburn  7764: ol.LC_docs_parameters {
                   7765:   margin-left: 0;
                   7766:   padding: 0;
                   7767:   list-style: none;
                   7768: }
                   7769: 
                   7770: ol.LC_docs_parameters li {
                   7771:   margin: 0;
                   7772:   padding-right: 20px;
                   7773:   display: inline;
                   7774: }
                   7775: 
1.976     raeburn  7776: ol.LC_docs_parameters li:before {
                   7777:   content: "\\002022 \\0020";
                   7778: }
                   7779: 
                   7780: li.LC_docs_parameters_title {
                   7781:   font-weight: bold;
                   7782: }
                   7783: 
                   7784: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7785:   content: "";
                   7786: }
                   7787: 
1.897     wenzelju 7788: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7789:   clear: right;
1.911     bisitz   7790:   color: $fontmenu;
                   7791:   background: $tabbg;
                   7792:   list-style: none;
                   7793:   padding: 0;
                   7794:   margin: 0;
                   7795:   width: 100%;
1.995     raeburn  7796:   text-align: left;
1.1075.2.4  raeburn  7797:   float: left;
1.808     droeschl 7798: }
                   7799: 
1.897     wenzelju 7800: ul#LC_secondary_menu li {
1.911     bisitz   7801:   font-weight: bold;
                   7802:   line-height: 1.8em;
                   7803:   border-right: 1px solid black;
1.1075.2.4  raeburn  7804:   float: left;
                   7805: }
                   7806: 
                   7807: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7808:   background-color: $data_table_light;
                   7809: }
                   7810: 
                   7811: ul#LC_secondary_menu li a {
                   7812:   padding: 0 0.8em;
                   7813: }
                   7814: 
                   7815: ul#LC_secondary_menu li ul {
                   7816:   display: none;
                   7817: }
                   7818: 
                   7819: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7820:   display: block;
                   7821:   position: absolute;
                   7822:   margin: 0;
                   7823:   padding: 0;
                   7824:   list-style:none;
                   7825:   float: none;
                   7826:   background-color: $data_table_light;
1.1075.2.5  raeburn  7827:   z-index: 2;
1.1075.2.10  raeburn  7828:   margin-left: -1px;
1.1075.2.4  raeburn  7829: }
                   7830: 
                   7831: ul#LC_secondary_menu li ul li {
                   7832:   font-size: 90%;
                   7833:   vertical-align: top;
                   7834:   border-left: 1px solid black;
                   7835:   border-right: 1px solid black;
1.1075.2.33  raeburn  7836:   background-color: $data_table_light;
1.1075.2.4  raeburn  7837:   list-style:none;
                   7838:   float: none;
                   7839: }
                   7840: 
                   7841: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7842:   background-color: $data_table_dark;
1.807     droeschl 7843: }
                   7844: 
1.847     tempelho 7845: ul.LC_TabContent {
1.911     bisitz   7846:   display:block;
                   7847:   background: $sidebg;
                   7848:   border-bottom: solid 1px $lg_border_color;
                   7849:   list-style:none;
1.1020    raeburn  7850:   margin: -1px -10px 0 -10px;
1.911     bisitz   7851:   padding: 0;
1.693     droeschl 7852: }
                   7853: 
1.795     www      7854: ul.LC_TabContent li,
                   7855: ul.LC_TabContentBigger li {
1.911     bisitz   7856:   float:left;
1.741     harmsja  7857: }
1.795     www      7858: 
1.897     wenzelju 7859: ul#LC_secondary_menu li a {
1.911     bisitz   7860:   color: $fontmenu;
                   7861:   text-decoration: none;
1.693     droeschl 7862: }
1.795     www      7863: 
1.721     harmsja  7864: ul.LC_TabContent {
1.952     onken    7865:   min-height:20px;
1.721     harmsja  7866: }
1.795     www      7867: 
                   7868: ul.LC_TabContent li {
1.911     bisitz   7869:   vertical-align:middle;
1.959     onken    7870:   padding: 0 16px 0 10px;
1.911     bisitz   7871:   background-color:$tabbg;
                   7872:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7873:   border-left: solid 1px $font;
1.721     harmsja  7874: }
1.795     www      7875: 
1.847     tempelho 7876: ul.LC_TabContent .right {
1.911     bisitz   7877:   float:right;
1.847     tempelho 7878: }
                   7879: 
1.911     bisitz   7880: ul.LC_TabContent li a,
                   7881: ul.LC_TabContent li {
                   7882:   color:rgb(47,47,47);
                   7883:   text-decoration:none;
                   7884:   font-size:95%;
                   7885:   font-weight:bold;
1.952     onken    7886:   min-height:20px;
                   7887: }
                   7888: 
1.959     onken    7889: ul.LC_TabContent li a:hover,
                   7890: ul.LC_TabContent li a:focus {
1.952     onken    7891:   color: $button_hover;
1.959     onken    7892:   background:none;
                   7893:   outline:none;
1.952     onken    7894: }
                   7895: 
                   7896: ul.LC_TabContent li:hover {
                   7897:   color: $button_hover;
                   7898:   cursor:pointer;
1.721     harmsja  7899: }
1.795     www      7900: 
1.911     bisitz   7901: ul.LC_TabContent li.active {
1.952     onken    7902:   color: $font;
1.911     bisitz   7903:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7904:   border-bottom:solid 1px #FFFFFF;
                   7905:   cursor: default;
1.744     ehlerst  7906: }
1.795     www      7907: 
1.959     onken    7908: ul.LC_TabContent li.active a {
                   7909:   color:$font;
                   7910:   background:#FFFFFF;
                   7911:   outline: none;
                   7912: }
1.1047    raeburn  7913: 
                   7914: ul.LC_TabContent li.goback {
                   7915:   float: left;
                   7916:   border-left: none;
                   7917: }
                   7918: 
1.870     tempelho 7919: #maincoursedoc {
1.911     bisitz   7920:   clear:both;
1.870     tempelho 7921: }
                   7922: 
                   7923: ul.LC_TabContentBigger {
1.911     bisitz   7924:   display:block;
                   7925:   list-style:none;
                   7926:   padding: 0;
1.870     tempelho 7927: }
                   7928: 
1.795     www      7929: ul.LC_TabContentBigger li {
1.911     bisitz   7930:   vertical-align:bottom;
                   7931:   height: 30px;
                   7932:   font-size:110%;
                   7933:   font-weight:bold;
                   7934:   color: #737373;
1.841     tempelho 7935: }
                   7936: 
1.957     onken    7937: ul.LC_TabContentBigger li.active {
                   7938:   position: relative;
                   7939:   top: 1px;
                   7940: }
                   7941: 
1.870     tempelho 7942: ul.LC_TabContentBigger li a {
1.911     bisitz   7943:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7944:   height: 30px;
                   7945:   line-height: 30px;
                   7946:   text-align: center;
                   7947:   display: block;
                   7948:   text-decoration: none;
1.958     onken    7949:   outline: none;  
1.741     harmsja  7950: }
1.795     www      7951: 
1.870     tempelho 7952: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7953:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7954:   color:$font;
1.744     ehlerst  7955: }
1.795     www      7956: 
1.870     tempelho 7957: ul.LC_TabContentBigger li b {
1.911     bisitz   7958:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7959:   display: block;
                   7960:   float: left;
                   7961:   padding: 0 30px;
1.957     onken    7962:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7963: }
                   7964: 
1.956     onken    7965: ul.LC_TabContentBigger li:hover b {
                   7966:   color:$button_hover;
                   7967: }
                   7968: 
1.870     tempelho 7969: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7970:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7971:   color:$font;
1.957     onken    7972:   border: 0;
1.741     harmsja  7973: }
1.693     droeschl 7974: 
1.870     tempelho 7975: 
1.862     bisitz   7976: ul.LC_CourseBreadcrumbs {
                   7977:   background: $sidebg;
1.1020    raeburn  7978:   height: 2em;
1.862     bisitz   7979:   padding-left: 10px;
1.1020    raeburn  7980:   margin: 0;
1.862     bisitz   7981:   list-style-position: inside;
                   7982: }
                   7983: 
1.911     bisitz   7984: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7985: ol#LC_PathBreadcrumbs {
1.911     bisitz   7986:   padding-left: 10px;
                   7987:   margin: 0;
1.933     droeschl 7988:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7989: }
                   7990: 
1.911     bisitz   7991: ol#LC_MenuBreadcrumbs li,
                   7992: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7993: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7994:   display: inline;
1.933     droeschl 7995:   white-space: normal;  
1.693     droeschl 7996: }
                   7997: 
1.823     bisitz   7998: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7999: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8000:   text-decoration: none;
                   8001:   font-size:90%;
1.693     droeschl 8002: }
1.795     www      8003: 
1.969     droeschl 8004: ol#LC_MenuBreadcrumbs h1 {
                   8005:   display: inline;
                   8006:   font-size: 90%;
                   8007:   line-height: 2.5em;
                   8008:   margin: 0;
                   8009:   padding: 0;
                   8010: }
                   8011: 
1.795     www      8012: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8013:   text-decoration:none;
                   8014:   font-size:100%;
                   8015:   font-weight:bold;
1.693     droeschl 8016: }
1.795     www      8017: 
1.840     bisitz   8018: .LC_Box {
1.911     bisitz   8019:   border: solid 1px $lg_border_color;
                   8020:   padding: 0 10px 10px 10px;
1.746     neumanie 8021: }
1.795     www      8022: 
1.1020    raeburn  8023: .LC_DocsBox {
                   8024:   border: solid 1px $lg_border_color;
                   8025:   padding: 0 0 10px 10px;
                   8026: }
                   8027: 
1.795     www      8028: .LC_AboutMe_Image {
1.911     bisitz   8029:   float:left;
                   8030:   margin-right:10px;
1.747     neumanie 8031: }
1.795     www      8032: 
                   8033: .LC_Clear_AboutMe_Image {
1.911     bisitz   8034:   clear:left;
1.747     neumanie 8035: }
1.795     www      8036: 
1.721     harmsja  8037: dl.LC_ListStyleClean dt {
1.911     bisitz   8038:   padding-right: 5px;
                   8039:   display: table-header-group;
1.693     droeschl 8040: }
                   8041: 
1.721     harmsja  8042: dl.LC_ListStyleClean dd {
1.911     bisitz   8043:   display: table-row;
1.693     droeschl 8044: }
                   8045: 
1.721     harmsja  8046: .LC_ListStyleClean,
                   8047: .LC_ListStyleSimple,
                   8048: .LC_ListStyleNormal,
1.795     www      8049: .LC_ListStyleSpecial {
1.911     bisitz   8050:   /* display:block; */
                   8051:   list-style-position: inside;
                   8052:   list-style-type: none;
                   8053:   overflow: hidden;
                   8054:   padding: 0;
1.693     droeschl 8055: }
                   8056: 
1.721     harmsja  8057: .LC_ListStyleSimple li,
                   8058: .LC_ListStyleSimple dd,
                   8059: .LC_ListStyleNormal li,
                   8060: .LC_ListStyleNormal dd,
                   8061: .LC_ListStyleSpecial li,
1.795     www      8062: .LC_ListStyleSpecial dd {
1.911     bisitz   8063:   margin: 0;
                   8064:   padding: 5px 5px 5px 10px;
                   8065:   clear: both;
1.693     droeschl 8066: }
                   8067: 
1.721     harmsja  8068: .LC_ListStyleClean li,
                   8069: .LC_ListStyleClean dd {
1.911     bisitz   8070:   padding-top: 0;
                   8071:   padding-bottom: 0;
1.693     droeschl 8072: }
                   8073: 
1.721     harmsja  8074: .LC_ListStyleSimple dd,
1.795     www      8075: .LC_ListStyleSimple li {
1.911     bisitz   8076:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8077: }
                   8078: 
1.721     harmsja  8079: .LC_ListStyleSpecial li,
                   8080: .LC_ListStyleSpecial dd {
1.911     bisitz   8081:   list-style-type: none;
                   8082:   background-color: RGB(220, 220, 220);
                   8083:   margin-bottom: 4px;
1.693     droeschl 8084: }
                   8085: 
1.721     harmsja  8086: table.LC_SimpleTable {
1.911     bisitz   8087:   margin:5px;
                   8088:   border:solid 1px $lg_border_color;
1.795     www      8089: }
1.693     droeschl 8090: 
1.721     harmsja  8091: table.LC_SimpleTable tr {
1.911     bisitz   8092:   padding: 0;
                   8093:   border:solid 1px $lg_border_color;
1.693     droeschl 8094: }
1.795     www      8095: 
                   8096: table.LC_SimpleTable thead {
1.911     bisitz   8097:   background:rgb(220,220,220);
1.693     droeschl 8098: }
                   8099: 
1.721     harmsja  8100: div.LC_columnSection {
1.911     bisitz   8101:   display: block;
                   8102:   clear: both;
                   8103:   overflow: hidden;
                   8104:   margin: 0;
1.693     droeschl 8105: }
                   8106: 
1.721     harmsja  8107: div.LC_columnSection>* {
1.911     bisitz   8108:   float: left;
                   8109:   margin: 10px 20px 10px 0;
                   8110:   overflow:hidden;
1.693     droeschl 8111: }
1.721     harmsja  8112: 
1.795     www      8113: table em {
1.911     bisitz   8114:   font-weight: bold;
                   8115:   font-style: normal;
1.748     schulted 8116: }
1.795     www      8117: 
1.779     bisitz   8118: table.LC_tableBrowseRes,
1.795     www      8119: table.LC_tableOfContent {
1.911     bisitz   8120:   border:none;
                   8121:   border-spacing: 1px;
                   8122:   padding: 3px;
                   8123:   background-color: #FFFFFF;
                   8124:   font-size: 90%;
1.753     droeschl 8125: }
1.789     droeschl 8126: 
1.911     bisitz   8127: table.LC_tableOfContent {
                   8128:   border-collapse: collapse;
1.789     droeschl 8129: }
                   8130: 
1.771     droeschl 8131: table.LC_tableBrowseRes a,
1.768     schulted 8132: table.LC_tableOfContent a {
1.911     bisitz   8133:   background-color: transparent;
                   8134:   text-decoration: none;
1.753     droeschl 8135: }
                   8136: 
1.795     www      8137: table.LC_tableOfContent img {
1.911     bisitz   8138:   border: none;
                   8139:   height: 1.3em;
                   8140:   vertical-align: text-bottom;
                   8141:   margin-right: 0.3em;
1.753     droeschl 8142: }
1.757     schulted 8143: 
1.795     www      8144: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8145:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8146: }
                   8147: 
1.795     www      8148: a#LC_content_toolbar_everything {
1.911     bisitz   8149:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8150: }
                   8151: 
1.795     www      8152: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8153:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8154: }
                   8155: 
1.795     www      8156: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8157:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8158: }
                   8159: 
1.795     www      8160: a#LC_content_toolbar_changefolder {
1.911     bisitz   8161:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8162: }
                   8163: 
1.795     www      8164: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8165:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8166: }
                   8167: 
1.1043    raeburn  8168: a#LC_content_toolbar_edittoplevel {
                   8169:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8170: }
                   8171: 
1.1075.2.161.  .12(raeb 8172:-23): a#LC_content_toolbar_printout {
                   8173:-23):   background-image:url(/res/adm/pages/printout.gif);
                   8174:-23): }
                   8175:-23): 
1.795     www      8176: ul#LC_toolbar li a:hover {
1.911     bisitz   8177:   background-position: bottom center;
1.757     schulted 8178: }
                   8179: 
1.795     www      8180: ul#LC_toolbar {
1.911     bisitz   8181:   padding: 0;
                   8182:   margin: 2px;
                   8183:   list-style:none;
                   8184:   position:relative;
                   8185:   background-color:white;
1.1075.2.9  raeburn  8186:   overflow: auto;
1.757     schulted 8187: }
                   8188: 
1.795     www      8189: ul#LC_toolbar li {
1.911     bisitz   8190:   border:1px solid white;
                   8191:   padding: 0;
                   8192:   margin: 0;
                   8193:   float: left;
                   8194:   display:inline;
                   8195:   vertical-align:middle;
1.1075.2.9  raeburn  8196:   white-space: nowrap;
1.911     bisitz   8197: }
1.757     schulted 8198: 
1.783     amueller 8199: 
1.795     www      8200: a.LC_toolbarItem {
1.911     bisitz   8201:   display:block;
                   8202:   padding: 0;
                   8203:   margin: 0;
                   8204:   height: 32px;
                   8205:   width: 32px;
                   8206:   color:white;
                   8207:   border: none;
                   8208:   background-repeat:no-repeat;
                   8209:   background-color:transparent;
1.757     schulted 8210: }
                   8211: 
1.915     droeschl 8212: ul.LC_funclist {
                   8213:     margin: 0;
                   8214:     padding: 0.5em 1em 0.5em 0;
                   8215: }
                   8216: 
1.933     droeschl 8217: ul.LC_funclist > li:first-child {
                   8218:     font-weight:bold; 
                   8219:     margin-left:0.8em;
                   8220: }
                   8221: 
1.915     droeschl 8222: ul.LC_funclist + ul.LC_funclist {
                   8223:     /* 
                   8224:        left border as a seperator if we have more than
                   8225:        one list 
                   8226:     */
                   8227:     border-left: 1px solid $sidebg;
                   8228:     /* 
                   8229:        this hides the left border behind the border of the 
                   8230:        outer box if element is wrapped to the next 'line' 
                   8231:     */
                   8232:     margin-left: -1px;
                   8233: }
                   8234: 
1.843     bisitz   8235: ul.LC_funclist li {
1.915     droeschl 8236:   display: inline;
1.782     bisitz   8237:   white-space: nowrap;
1.915     droeschl 8238:   margin: 0 0 0 25px;
                   8239:   line-height: 150%;
1.782     bisitz   8240: }
                   8241: 
1.974     wenzelju 8242: .LC_hidden {
                   8243:   display: none;
                   8244: }
                   8245: 
1.1030    www      8246: .LCmodal-overlay {
                   8247: 		position:fixed;
                   8248: 		top:0;
                   8249: 		right:0;
                   8250: 		bottom:0;
                   8251: 		left:0;
                   8252: 		height:100%;
                   8253: 		width:100%;
                   8254: 		margin:0;
                   8255: 		padding:0;
                   8256: 		background:#999;
                   8257: 		opacity:.75;
                   8258: 		filter: alpha(opacity=75);
                   8259: 		-moz-opacity: 0.75;
                   8260: 		z-index:101;
                   8261: }
                   8262: 
                   8263: * html .LCmodal-overlay {   
                   8264: 		position: absolute;
                   8265: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   8266: }
                   8267: 
                   8268: .LCmodal-window {
                   8269: 		position:fixed;
                   8270: 		top:50%;
                   8271: 		left:50%;
                   8272: 		margin:0;
                   8273: 		padding:0;
                   8274: 		z-index:102;
                   8275: 	}
                   8276: 
                   8277: * html .LCmodal-window {
                   8278: 		position:absolute;
                   8279: }
                   8280: 
                   8281: .LCclose-window {
                   8282: 		position:absolute;
                   8283: 		width:32px;
                   8284: 		height:32px;
                   8285: 		right:8px;
                   8286: 		top:8px;
                   8287: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   8288: 		text-indent:-99999px;
                   8289: 		overflow:hidden;
                   8290: 		cursor:pointer;
                   8291: }
                   8292: 
1.1075.2.158  raeburn  8293: .LCisDisabled {
                   8294:   cursor: not-allowed;
                   8295:   opacity: 0.5;
                   8296: }
                   8297: 
                   8298: a[aria-disabled="true"] {
                   8299:   color: currentColor;
                   8300:   display: inline-block;  /* For IE11/ MS Edge bug */
                   8301:   pointer-events: none;
                   8302:   text-decoration: none;
                   8303: }
                   8304: 
1.1075.2.141  raeburn  8305: pre.LC_wordwrap {
                   8306:   white-space: pre-wrap;
                   8307:   white-space: -moz-pre-wrap;
                   8308:   white-space: -pre-wrap;
                   8309:   white-space: -o-pre-wrap;
                   8310:   word-wrap: break-word;
                   8311: }
                   8312: 
1.1075.2.17  raeburn  8313: /*
                   8314:   styles used by TTH when "Default set of options to pass to tth/m
                   8315:   when converting TeX" in course settings has been set
                   8316: 
                   8317:   option passed: -t
                   8318: 
                   8319: */
                   8320: 
                   8321: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   8322: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   8323: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   8324: td div.norm {line-height:normal;}
                   8325: 
                   8326: /*
                   8327:   option passed -y3
                   8328: */
                   8329: 
                   8330: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   8331: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   8332: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   8333: 
1.1075.2.121  raeburn  8334: #LC_minitab_header {
                   8335:   float:left;
                   8336:   width:100%;
                   8337:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   8338:   font-size:93%;
                   8339:   line-height:normal;
                   8340:   margin: 0.5em 0 0.5em 0;
                   8341: }
                   8342: #LC_minitab_header ul {
                   8343:   margin:0;
                   8344:   padding:10px 10px 0;
                   8345:   list-style:none;
                   8346: }
                   8347: #LC_minitab_header li {
                   8348:   float:left;
                   8349:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   8350:   margin:0;
                   8351:   padding:0 0 0 9px;
                   8352: }
                   8353: #LC_minitab_header a {
                   8354:   display:block;
                   8355:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   8356:   padding:5px 15px 4px 6px;
                   8357: }
                   8358: #LC_minitab_header #LC_current_minitab {
                   8359:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   8360: }
                   8361: #LC_minitab_header #LC_current_minitab a {
                   8362:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   8363:   padding-bottom:5px;
                   8364: }
                   8365: 
                   8366: 
1.343     albertel 8367: END
                   8368: }
                   8369: 
1.306     albertel 8370: =pod
                   8371: 
                   8372: =item * &headtag()
                   8373: 
                   8374: Returns a uniform footer for LON-CAPA web pages.
                   8375: 
1.307     albertel 8376: Inputs: $title - optional title for the head
                   8377:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 8378:         $args - optional arguments
1.319     albertel 8379:             force_register - if is true call registerurl so the remote is 
                   8380:                              informed
1.415     albertel 8381:             redirect       -> array ref of
                   8382:                                    1- seconds before redirect occurs
                   8383:                                    2- url to redirect to
                   8384:                                    3- whether the side effect should occur
1.315     albertel 8385:                            (side effect of setting 
                   8386:                                $env{'internal.head.redirect'} to the url 
1.1075.2.161.  .9(raebu 8387:22):                                redirected to)
                   8388:22):                                    4- whether the redirect target should be
                   8389:22):                                       the opener of the current (pop-up)
                   8390:22):                                       window (side effect of setting
                   8391:22):                                       $env{'internal.head.to_opener'} to
                   8392:22):                                       1, if true.
          .10(raeb 8393:-22):                                    5- whether encrypt check should be skipped
1.352     albertel 8394:             domain         -> force to color decorate a page for a specific
                   8395:                                domain
                   8396:             function       -> force usage of a specific rolish color scheme
                   8397:             bgcolor        -> override the default page bgcolor
1.460     albertel 8398:             no_auto_mt_title
                   8399:                            -> prevent &mt()ing the title arg
1.464     albertel 8400: 
1.306     albertel 8401: =cut
                   8402: 
                   8403: sub headtag {
1.313     albertel 8404:     my ($title,$head_extra,$args) = @_;
1.306     albertel 8405:     
1.363     albertel 8406:     my $function = $args->{'function'} || &get_users_function();
                   8407:     my $domain   = $args->{'domain'}   || &determinedomain();
                   8408:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  8409:     my $httphost = $args->{'use_absolute'};
1.418     albertel 8410:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 8411: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 8412: 		   #time(),
1.418     albertel 8413: 		   $env{'environment.color.timestamp'},
1.363     albertel 8414: 		   $function,$domain,$bgcolor);
                   8415: 
1.369     www      8416:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 8417: 
1.308     albertel 8418:     my $result =
                   8419: 	'<head>'.
1.1075.2.56  raeburn  8420: 	&font_settings($args);
1.319     albertel 8421: 
1.1075.2.72  raeburn  8422:     my $inhibitprint;
                   8423:     if ($args->{'print_suppress'}) {
                   8424:         $inhibitprint = &print_suppression();
                   8425:     }
1.1064    raeburn  8426: 
1.461     albertel 8427:     if (!$args->{'frameset'}) {
                   8428: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   8429:     }
1.1075.2.12  raeburn  8430:     if ($args->{'force_register'}) {
                   8431:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 8432:     }
1.436     albertel 8433:     if (!$args->{'no_nav_bar'} 
                   8434: 	&& !$args->{'only_body'}
                   8435: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  8436: 	$result .= &help_menu_js($httphost);
1.1032    www      8437:         $result.=&modal_window();
1.1038    www      8438:         $result.=&togglebox_script();
1.1034    www      8439:         $result.=&wishlist_window();
1.1041    www      8440:         $result.=&LCprogressbarUpdate_script();
1.1034    www      8441:     } else {
                   8442:         if ($args->{'add_modal'}) {
                   8443:            $result.=&modal_window();
                   8444:         }
                   8445:         if ($args->{'add_wishlist'}) {
                   8446:            $result.=&wishlist_window();
                   8447:         }
1.1038    www      8448:         if ($args->{'add_togglebox'}) {
                   8449:            $result.=&togglebox_script();
                   8450:         }
1.1041    www      8451:         if ($args->{'add_progressbar'}) {
                   8452:            $result.=&LCprogressbarUpdate_script();
                   8453:         }
1.436     albertel 8454:     }
1.314     albertel 8455:     if (ref($args->{'redirect'})) {
1.1075.2.161.  .10(raeb 8456:-22): 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   8457:-22):         if (!$skip_enc_check) {
                   8458:-22): 	    $url = &Apache::lonenc::check_encrypt($url);
                   8459:-22):         }
1.414     albertel 8460: 	if (!$inhibit_continue) {
                   8461: 	    $env{'internal.head.redirect'} = $url;
                   8462: 	}
1.1075.2.161.  .9(raebu 8463:22):         $result.=<<"ADDMETA";
1.313     albertel 8464: <meta http-equiv="pragma" content="no-cache" />
1.1075.2.161.  .9(raebu 8465:22): ADDMETA
                   8466:22):         if ($to_opener) {
                   8467:22):             $env{'internal.head.to_opener'} = 1;
                   8468:22):             my $dest = &js_escape($url);
                   8469:22):             my $timeout = int($time * 1000);
                   8470:22):             $result .=<<"ENDJS";
                   8471:22): <script type="text/javascript">
                   8472:22): // <![CDATA[
                   8473:22): function LC_To_Opener() {
                   8474:22):     var dest = '$dest';
                   8475:22):     if (dest != '') {
                   8476:22):         if (window.opener != null && !window.opener.closed) {
                   8477:22):             window.opener.location.href=dest;
                   8478:22):             window.close();
                   8479:22):         } else {
                   8480:22):             window.location.href=dest;
                   8481:22):         }
                   8482:22):     }
                   8483:22): }
                   8484:22): \$(document).ready(function () {
                   8485:22):     setTimeout('LC_To_Opener()',$timeout);
                   8486:22): });
                   8487:22): // ]]>
                   8488:22): </script>
                   8489:22): ENDJS
                   8490:22):         } else {
                   8491:22):             $result.=<<"ADDMETA";
1.344     albertel 8492: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 8493: ADDMETA
1.1075.2.161.  .9(raebu 8494:22):         }
1.1075.2.89  raeburn  8495:     } else {
                   8496:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   8497:             my $requrl = $env{'request.uri'};
                   8498:             if ($requrl eq '') {
                   8499:                 $requrl = $ENV{'REQUEST_URI'};
                   8500:                 $requrl =~ s/\?.+$//;
                   8501:             }
                   8502:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   8503:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   8504:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   8505:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   8506:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   8507:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1075.2.145  raeburn  8508:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1075.2.151  raeburn  8509:                     my ($offload,$offloadoth);
1.1075.2.89  raeburn  8510:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   8511:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1075.2.145  raeburn  8512:                             $offload = 1;
1.1075.2.151  raeburn  8513:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8514:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8515:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8516:                                     $offloadoth = 1;
                   8517:                                     $dom_in_use = $env{'user.domain'};
                   8518:                                 }
                   8519:                             }
1.1075.2.145  raeburn  8520:                         }
                   8521:                     }
                   8522:                     unless ($offload) {
                   8523:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   8524:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   8525:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   8526:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   8527:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   8528:                                         $offload = 1;
1.1075.2.151  raeburn  8529:                                         $offloadoth = 1;
1.1075.2.145  raeburn  8530:                                         $dom_in_use = $env{'user.domain'};
                   8531:                                     }
1.1075.2.89  raeburn  8532:                                 }
1.1075.2.145  raeburn  8533:                             }
                   8534:                         }
                   8535:                     }
                   8536:                     if ($offload) {
1.1075.2.158  raeburn  8537:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1075.2.151  raeburn  8538:                         if (($newserver eq '') && ($offloadoth)) {
                   8539:                             my @domains = &Apache::lonnet::current_machine_domains();
1.1075.2.161.  .1(raebu 8540:21):                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
1.1075.2.151  raeburn  8541:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   8542:                             }
                   8543:                         }
1.1075.2.145  raeburn  8544:                         if (($newserver) && ($newserver ne $lonhost)) {
                   8545:                             my $numsec = 5;
                   8546:                             my $timeout = $numsec * 1000;
                   8547:                             my ($newurl,$locknum,%locks,$msg);
                   8548:                             if ($env{'request.role.adv'}) {
                   8549:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   8550:                             }
                   8551:                             my $disable_submit = 0;
                   8552:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   8553:                                 $disable_submit = 1;
                   8554:                             }
                   8555:                             if ($locknum) {
                   8556:                                 my @lockinfo = sort(values(%locks));
1.1075.2.153  raeburn  8557:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1075.2.145  raeburn  8558:                                        join(", ",sort(values(%locks)))."\n";
                   8559:                                 if (&show_course()) {
                   8560:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
1.1075.2.89  raeburn  8561:                                 } else {
1.1075.2.145  raeburn  8562:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
                   8563:                                 }
                   8564:                             } else {
                   8565:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   8566:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   8567:                                 }
                   8568:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   8569:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   8570:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   8571:                                     $newurl .= '&role='.$env{'request.role'};
                   8572:                                 }
                   8573:                                 if ($env{'request.symb'}) {
                   8574:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   8575:                                     if ($shownsymb =~ m{^/enc/}) {
                   8576:                                         my $reqdmajor = 2;
                   8577:                                         my $reqdminor = 11;
                   8578:                                         my $reqdsubminor = 3;
                   8579:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   8580:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   8581:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   8582:                                         if (($major eq '' && $minor eq '') ||
                   8583:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   8584:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   8585:                                              ($reqdsubminor > $subminor))))) {
                   8586:                                             undef($shownsymb);
                   8587:                                         }
1.1075.2.89  raeburn  8588:                                     }
1.1075.2.145  raeburn  8589:                                     if ($shownsymb) {
                   8590:                                         &js_escape(\$shownsymb);
                   8591:                                         $newurl .= '&symb='.$shownsymb;
1.1075.2.89  raeburn  8592:                                     }
1.1075.2.145  raeburn  8593:                                 } else {
                   8594:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   8595:                                     &js_escape(\$shownurl);
                   8596:                                     $newurl .= '&origurl='.$shownurl;
1.1075.2.89  raeburn  8597:                                 }
1.1075.2.145  raeburn  8598:                             }
                   8599:                             &js_escape(\$msg);
                   8600:                             $result.=<<OFFLOAD
1.1075.2.89  raeburn  8601: <meta http-equiv="pragma" content="no-cache" />
                   8602: <script type="text/javascript">
1.1075.2.92  raeburn  8603: // <![CDATA[
1.1075.2.89  raeburn  8604: function LC_Offload_Now() {
                   8605:     var dest = "$newurl";
                   8606:     if (dest != '') {
                   8607:         window.location.href="$newurl";
                   8608:     }
                   8609: }
1.1075.2.92  raeburn  8610: \$(document).ready(function () {
                   8611:     window.alert('$msg');
                   8612:     if ($disable_submit) {
1.1075.2.89  raeburn  8613:         \$(".LC_hwk_submit").prop("disabled", true);
                   8614:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  8615:     }
                   8616:     setTimeout('LC_Offload_Now()', $timeout);
                   8617: });
                   8618: // ]]>
1.1075.2.89  raeburn  8619: </script>
                   8620: OFFLOAD
                   8621:                         }
                   8622:                     }
                   8623:                 }
                   8624:             }
                   8625:         }
1.313     albertel 8626:     }
1.306     albertel 8627:     if (!defined($title)) {
                   8628: 	$title = 'The LearningOnline Network with CAPA';
                   8629:     }
1.460     albertel 8630:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   8631:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  8632: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   8633:     if (!$args->{'frameset'}) {
                   8634:         $result .= ' /';
                   8635:     }
                   8636:     $result .= '>'
1.1064    raeburn  8637:         .$inhibitprint
1.414     albertel 8638: 	.$head_extra;
1.1075.2.108  raeburn  8639:     my $clientmobile;
                   8640:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   8641:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   8642:     } else {
                   8643:         $clientmobile = $env{'browser.mobile'};
                   8644:     }
                   8645:     if ($clientmobile) {
1.1075.2.42  raeburn  8646:         $result .= '
                   8647: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   8648: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   8649:     }
1.1075.2.126  raeburn  8650:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 8651:     return $result.'</head>';
1.306     albertel 8652: }
                   8653: 
                   8654: =pod
                   8655: 
1.340     albertel 8656: =item * &font_settings()
                   8657: 
                   8658: Returns neccessary <meta> to set the proper encoding
                   8659: 
1.1075.2.56  raeburn  8660: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 8661: 
                   8662: =cut
                   8663: 
                   8664: sub font_settings {
1.1075.2.56  raeburn  8665:     my ($args) = @_;
1.340     albertel 8666:     my $headerstring='';
1.1075.2.56  raeburn  8667:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   8668:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 8669: 	$headerstring.=
1.1075.2.61  raeburn  8670: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   8671:         if (!$args->{'frameset'}) {
                   8672:             $headerstring.= ' /';
                   8673:         }
                   8674:         $headerstring .= '>'."\n";
1.340     albertel 8675:     }
                   8676:     return $headerstring;
                   8677: }
                   8678: 
1.341     albertel 8679: =pod
                   8680: 
1.1064    raeburn  8681: =item * &print_suppression()
                   8682: 
                   8683: In course context returns css which causes the body to be blank when media="print",
                   8684: if printout generation is unavailable for the current resource.
                   8685: 
                   8686: This could be because:
                   8687: 
                   8688: (a) printstartdate is in the future
                   8689: 
                   8690: (b) printenddate is in the past
                   8691: 
                   8692: (c) there is an active exam block with "printout"
                   8693: functionality blocked
                   8694: 
                   8695: Users with pav, pfo or evb privileges are exempt.
                   8696: 
                   8697: Inputs: none
                   8698: 
                   8699: =cut
                   8700: 
                   8701: 
                   8702: sub print_suppression {
                   8703:     my $noprint;
                   8704:     if ($env{'request.course.id'}) {
                   8705:         my $scope = $env{'request.course.id'};
                   8706:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8707:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   8708:             return;
                   8709:         }
                   8710:         if ($env{'request.course.sec'} ne '') {
                   8711:             $scope .= "/$env{'request.course.sec'}";
                   8712:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   8713:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  8714:                 return;
1.1064    raeburn  8715:             }
                   8716:         }
                   8717:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8718:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.158  raeburn  8719:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   8720:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  8721:         if ($blocked) {
                   8722:             my $checkrole = "cm./$cdom/$cnum";
                   8723:             if ($env{'request.course.sec'} ne '') {
                   8724:                 $checkrole .= "/$env{'request.course.sec'}";
                   8725:             }
                   8726:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   8727:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   8728:                 $noprint = 1;
                   8729:             }
                   8730:         }
                   8731:         unless ($noprint) {
                   8732:             my $symb = &Apache::lonnet::symbread();
                   8733:             if ($symb ne '') {
                   8734:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   8735:                 if (ref($navmap)) {
                   8736:                     my $res = $navmap->getBySymb($symb);
                   8737:                     if (ref($res)) {
                   8738:                         if (!$res->resprintable()) {
                   8739:                             $noprint = 1;
                   8740:                         }
                   8741:                     }
                   8742:                 }
                   8743:             }
                   8744:         }
                   8745:         if ($noprint) {
                   8746:             return <<"ENDSTYLE";
                   8747: <style type="text/css" media="print">
                   8748:     body { display:none }
                   8749: </style>
                   8750: ENDSTYLE
                   8751:         }
                   8752:     }
                   8753:     return;
                   8754: }
                   8755: 
                   8756: =pod
                   8757: 
1.341     albertel 8758: =item * &xml_begin()
                   8759: 
                   8760: Returns the needed doctype and <html>
                   8761: 
                   8762: Inputs: none
                   8763: 
                   8764: =cut
                   8765: 
                   8766: sub xml_begin {
1.1075.2.61  raeburn  8767:     my ($is_frameset) = @_;
1.341     albertel 8768:     my $output='';
                   8769: 
                   8770:     if ($env{'browser.mathml'}) {
                   8771: 	$output='<?xml version="1.0"?>'
                   8772:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8773: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8774:             
                   8775: #	    .'<!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">] >'
                   8776: 	    .'<!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">'
                   8777:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8778: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8779:     } elsif ($is_frameset) {
                   8780:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8781:                 '<html>'."\n";
1.341     albertel 8782:     } else {
1.1075.2.61  raeburn  8783: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8784:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8785:     }
                   8786:     return $output;
                   8787: }
1.340     albertel 8788: 
                   8789: =pod
                   8790: 
1.306     albertel 8791: =item * &start_page()
                   8792: 
                   8793: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8794: 
1.648     raeburn  8795: Inputs:
                   8796: 
                   8797: =over 4
                   8798: 
                   8799: $title - optional title for the page
                   8800: 
                   8801: $head_extra - optional extra HTML to incude inside the <head>
                   8802: 
                   8803: $args - additional optional args supported are:
                   8804: 
                   8805: =over 8
                   8806: 
                   8807:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8808:                                     arg on
1.814     bisitz   8809:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8810:              add_entries    -> additional attributes to add to the  <body>
                   8811:              domain         -> force to color decorate a page for a 
1.317     albertel 8812:                                     specific domain
1.648     raeburn  8813:              function       -> force usage of a specific rolish color
1.317     albertel 8814:                                     scheme
1.648     raeburn  8815:              redirect       -> see &headtag()
                   8816:              bgcolor        -> override the default page bg color
                   8817:              js_ready       -> return a string ready for being used in 
1.317     albertel 8818:                                     a javascript writeln
1.648     raeburn  8819:              html_encode    -> return a string ready for being used in 
1.320     albertel 8820:                                     a html attribute
1.648     raeburn  8821:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8822:                                     $forcereg arg
1.648     raeburn  8823:              frameset       -> if true will start with a <frameset>
1.330     albertel 8824:                                     rather than <body>
1.648     raeburn  8825:              skip_phases    -> hash ref of 
1.338     albertel 8826:                                     head -> skip the <html><head> generation
                   8827:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8828:              no_inline_link -> if true and in remote mode, don't show the
                   8829:                                     'Switch To Inline Menu' link
1.648     raeburn  8830:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8831:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8832:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8833:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8834:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8835:              group          -> includes the current group, if page is for a
                   8836:                                specific group
1.1075.2.133  raeburn  8837:              use_absolute   -> for request for external resource or syllabus, this
                   8838:                                will contain https://<hostname> if server uses
                   8839:                                https (as per hosts.tab), but request is for http
                   8840:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1075.2.158  raeburn  8841:              links_disabled -> Links in primary and secondary menus are disabled
                   8842:                                (Can enable them once page has loaded - see lonroles.pm
                   8843:                                for an example).
1.1075.2.161.  .6(raebu 8844:22):              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 8845: 
1.648     raeburn  8846: =back
1.460     albertel 8847: 
1.648     raeburn  8848: =back
1.562     albertel 8849: 
1.306     albertel 8850: =cut
                   8851: 
                   8852: sub start_page {
1.309     albertel 8853:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8854:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8855: 
1.315     albertel 8856:     $env{'internal.start_page'}++;
1.1075.2.161.  .1(raebu 8857:21):     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 8858: 
1.338     albertel 8859:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8860:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8861:     }
1.1075.2.161.  .1(raebu 8862:21): 
                   8863:21):     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
                   8864:21):         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   8865:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   8866:21):                 $args->{'no_primary_menu'} = 1;
                   8867:21):             }
                   8868:21):             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   8869:21):                 $args->{'no_inline_menu'} = 1;
                   8870:21):             }
                   8871:21):             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   8872:21):                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   8873:21):             }
                   8874:21):         } else {
                   8875:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8876:21):             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   8877:21):             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   8878:21):                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   8879:21):                     $args->{'no_primary_menu'} = 1;
                   8880:21):                 }
                   8881:21):                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   8882:21):                     $args->{'no_inline_menu'} = 1;
                   8883:21):                 }
                   8884:21):                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   8885:21):                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   8886:21):                 }
                   8887:21):             }
                   8888:21):         }
                   8889:21):         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   8890:21):                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   8891:21):                                   $env{'course.'.$env{'request.course.id'}.'.num'});
                   8892:21):     } elsif ($env{'request.course.id'}) {
                   8893:21):         my $expiretime=600;
                   8894:21):         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   8895:21):             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   8896:21):         }
                   8897:21):         my ($deeplinkmenu,$menuref);
                   8898:21):         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   8899:21):         if ($menucoll) {
                   8900:21):             if (ref($menuref) eq 'HASH') {
                   8901:21):                 %menu = %{$menuref};
                   8902:21):             }
                   8903:21):             if ($menu{'top'} eq 'n') {
                   8904:21):                 $args->{'no_primary_menu'} = 1;
                   8905:21):             }
                   8906:21):             if ($menu{'inline'} eq 'n') {
                   8907:21):                 unless (&Apache::lonnet::allowed('opa')) {
                   8908:21):                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8909:21):                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8910:21):                     my $crstype = &course_type();
                   8911:21):                     my $now = time;
                   8912:21):                     my $ccrole;
                   8913:21):                     if ($crstype eq 'Community') {
                   8914:21):                         $ccrole = 'co';
                   8915:21):                     } else {
                   8916:21):                         $ccrole = 'cc';
                   8917:21):                     }
                   8918:21):                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   8919:21):                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   8920:21):                         if ((($start) && ($start<0)) ||
                   8921:21):                             (($end) && ($end<$now))  ||
                   8922:21):                             (($start) && ($now<$start))) {
                   8923:21):                             $args->{'no_inline_menu'} = 1;
                   8924:21):                         }
                   8925:21):                     } else {
                   8926:21):                         $args->{'no_inline_menu'} = 1;
                   8927:21):                     }
                   8928:21):                 }
                   8929:21):             }
                   8930:21):         }
                   8931:21):     }
          .4(raebu 8932:22): 
          .8(raebu 8933:22):     my $showncrumbs;
1.338     albertel 8934:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8935: 	if ($args->{'frameset'}) {
                   8936: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8937: 						$args->{'add_entries'});
                   8938: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8939:         } else {
                   8940:             $result .=
                   8941:                 &bodytag($title, 
                   8942:                          $args->{'function'},       $args->{'add_entries'},
                   8943:                          $args->{'only_body'},      $args->{'domain'},
                   8944:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8945:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.161.  .1(raebu 8946:21):                          $args,                     \@advtools,
          .8(raebu 8947:22):                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
1.831     bisitz   8948:         }
1.330     albertel 8949:     }
1.338     albertel 8950: 
1.315     albertel 8951:     if ($args->{'js_ready'}) {
1.713     kaisler  8952: 		$result = &js_ready($result);
1.315     albertel 8953:     }
1.320     albertel 8954:     if ($args->{'html_encode'}) {
1.713     kaisler  8955: 		$result = &html_encode($result);
                   8956:     }
                   8957: 
1.813     bisitz   8958:     # Preparation for new and consistent functionlist at top of screen
                   8959:     # if ($args->{'functionlist'}) {
                   8960:     #            $result .= &build_functionlist();
                   8961:     #}
                   8962: 
1.964     droeschl 8963:     # Don't add anything more if only_body wanted or in const space
                   8964:     return $result if    $args->{'only_body'} 
                   8965:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8966: 
                   8967:     #Breadcrumbs
1.758     kaisler  8968:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1075.2.161.  .8(raebu 8969:22):         unless ($showncrumbs) {
1.758     kaisler  8970: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8971: 		#if any br links exists, add them to the breadcrumbs
                   8972: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8973: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8974: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8975: 			}
                   8976: 		}
1.1075.2.19  raeburn  8977:                 # if @advtools array contains items add then to the breadcrumbs
                   8978:                 if (@advtools > 0) {
                   8979:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8980:                 }
1.1075.2.123  raeburn  8981:                 my $menulink;
                   8982:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
1.1075.2.161.  .1(raebu 8983:21):                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
                   8984:21):                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
1.1075.2.123  raeburn  8985:                     $menulink = 0;
                   8986:                 } else {
                   8987:                     undef($menulink);
                   8988:                 }
1.1075.2.161.  .8(raebu 8989:22):                 my $linkprotout;
                   8990:22):                 if ($env{'request.deeplink.login'}) {
                   8991:22):                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   8992:22):                     if ($linkprotout) {
                   8993:22):                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   8994:22):                     }
                   8995:22):                 }
1.758     kaisler  8996: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8997: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8998: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1075.2.161.  .1(raebu 8999:21): 		} else {
1.1075.2.123  raeburn  9000: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9001: 		}
1.1075.2.161.  .8(raebu 9002:22):         }
1.1075.2.24  raeburn  9003:     } elsif (($env{'environment.remote'} eq 'on') &&
                   9004:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   9005:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   9006:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  9007:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 9008:     }
1.315     albertel 9009:     return $result;
1.306     albertel 9010: }
                   9011: 
                   9012: sub end_page {
1.315     albertel 9013:     my ($args) = @_;
                   9014:     $env{'internal.end_page'}++;
1.330     albertel 9015:     my $result;
1.335     albertel 9016:     if ($args->{'discussion'}) {
                   9017: 	my ($target,$parser);
                   9018: 	if (ref($args->{'discussion'})) {
                   9019: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9020: 				$args->{'discussion'}{'parser'});
                   9021: 	}
                   9022: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9023:     }
1.330     albertel 9024:     if ($args->{'frameset'}) {
                   9025: 	$result .= '</frameset>';
                   9026:     } else {
1.635     raeburn  9027: 	$result .= &endbodytag($args);
1.330     albertel 9028:     }
1.1075.2.6  raeburn  9029:     unless ($args->{'notbody'}) {
                   9030:         $result .= "\n</html>";
                   9031:     }
1.330     albertel 9032: 
1.315     albertel 9033:     if ($args->{'js_ready'}) {
1.317     albertel 9034: 	$result = &js_ready($result);
1.315     albertel 9035:     }
1.335     albertel 9036: 
1.320     albertel 9037:     if ($args->{'html_encode'}) {
                   9038: 	$result = &html_encode($result);
                   9039:     }
1.335     albertel 9040: 
1.315     albertel 9041:     return $result;
                   9042: }
                   9043: 
1.1075.2.161.  .1(raebu 9044:21): sub menucoll_in_effect {
                   9045:21):     my ($menucoll,$deeplinkmenu,%menu);
                   9046:21):     if ($env{'request.course.id'}) {
                   9047:21):         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
                   9048:21):         if ($env{'request.deeplink.login'}) {
                   9049:21):             my ($deeplink_symb,$deeplink,$check_login_symb);
                   9050:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9051:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9052:21):             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9053:21):                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9054:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9055:21):                     if (ref($navmap)) {
                   9056:21):                         $deeplink = $navmap->get_mapparam(undef,
                   9057:21):                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9058:21):                                                           '0.deeplink');
                   9059:21):                     } else {
                   9060:21):                         $check_login_symb = 1;
                   9061:21):                     }
                   9062:21):                 } else {
                   9063:21):                     my $symb=&Apache::lonnet::symbread();
                   9064:21):                     if ($symb) {
                   9065:21):                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9066:21):                     } else {
                   9067:21):                         $check_login_symb = 1;
                   9068:21):                     }
                   9069:21):                 }
                   9070:21):             } else {
                   9071:21):                 $check_login_symb = 1;
                   9072:21):             }
                   9073:21):             if ($check_login_symb) {
                   9074:21):                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9075:21):                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9076:21):                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9077:21):                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9078:21):                     if (ref($navmap)) {
                   9079:21):                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9080:21):                     }
                   9081:21):                 } else {
                   9082:21):                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9083:21):                 }
                   9084:21):             }
                   9085:21):             if ($deeplink ne '') {
          .6(raebu 9086:22):                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
          .1(raebu 9087:21):                 if ($display =~ /^\d+$/) {
                   9088:21):                     $deeplinkmenu = 1;
                   9089:21):                     $menucoll = $display;
                   9090:21):                 }
                   9091:21):             }
                   9092:21):         }
                   9093:21):         if ($menucoll) {
                   9094:21):             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9095:21):         }
                   9096:21):     }
                   9097:21):     return ($menucoll,$deeplinkmenu,\%menu);
                   9098:21): }
                   9099:21): 
                   9100:21): sub deeplink_login_symb {
                   9101:21):     my ($cnum,$cdom) = @_;
                   9102:21):     my $login_symb;
                   9103:21):     if ($env{'request.deeplink.login'}) {
                   9104:21):         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9105:21):     }
                   9106:21):     return $login_symb;
                   9107:21): }
                   9108:21): 
                   9109:21): sub symb_from_tinyurl {
                   9110:21):     my ($url,$cnum,$cdom) = @_;
                   9111:21):     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9112:21):         my $key = $1;
                   9113:21):         my ($tinyurl,$login);
                   9114:21):         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9115:21):         if (defined($cached)) {
                   9116:21):             $tinyurl = $result;
                   9117:21):         } else {
                   9118:21):             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9119:21):             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9120:21):             if ($currtiny{$key} ne '') {
                   9121:21):                 $tinyurl = $currtiny{$key};
                   9122:21):                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
                   9123:21):             }
                   9124:21):         }
                   9125:21):         if ($tinyurl ne '') {
                   9126:21):             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9127:21):             if (wantarray) {
                   9128:21):                 return ($cnumreq,$symb);
                   9129:21):             } elsif ($cnumreq eq $cnum) {
                   9130:21):                 return $symb;
                   9131:21):             }
                   9132:21):         }
                   9133:21):     }
                   9134:21):     if (wantarray) {
                   9135:21):         return ();
                   9136:21):     } else {
                   9137:21):         return;
                   9138:21):     }
                   9139:21): }
                   9140:21): 
1.1034    www      9141: sub wishlist_window {
                   9142:     return(<<'ENDWISHLIST');
1.1046    raeburn  9143: <script type="text/javascript">
1.1034    www      9144: // <![CDATA[
                   9145: // <!-- BEGIN LON-CAPA Internal
                   9146: function set_wishlistlink(title, path) {
                   9147:     if (!title) {
                   9148:         title = document.title;
                   9149:         title = title.replace(/^LON-CAPA /,'');
                   9150:     }
1.1075.2.65  raeburn  9151:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  9152:     title = title.replace("'","\\\'");
1.1034    www      9153:     if (!path) {
                   9154:         path = location.pathname;
                   9155:     }
1.1075.2.65  raeburn  9156:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  9157:     path = path.replace("'","\\\'");
1.1034    www      9158:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   9159:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   9160: }
                   9161: // END LON-CAPA Internal -->
                   9162: // ]]>
                   9163: </script>
                   9164: ENDWISHLIST
                   9165: }
                   9166: 
1.1030    www      9167: sub modal_window {
                   9168:     return(<<'ENDMODAL');
1.1046    raeburn  9169: <script type="text/javascript">
1.1030    www      9170: // <![CDATA[
                   9171: // <!-- BEGIN LON-CAPA Internal
                   9172: var modalWindow = {
                   9173: 	parent:"body",
                   9174: 	windowId:null,
                   9175: 	content:null,
                   9176: 	width:null,
                   9177: 	height:null,
                   9178: 	close:function()
                   9179: 	{
                   9180: 	        $(".LCmodal-window").remove();
                   9181: 	        $(".LCmodal-overlay").remove();
                   9182: 	},
                   9183: 	open:function()
                   9184: 	{
                   9185: 		var modal = "";
                   9186: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   9187: 		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;\">";
                   9188: 		modal += this.content;
                   9189: 		modal += "</div>";	
                   9190: 
                   9191: 		$(this.parent).append(modal);
                   9192: 
                   9193: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   9194: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   9195: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   9196: 	}
                   9197: };
1.1075.2.42  raeburn  9198: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      9199: 	{
1.1075.2.119  raeburn  9200:                 source = source.replace(/'/g,"&#39;");
1.1030    www      9201: 		modalWindow.windowId = "myModal";
                   9202: 		modalWindow.width = width;
                   9203: 		modalWindow.height = height;
1.1075.2.80  raeburn  9204: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      9205: 		modalWindow.open();
1.1075.2.87  raeburn  9206: 	};
1.1030    www      9207: // END LON-CAPA Internal -->
                   9208: // ]]>
                   9209: </script>
                   9210: ENDMODAL
                   9211: }
                   9212: 
                   9213: sub modal_link {
1.1075.2.42  raeburn  9214:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      9215:     unless ($width) { $width=480; }
                   9216:     unless ($height) { $height=400; }
1.1031    www      9217:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  9218:     unless ($transparency) { $transparency='true'; }
                   9219: 
1.1074    raeburn  9220:     my $target_attr;
                   9221:     if (defined($target)) {
                   9222:         $target_attr = 'target="'.$target.'"';
                   9223:     }
                   9224:     return <<"ENDLINK";
1.1075.2.143  raeburn  9225: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  9226: ENDLINK
1.1030    www      9227: }
                   9228: 
1.1032    www      9229: sub modal_adhoc_script {
1.1075.2.155  raeburn  9230:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   9231:     my $mathjax;
                   9232:     if ($possmathjax) {
                   9233:         $mathjax = <<'ENDJAX';
                   9234:                if (typeof MathJax == 'object') {
                   9235:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   9236:                }
                   9237: ENDJAX
                   9238:     }
1.1032    www      9239:     return (<<ENDADHOC);
1.1046    raeburn  9240: <script type="text/javascript">
1.1032    www      9241: // <![CDATA[
                   9242:         var $funcname = function()
                   9243:         {
                   9244:                 modalWindow.windowId = "myModal";
                   9245:                 modalWindow.width = $width;
                   9246:                 modalWindow.height = $height;
                   9247:                 modalWindow.content = '$content';
                   9248:                 modalWindow.open();
1.1075.2.155  raeburn  9249:                 $mathjax
1.1032    www      9250:         };  
                   9251: // ]]>
                   9252: </script>
                   9253: ENDADHOC
                   9254: }
                   9255: 
1.1041    www      9256: sub modal_adhoc_inner {
1.1075.2.155  raeburn  9257:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      9258:     my $innerwidth=$width-20;
                   9259:     $content=&js_ready(
1.1042    www      9260:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  9261:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   9262:                  $content.
1.1041    www      9263:                  &end_scrollbox().
1.1075.2.42  raeburn  9264:                  &end_page()
1.1041    www      9265:              );
1.1075.2.155  raeburn  9266:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      9267: }
                   9268: 
                   9269: sub modal_adhoc_window {
1.1075.2.155  raeburn  9270:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   9271:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      9272:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   9273: }
                   9274: 
                   9275: sub modal_adhoc_launch {
                   9276:     my ($funcname,$width,$height,$content)=@_;
                   9277:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   9278: <script type="text/javascript">
                   9279: // <![CDATA[
                   9280: $funcname();
                   9281: // ]]>
                   9282: </script>
                   9283: ENDLAUNCH
                   9284: }
                   9285: 
                   9286: sub modal_adhoc_close {
                   9287:     return (<<ENDCLOSE);
                   9288: <script type="text/javascript">
                   9289: // <![CDATA[
                   9290: modalWindow.close();
                   9291: // ]]>
                   9292: </script>
                   9293: ENDCLOSE
                   9294: }
                   9295: 
1.1038    www      9296: sub togglebox_script {
                   9297:    return(<<ENDTOGGLE);
                   9298: <script type="text/javascript"> 
                   9299: // <![CDATA[
                   9300: function LCtoggleDisplay(id,hidetext,showtext) {
                   9301:    link = document.getElementById(id + "link").childNodes[0];
                   9302:    with (document.getElementById(id).style) {
                   9303:       if (display == "none" ) {
                   9304:           display = "inline";
                   9305:           link.nodeValue = hidetext;
                   9306:         } else {
                   9307:           display = "none";
                   9308:           link.nodeValue = showtext;
                   9309:        }
                   9310:    }
                   9311: }
                   9312: // ]]>
                   9313: </script>
                   9314: ENDTOGGLE
                   9315: }
                   9316: 
1.1039    www      9317: sub start_togglebox {
                   9318:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   9319:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   9320:     unless ($showtext) { $showtext=&mt('show'); }
                   9321:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   9322:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   9323:     return &start_data_table().
                   9324:            &start_data_table_header_row().
                   9325:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   9326:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   9327:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   9328:            &end_data_table_header_row().
                   9329:            '<tr id="'.$id.'" style="display:none""><td>';
                   9330: }
                   9331: 
                   9332: sub end_togglebox {
                   9333:     return '</td></tr>'.&end_data_table();
                   9334: }
                   9335: 
1.1041    www      9336: sub LCprogressbar_script {
1.1075.2.130  raeburn  9337:    my ($id,$number_to_do)=@_;
                   9338:    if ($number_to_do) {
                   9339:        return(<<ENDPROGRESS);
1.1041    www      9340: <script type="text/javascript">
                   9341: // <![CDATA[
1.1045    www      9342: \$('#progressbar$id').progressbar({
1.1041    www      9343:   value: 0,
                   9344:   change: function(event, ui) {
                   9345:     var newVal = \$(this).progressbar('option', 'value');
                   9346:     \$('.pblabel', this).text(LCprogressTxt);
                   9347:   }
                   9348: });
                   9349: // ]]>
                   9350: </script>
                   9351: ENDPROGRESS
1.1075.2.130  raeburn  9352:    } else {
                   9353:        return(<<ENDPROGRESS);
                   9354: <script type="text/javascript">
                   9355: // <![CDATA[
                   9356: \$('#progressbar$id').progressbar({
                   9357:   value: false,
                   9358:   create: function(event, ui) {
                   9359:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   9360:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   9361:   }
                   9362: });
                   9363: // ]]>
                   9364: </script>
                   9365: ENDPROGRESS
                   9366:    }
1.1041    www      9367: }
                   9368: 
                   9369: sub LCprogressbarUpdate_script {
                   9370:    return(<<ENDPROGRESSUPDATE);
                   9371: <style type="text/css">
                   9372: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  9373: .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      9374: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   9375: </style>
                   9376: <script type="text/javascript">
                   9377: // <![CDATA[
1.1045    www      9378: var LCprogressTxt='---';
                   9379: 
1.1075.2.130  raeburn  9380: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      9381:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  9382:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   9383:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   9384:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   9385:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   9386:    } else {
                   9387:        \$('#progressbar'+id).progressbar('value',percent);
                   9388:    }
1.1041    www      9389: }
                   9390: // ]]>
                   9391: </script>
                   9392: ENDPROGRESSUPDATE
                   9393: }
                   9394: 
1.1042    www      9395: my $LClastpercent;
1.1045    www      9396: my $LCidcnt;
                   9397: my $LCcurrentid;
1.1042    www      9398: 
1.1041    www      9399: sub LCprogressbar {
1.1075.2.130  raeburn  9400:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      9401:     $LClastpercent=0;
1.1045    www      9402:     $LCidcnt++;
                   9403:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  9404:     my ($starting,$content);
                   9405:     if ($number_to_do) {
                   9406:         $starting=&mt('Starting');
                   9407:         $content=(<<ENDPROGBAR);
                   9408: $preamble
1.1045    www      9409:   <div id="progressbar$LCcurrentid">
1.1041    www      9410:     <span class="pblabel">$starting</span>
                   9411:   </div>
                   9412: ENDPROGBAR
1.1075.2.130  raeburn  9413:     } else {
                   9414:         $starting=&mt('Loading...');
                   9415:         $LClastpercent='false';
                   9416:         $content=(<<ENDPROGBAR);
                   9417: $preamble
                   9418:   <div id="progressbar$LCcurrentid">
                   9419:       <div class="progress-label">$starting</div>
                   9420:   </div>
                   9421: ENDPROGBAR
                   9422:     }
                   9423:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      9424: }
                   9425: 
                   9426: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  9427:     my ($r,$val,$text,$number_to_do)=@_;
                   9428:     if ($number_to_do) {
                   9429:         unless ($val) { 
                   9430:             if ($LClastpercent) {
                   9431:                 $val=$LClastpercent;
                   9432:             } else {
                   9433:                 $val=0;
                   9434:             }
                   9435:         }
                   9436:         if ($val<0) { $val=0; }
                   9437:         if ($val>100) { $val=0; }
                   9438:         $LClastpercent=$val;
                   9439:         unless ($text) { $text=$val.'%'; }
                   9440:     } else {
                   9441:         $val = 'false';
1.1042    www      9442:     }
1.1041    www      9443:     $text=&js_ready($text);
1.1044    www      9444:     &r_print($r,<<ENDUPDATE);
1.1041    www      9445: <script type="text/javascript">
                   9446: // <![CDATA[
1.1075.2.130  raeburn  9447: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      9448: // ]]>
                   9449: </script>
                   9450: ENDUPDATE
1.1035    www      9451: }
                   9452: 
1.1042    www      9453: sub LCprogressbarClose {
                   9454:     my ($r)=@_;
                   9455:     $LClastpercent=0;
1.1044    www      9456:     &r_print($r,<<ENDCLOSE);
1.1042    www      9457: <script type="text/javascript">
                   9458: // <![CDATA[
1.1045    www      9459: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      9460: // ]]>
                   9461: </script>
                   9462: ENDCLOSE
1.1044    www      9463: }
                   9464: 
                   9465: sub r_print {
                   9466:     my ($r,$to_print)=@_;
                   9467:     if ($r) {
                   9468:       $r->print($to_print);
                   9469:       $r->rflush();
                   9470:     } else {
                   9471:       print($to_print);
                   9472:     }
1.1042    www      9473: }
                   9474: 
1.320     albertel 9475: sub html_encode {
                   9476:     my ($result) = @_;
                   9477: 
1.322     albertel 9478:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 9479:     
                   9480:     return $result;
                   9481: }
1.1044    www      9482: 
1.317     albertel 9483: sub js_ready {
                   9484:     my ($result) = @_;
                   9485: 
1.323     albertel 9486:     $result =~ s/[\n\r]/ /xmsg;
                   9487:     $result =~ s/\\/\\\\/xmsg;
                   9488:     $result =~ s/'/\\'/xmsg;
1.372     albertel 9489:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 9490:     
                   9491:     return $result;
                   9492: }
                   9493: 
1.315     albertel 9494: sub validate_page {
                   9495:     if (  exists($env{'internal.start_page'})
1.316     albertel 9496: 	  &&     $env{'internal.start_page'} > 1) {
                   9497: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 9498: 				 $env{'internal.start_page'}.' '.
1.316     albertel 9499: 				 $ENV{'request.filename'});
1.315     albertel 9500:     }
                   9501:     if (  exists($env{'internal.end_page'})
1.316     albertel 9502: 	  &&     $env{'internal.end_page'} > 1) {
                   9503: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 9504: 				 $env{'internal.end_page'}.' '.
1.316     albertel 9505: 				 $env{'request.filename'});
1.315     albertel 9506:     }
                   9507:     if (     exists($env{'internal.start_page'})
                   9508: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 9509: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   9510: 				 $env{'request.filename'});
1.315     albertel 9511:     }
                   9512:     if (   ! exists($env{'internal.start_page'})
                   9513: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 9514: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   9515: 				 $env{'request.filename'});
1.315     albertel 9516:     }
1.306     albertel 9517: }
1.315     albertel 9518: 
1.996     www      9519: 
                   9520: sub start_scrollbox {
1.1075.2.56  raeburn  9521:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  9522:     unless ($outerwidth) { $outerwidth='520px'; }
                   9523:     unless ($width) { $width='500px'; }
                   9524:     unless ($height) { $height='200px'; }
1.1075    raeburn  9525:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  9526:     if ($id ne '') {
1.1075.2.42  raeburn  9527:         $table_id = ' id="table_'.$id.'"';
                   9528:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  9529:     }
1.1075    raeburn  9530:     if ($bgcolor ne '') {
                   9531:         $tdcol = "background-color: $bgcolor;";
                   9532:     }
1.1075.2.42  raeburn  9533:     my $nicescroll_js;
                   9534:     if ($env{'browser.mobile'}) {
                   9535:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   9536:     }
1.1075    raeburn  9537:     return <<"END";
1.1075.2.42  raeburn  9538: $nicescroll_js
                   9539: 
                   9540: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  9541: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  9542: END
1.996     www      9543: }
                   9544: 
                   9545: sub end_scrollbox {
1.1036    www      9546:     return '</div></td></tr></table>';
1.996     www      9547: }
                   9548: 
1.1075.2.42  raeburn  9549: sub nicescroll_javascript {
                   9550:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   9551:     my %options;
                   9552:     if (ref($cursor) eq 'HASH') {
                   9553:         %options = %{$cursor};
                   9554:     }
                   9555:     unless ($options{'railalign'} =~ /^left|right$/) {
                   9556:         $options{'railalign'} = 'left';
                   9557:     }
                   9558:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9559:         my $function  = &get_users_function();
                   9560:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   9561:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   9562:             $options{'cursorcolor'} = '#00F';
                   9563:         }
                   9564:     }
                   9565:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   9566:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   9567:             $options{'cursoropacity'}='1.0';
                   9568:         }
                   9569:     } else {
                   9570:         $options{'cursoropacity'}='1.0';
                   9571:     }
                   9572:     if ($options{'cursorfixedheight'} eq 'none') {
                   9573:         delete($options{'cursorfixedheight'});
                   9574:     } else {
                   9575:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   9576:     }
                   9577:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   9578:         delete($options{'railoffset'});
                   9579:     }
                   9580:     my @niceoptions;
                   9581:     while (my($key,$value) = each(%options)) {
                   9582:         if ($value =~ /^\{.+\}$/) {
                   9583:             push(@niceoptions,$key.':'.$value);
                   9584:         } else {
                   9585:             push(@niceoptions,$key.':"'.$value.'"');
                   9586:         }
                   9587:     }
                   9588:     my $nicescroll_js = '
                   9589: $(document).ready(
                   9590:       function() {
                   9591:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   9592:       }
                   9593: );
                   9594: ';
                   9595:     if ($framecheck) {
                   9596:         $nicescroll_js .= '
                   9597: function expand_div(caller) {
                   9598:     if (top === self) {
                   9599:         document.getElementById("'.$id.'").style.width = "auto";
                   9600:         document.getElementById("'.$id.'").style.height = "auto";
                   9601:     } else {
                   9602:         try {
                   9603:             if (parent.frames) {
                   9604:                 if (parent.frames.length > 1) {
                   9605:                     var framesrc = parent.frames[1].location.href;
                   9606:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   9607:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   9608:                         document.getElementById("'.$id.'").style.width = "auto";
                   9609:                         document.getElementById("'.$id.'").style.height = "auto";
                   9610:                     }
                   9611:                 }
                   9612:             }
                   9613:         } catch (e) {
                   9614:             return;
                   9615:         }
                   9616:     }
                   9617:     return;
                   9618: }
                   9619: ';
                   9620:     }
                   9621:     if ($needjsready) {
                   9622:         $nicescroll_js = '
                   9623: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   9624:     } else {
                   9625:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   9626:     }
                   9627:     return $nicescroll_js;
                   9628: }
                   9629: 
1.318     albertel 9630: sub simple_error_page {
1.1075.2.49  raeburn  9631:     my ($r,$title,$msg,$args) = @_;
1.1075.2.161.  .4(raebu 9632:22):     my %displayargs;
1.1075.2.49  raeburn  9633:     if (ref($args) eq 'HASH') {
                   9634:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1075.2.161.  .4(raebu 9635:22):         if ($args->{'only_body'}) {
                   9636:22):             $displayargs{'only_body'} = 1;
                   9637:22):         }
                   9638:22):         if ($args->{'no_nav_bar'}) {
                   9639:22):             $displayargs{'no_nav_bar'} = 1;
                   9640:22):         }
1.1075.2.49  raeburn  9641:     } else {
                   9642:         $msg = &mt($msg);
                   9643:     }
                   9644: 
1.318     albertel 9645:     my $page =
1.1075.2.161.  .4(raebu 9646:22): 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1075.2.49  raeburn  9647: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 9648: 	&Apache::loncommon::end_page();
                   9649:     if (ref($r)) {
                   9650: 	$r->print($page);
1.327     albertel 9651: 	return;
1.318     albertel 9652:     }
                   9653:     return $page;
                   9654: }
1.347     albertel 9655: 
                   9656: {
1.610     albertel 9657:     my @row_count;
1.961     onken    9658: 
                   9659:     sub start_data_table_count {
                   9660:         unshift(@row_count, 0);
                   9661:         return;
                   9662:     }
                   9663: 
                   9664:     sub end_data_table_count {
                   9665:         shift(@row_count);
                   9666:         return;
                   9667:     }
                   9668: 
1.347     albertel 9669:     sub start_data_table {
1.1018    raeburn  9670: 	my ($add_class,$id) = @_;
1.422     albertel 9671: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  9672:         my $table_id;
                   9673:         if (defined($id)) {
                   9674:             $table_id = ' id="'.$id.'"';
                   9675:         }
1.961     onken    9676: 	&start_data_table_count();
1.1018    raeburn  9677: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 9678:     }
                   9679: 
                   9680:     sub end_data_table {
1.961     onken    9681: 	&end_data_table_count();
1.389     albertel 9682: 	return '</table>'."\n";;
1.347     albertel 9683:     }
                   9684: 
                   9685:     sub start_data_table_row {
1.974     wenzelju 9686: 	my ($add_class, $id) = @_;
1.610     albertel 9687: 	$row_count[0]++;
                   9688: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   9689: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 9690:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9691:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 9692:     }
1.471     banghart 9693:     
                   9694:     sub continue_data_table_row {
1.974     wenzelju 9695: 	my ($add_class, $id) = @_;
1.610     albertel 9696: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 9697: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   9698:         $id = (' id="'.$id.'"') unless ($id eq '');
                   9699:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 9700:     }
1.347     albertel 9701: 
                   9702:     sub end_data_table_row {
1.389     albertel 9703: 	return '</tr>'."\n";;
1.347     albertel 9704:     }
1.367     www      9705: 
1.421     albertel 9706:     sub start_data_table_empty_row {
1.707     bisitz   9707: #	$row_count[0]++;
1.421     albertel 9708: 	return  '<tr class="LC_empty_row" >'."\n";;
                   9709:     }
                   9710: 
                   9711:     sub end_data_table_empty_row {
                   9712: 	return '</tr>'."\n";;
                   9713:     }
                   9714: 
1.367     www      9715:     sub start_data_table_header_row {
1.389     albertel 9716: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      9717:     }
                   9718: 
                   9719:     sub end_data_table_header_row {
1.389     albertel 9720: 	return '</tr>'."\n";;
1.367     www      9721:     }
1.890     droeschl 9722: 
                   9723:     sub data_table_caption {
                   9724:         my $caption = shift;
                   9725:         return "<caption class=\"LC_caption\">$caption</caption>";
                   9726:     }
1.347     albertel 9727: }
                   9728: 
1.548     albertel 9729: =pod
                   9730: 
                   9731: =item * &inhibit_menu_check($arg)
                   9732: 
                   9733: Checks for a inhibitmenu state and generates output to preserve it
                   9734: 
                   9735: Inputs:         $arg - can be any of
                   9736:                      - undef - in which case the return value is a string 
                   9737:                                to add  into arguments list of a uri
                   9738:                      - 'input' - in which case the return value is a HTML
                   9739:                                  <form> <input> field of type hidden to
                   9740:                                  preserve the value
                   9741:                      - a url - in which case the return value is the url with
                   9742:                                the neccesary cgi args added to preserve the
                   9743:                                inhibitmenu state
                   9744:                      - a ref to a url - no return value, but the string is
                   9745:                                         updated to include the neccessary cgi
                   9746:                                         args to preserve the inhibitmenu state
                   9747: 
                   9748: =cut
                   9749: 
                   9750: sub inhibit_menu_check {
                   9751:     my ($arg) = @_;
                   9752:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   9753:     if ($arg eq 'input') {
                   9754: 	if ($env{'form.inhibitmenu'}) {
                   9755: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   9756: 	} else {
                   9757: 	    return
                   9758: 	}
                   9759:     }
                   9760:     if ($env{'form.inhibitmenu'}) {
                   9761: 	if (ref($arg)) {
                   9762: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9763: 	} elsif ($arg eq '') {
                   9764: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   9765: 	} else {
                   9766: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   9767: 	}
                   9768:     }
                   9769:     if (!ref($arg)) {
                   9770: 	return $arg;
                   9771:     }
                   9772: }
                   9773: 
1.251     albertel 9774: ###############################################
1.182     matthew  9775: 
                   9776: =pod
                   9777: 
1.549     albertel 9778: =back
                   9779: 
                   9780: =head1 User Information Routines
                   9781: 
                   9782: =over 4
                   9783: 
1.405     albertel 9784: =item * &get_users_function()
1.182     matthew  9785: 
                   9786: Used by &bodytag to determine the current users primary role.
                   9787: Returns either 'student','coordinator','admin', or 'author'.
                   9788: 
                   9789: =cut
                   9790: 
                   9791: ###############################################
                   9792: sub get_users_function {
1.815     tempelho 9793:     my $function = 'norole';
1.818     tempelho 9794:     if ($env{'request.role'}=~/^(st)/) {
                   9795:         $function='student';
                   9796:     }
1.907     raeburn  9797:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  9798:         $function='coordinator';
                   9799:     }
1.258     albertel 9800:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  9801:         $function='admin';
                   9802:     }
1.826     bisitz   9803:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  9804:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  9805:         $function='author';
                   9806:     }
                   9807:     return $function;
1.54      www      9808: }
1.99      www      9809: 
                   9810: ###############################################
                   9811: 
1.233     raeburn  9812: =pod
                   9813: 
1.821     raeburn  9814: =item * &show_course()
                   9815: 
                   9816: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   9817: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   9818: 
                   9819: Inputs:
                   9820: None
                   9821: 
                   9822: Outputs:
                   9823: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   9824: 
                   9825: =cut
                   9826: 
                   9827: ###############################################
                   9828: sub show_course {
                   9829:     my $course = !$env{'user.adv'};
                   9830:     if (!$env{'user.adv'}) {
                   9831:         foreach my $env (keys(%env)) {
                   9832:             next if ($env !~ m/^user\.priv\./);
                   9833:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   9834:                 $course = 0;
                   9835:                 last;
                   9836:             }
                   9837:         }
                   9838:     }
                   9839:     return $course;
                   9840: }
                   9841: 
                   9842: ###############################################
                   9843: 
                   9844: =pod
                   9845: 
1.542     raeburn  9846: =item * &check_user_status()
1.274     raeburn  9847: 
                   9848: Determines current status of supplied role for a
                   9849: specific user. Roles can be active, previous or future.
                   9850: 
                   9851: Inputs: 
                   9852: user's domain, user's username, course's domain,
1.375     raeburn  9853: course's number, optional section ID.
1.274     raeburn  9854: 
                   9855: Outputs:
                   9856: role status: active, previous or future. 
                   9857: 
                   9858: =cut
                   9859: 
                   9860: sub check_user_status {
1.412     raeburn  9861:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  9862:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  9863:     my @uroles = keys(%userinfo);
1.274     raeburn  9864:     my $srchstr;
                   9865:     my $active_chk = 'none';
1.412     raeburn  9866:     my $now = time;
1.274     raeburn  9867:     if (@uroles > 0) {
1.908     raeburn  9868:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  9869:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   9870:         } else {
1.412     raeburn  9871:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   9872:         }
                   9873:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  9874:             my $role_end = 0;
                   9875:             my $role_start = 0;
                   9876:             $active_chk = 'active';
1.412     raeburn  9877:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   9878:                 $role_end = $1;
                   9879:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   9880:                     $role_start = $1;
1.274     raeburn  9881:                 }
                   9882:             }
                   9883:             if ($role_start > 0) {
1.412     raeburn  9884:                 if ($now < $role_start) {
1.274     raeburn  9885:                     $active_chk = 'future';
                   9886:                 }
                   9887:             }
                   9888:             if ($role_end > 0) {
1.412     raeburn  9889:                 if ($now > $role_end) {
1.274     raeburn  9890:                     $active_chk = 'previous';
                   9891:                 }
                   9892:             }
                   9893:         }
                   9894:     }
                   9895:     return $active_chk;
                   9896: }
                   9897: 
                   9898: ###############################################
                   9899: 
                   9900: =pod
                   9901: 
1.405     albertel 9902: =item * &get_sections()
1.233     raeburn  9903: 
                   9904: Determines all the sections for a course including
                   9905: sections with students and sections containing other roles.
1.419     raeburn  9906: Incoming parameters: 
                   9907: 
                   9908: 1. domain
                   9909: 2. course number 
                   9910: 3. reference to array containing roles for which sections should 
                   9911: be gathered (optional).
                   9912: 4. reference to array containing status types for which sections 
                   9913: should be gathered (optional).
                   9914: 
                   9915: If the third argument is undefined, sections are gathered for any role. 
                   9916: If the fourth argument is undefined, sections are gathered for any status.
                   9917: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  9918:  
1.374     raeburn  9919: Returns section hash (keys are section IDs, values are
                   9920: number of users in each section), subject to the
1.419     raeburn  9921: optional roles filter, optional status filter 
1.233     raeburn  9922: 
                   9923: =cut
                   9924: 
                   9925: ###############################################
                   9926: sub get_sections {
1.419     raeburn  9927:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 9928:     if (!defined($cdom) || !defined($cnum)) {
                   9929:         my $cid =  $env{'request.course.id'};
                   9930: 
                   9931: 	return if (!defined($cid));
                   9932: 
                   9933:         $cdom = $env{'course.'.$cid.'.domain'};
                   9934:         $cnum = $env{'course.'.$cid.'.num'};
                   9935:     }
                   9936: 
                   9937:     my %sectioncount;
1.419     raeburn  9938:     my $now = time;
1.240     albertel 9939: 
1.1075.2.33  raeburn  9940:     my $check_students = 1;
                   9941:     my $only_students = 0;
                   9942:     if (ref($possible_roles) eq 'ARRAY') {
                   9943:         if (grep(/^st$/,@{$possible_roles})) {
                   9944:             if (@{$possible_roles} == 1) {
                   9945:                 $only_students = 1;
                   9946:             }
                   9947:         } else {
                   9948:             $check_students = 0;
                   9949:         }
                   9950:     }
                   9951: 
                   9952:     if ($check_students) {
1.276     albertel 9953: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9954: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9955: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9956:         my $start_index = &Apache::loncoursedata::CL_START();
                   9957:         my $end_index = &Apache::loncoursedata::CL_END();
                   9958:         my $status;
1.366     albertel 9959: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9960: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9961: 				                     $data->[$status_index],
                   9962:                                                      $data->[$start_index],
                   9963:                                                      $data->[$end_index]);
                   9964:             if ($stu_status eq 'Active') {
                   9965:                 $status = 'active';
                   9966:             } elsif ($end < $now) {
                   9967:                 $status = 'previous';
                   9968:             } elsif ($start > $now) {
                   9969:                 $status = 'future';
                   9970:             } 
                   9971: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9972:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9973:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9974: 		    $sectioncount{$section}++;
                   9975:                 }
1.240     albertel 9976: 	    }
                   9977: 	}
                   9978:     }
1.1075.2.33  raeburn  9979:     if ($only_students) {
                   9980:         return %sectioncount;
                   9981:     }
1.240     albertel 9982:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9983:     foreach my $user (sort(keys(%courseroles))) {
                   9984: 	if ($user !~ /^(\w{2})/) { next; }
                   9985: 	my ($role) = ($user =~ /^(\w{2})/);
                   9986: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9987: 	my ($section,$status);
1.240     albertel 9988: 	if ($role eq 'cr' &&
                   9989: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9990: 	    $section=$1;
                   9991: 	}
                   9992: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9993: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9994:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9995:         if ($end == -1 && $start == -1) {
                   9996:             next; #deleted role
                   9997:         }
                   9998:         if (!defined($possible_status)) { 
                   9999:             $sectioncount{$section}++;
                   10000:         } else {
                   10001:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10002:                 $status = 'active';
                   10003:             } elsif ($end < $now) {
                   10004:                 $status = 'future';
                   10005:             } elsif ($start > $now) {
                   10006:                 $status = 'previous';
                   10007:             }
                   10008:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10009:                 $sectioncount{$section}++;
                   10010:             }
                   10011:         }
1.233     raeburn  10012:     }
1.366     albertel 10013:     return %sectioncount;
1.233     raeburn  10014: }
                   10015: 
1.274     raeburn  10016: ###############################################
1.294     raeburn  10017: 
                   10018: =pod
1.405     albertel 10019: 
                   10020: =item * &get_course_users()
                   10021: 
1.275     raeburn  10022: Retrieves usernames:domains for users in the specified course
                   10023: with specific role(s), and access status. 
                   10024: 
                   10025: Incoming parameters:
1.277     albertel 10026: 1. course domain
                   10027: 2. course number
                   10028: 3. access status: users must have - either active, 
1.275     raeburn  10029: previous, future, or all.
1.277     albertel 10030: 4. reference to array of permissible roles
1.288     raeburn  10031: 5. reference to array of section restrictions (optional)
                   10032: 6. reference to results object (hash of hashes).
                   10033: 7. reference to optional userdata hash
1.609     raeburn  10034: 8. reference to optional statushash
1.630     raeburn  10035: 9. flag if privileged users (except those set to unhide in
                   10036:    course settings) should be excluded    
1.609     raeburn  10037: Keys of top level results hash are roles.
1.275     raeburn  10038: Keys of inner hashes are username:domain, with 
                   10039: values set to access type.
1.288     raeburn  10040: Optional userdata hash returns an array with arguments in the 
                   10041: same order as loncoursedata::get_classlist() for student data.
                   10042: 
1.609     raeburn  10043: Optional statushash returns
                   10044: 
1.288     raeburn  10045: Entries for end, start, section and status are blank because
                   10046: of the possibility of multiple values for non-student roles.
                   10047: 
1.275     raeburn  10048: =cut
1.405     albertel 10049: 
1.275     raeburn  10050: ###############################################
1.405     albertel 10051: 
1.275     raeburn  10052: sub get_course_users {
1.630     raeburn  10053:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10054:     my %idx = ();
1.419     raeburn  10055:     my %seclists;
1.288     raeburn  10056: 
                   10057:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10058:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10059:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10060:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10061:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10062:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10063:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10064:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10065: 
1.290     albertel 10066:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10067:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10068:         my $now = time;
1.277     albertel 10069:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10070:             my $match = 0;
1.412     raeburn  10071:             my $secmatch = 0;
1.419     raeburn  10072:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10073:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10074:             if ($section eq '') {
                   10075:                 $section = 'none';
                   10076:             }
1.291     albertel 10077:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10078:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10079:                     $secmatch = 1;
                   10080:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 10081:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10082:                         $secmatch = 1;
                   10083:                     }
                   10084:                 } else {  
1.419     raeburn  10085: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  10086: 		        $secmatch = 1;
                   10087:                     }
1.290     albertel 10088: 		}
1.412     raeburn  10089:                 if (!$secmatch) {
                   10090:                     next;
                   10091:                 }
1.419     raeburn  10092:             }
1.275     raeburn  10093:             if (defined($$types{'active'})) {
1.288     raeburn  10094:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  10095:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  10096:                     $match = 1;
1.275     raeburn  10097:                 }
                   10098:             }
                   10099:             if (defined($$types{'previous'})) {
1.609     raeburn  10100:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  10101:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  10102:                     $match = 1;
1.275     raeburn  10103:                 }
                   10104:             }
                   10105:             if (defined($$types{'future'})) {
1.609     raeburn  10106:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  10107:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  10108:                     $match = 1;
1.275     raeburn  10109:                 }
                   10110:             }
1.609     raeburn  10111:             if ($match) {
                   10112:                 push(@{$seclists{$student}},$section);
                   10113:                 if (ref($userdata) eq 'HASH') {
                   10114:                     $$userdata{$student} = $$classlist{$student};
                   10115:                 }
                   10116:                 if (ref($statushash) eq 'HASH') {
                   10117:                     $statushash->{$student}{'st'}{$section} = $status;
                   10118:                 }
1.288     raeburn  10119:             }
1.275     raeburn  10120:         }
                   10121:     }
1.412     raeburn  10122:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  10123:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10124:         my $now = time;
1.609     raeburn  10125:         my %displaystatus = ( previous => 'Expired',
                   10126:                               active   => 'Active',
                   10127:                               future   => 'Future',
                   10128:                             );
1.1075.2.36  raeburn  10129:         my (%nothide,@possdoms);
1.630     raeburn  10130:         if ($hidepriv) {
                   10131:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   10132:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   10133:                 if ($user !~ /:/) {
                   10134:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   10135:                 } else {
                   10136:                     $nothide{$user} = 1;
                   10137:                 }
                   10138:             }
1.1075.2.36  raeburn  10139:             my @possdoms = ($cdom);
                   10140:             if ($coursehash{'checkforpriv'}) {
                   10141:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   10142:             }
1.630     raeburn  10143:         }
1.439     raeburn  10144:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  10145:             my $match = 0;
1.412     raeburn  10146:             my $secmatch = 0;
1.439     raeburn  10147:             my $status;
1.412     raeburn  10148:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  10149:             $user =~ s/:$//;
1.439     raeburn  10150:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   10151:             if ($end == -1 || $start == -1) {
                   10152:                 next;
                   10153:             }
                   10154:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   10155:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  10156:                 my ($uname,$udom) = split(/:/,$user);
                   10157:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 10158:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  10159:                         $secmatch = 1;
                   10160:                     } elsif ($usec eq '') {
1.420     albertel 10161:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  10162:                             $secmatch = 1;
                   10163:                         }
                   10164:                     } else {
                   10165:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   10166:                             $secmatch = 1;
                   10167:                         }
                   10168:                     }
                   10169:                     if (!$secmatch) {
                   10170:                         next;
                   10171:                     }
1.288     raeburn  10172:                 }
1.419     raeburn  10173:                 if ($usec eq '') {
                   10174:                     $usec = 'none';
                   10175:                 }
1.275     raeburn  10176:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  10177:                     if ($hidepriv) {
1.1075.2.36  raeburn  10178:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  10179:                             (!$nothide{$uname.':'.$udom})) {
                   10180:                             next;
                   10181:                         }
                   10182:                     }
1.503     raeburn  10183:                     if ($end > 0 && $end < $now) {
1.439     raeburn  10184:                         $status = 'previous';
                   10185:                     } elsif ($start > $now) {
                   10186:                         $status = 'future';
                   10187:                     } else {
                   10188:                         $status = 'active';
                   10189:                     }
1.277     albertel 10190:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  10191:                         if ($status eq $type) {
1.420     albertel 10192:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  10193:                                 push(@{$$users{$role}{$user}},$type);
                   10194:                             }
1.288     raeburn  10195:                             $match = 1;
                   10196:                         }
                   10197:                     }
1.419     raeburn  10198:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   10199:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   10200: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   10201:                         }
1.420     albertel 10202:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  10203:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   10204:                         }
1.609     raeburn  10205:                         if (ref($statushash) eq 'HASH') {
                   10206:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   10207:                         }
1.275     raeburn  10208:                     }
                   10209:                 }
                   10210:             }
                   10211:         }
1.290     albertel 10212:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  10213:             if ((defined($cdom)) && (defined($cnum))) {
                   10214:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   10215:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   10216:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  10217:                     next if ($owner eq '');
                   10218:                     my ($ownername,$ownerdom);
                   10219:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   10220:                         $ownername = $1;
                   10221:                         $ownerdom = $2;
                   10222:                     } else {
                   10223:                         $ownername = $owner;
                   10224:                         $ownerdom = $cdom;
                   10225:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  10226:                     }
                   10227:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 10228:                     if (defined($userdata) && 
1.609     raeburn  10229: 			!exists($$userdata{$owner})) {
                   10230: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   10231:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   10232:                             push(@{$seclists{$owner}},'none');
                   10233:                         }
                   10234:                         if (ref($statushash) eq 'HASH') {
                   10235:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  10236:                         }
1.290     albertel 10237: 		    }
1.279     raeburn  10238:                 }
                   10239:             }
                   10240:         }
1.419     raeburn  10241:         foreach my $user (keys(%seclists)) {
                   10242:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   10243:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   10244:         }
1.275     raeburn  10245:     }
                   10246:     return;
                   10247: }
                   10248: 
1.288     raeburn  10249: sub get_user_info {
                   10250:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 10251:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   10252: 	&plainname($uname,$udom,'lastname');
1.291     albertel 10253:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  10254:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  10255:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   10256:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  10257:     return;
                   10258: }
1.275     raeburn  10259: 
1.472     raeburn  10260: ###############################################
                   10261: 
                   10262: =pod
                   10263: 
                   10264: =item * &get_user_quota()
                   10265: 
1.1075.2.41  raeburn  10266: Retrieves quota assigned for storage of user files.
                   10267: Default is to report quota for portfolio files.
1.472     raeburn  10268: 
                   10269: Incoming parameters:
                   10270: 1. user's username
                   10271: 2. user's domain
1.1075.2.41  raeburn  10272: 3. quota name - portfolio, author, or course
                   10273:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  10274: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  10275:    course
1.472     raeburn  10276: 
                   10277: Returns:
1.1075.2.58  raeburn  10278: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  10279: 2. (Optional) Type of setting: custom or default
                   10280:    (individually assigned or default for user's 
                   10281:    institutional status).
                   10282: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   10283:    or student - types as defined in localenroll::inst_usertypes 
                   10284:    for user's domain, which determines default quota for user.
                   10285: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  10286: 
                   10287: If a value has been stored in the user's environment, 
1.536     raeburn  10288: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  10289: defined for the user's institutional status(es) in the domain.
1.472     raeburn  10290: 
                   10291: =cut
                   10292: 
                   10293: ###############################################
                   10294: 
                   10295: 
                   10296: sub get_user_quota {
1.1075.2.42  raeburn  10297:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  10298:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  10299:     if (!defined($udom)) {
                   10300:         $udom = $env{'user.domain'};
                   10301:     }
                   10302:     if (!defined($uname)) {
                   10303:         $uname = $env{'user.name'};
                   10304:     }
                   10305:     if (($udom eq '' || $uname eq '') ||
                   10306:         ($udom eq 'public') && ($uname eq 'public')) {
                   10307:         $quota = 0;
1.536     raeburn  10308:         $quotatype = 'default';
                   10309:         $defquota = 0; 
1.472     raeburn  10310:     } else {
1.536     raeburn  10311:         my $inststatus;
1.1075.2.41  raeburn  10312:         if ($quotaname eq 'course') {
                   10313:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   10314:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   10315:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   10316:             } else {
                   10317:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   10318:                 $quota = $cenv{'internal.uploadquota'};
                   10319:             }
1.536     raeburn  10320:         } else {
1.1075.2.41  raeburn  10321:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   10322:                 if ($quotaname eq 'author') {
                   10323:                     $quota = $env{'environment.authorquota'};
                   10324:                 } else {
                   10325:                     $quota = $env{'environment.portfolioquota'};
                   10326:                 }
                   10327:                 $inststatus = $env{'environment.inststatus'};
                   10328:             } else {
                   10329:                 my %userenv = 
                   10330:                     &Apache::lonnet::get('environment',['portfolioquota',
                   10331:                                          'authorquota','inststatus'],$udom,$uname);
                   10332:                 my ($tmp) = keys(%userenv);
                   10333:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   10334:                     if ($quotaname eq 'author') {
                   10335:                         $quota = $userenv{'authorquota'};
                   10336:                     } else {
                   10337:                         $quota = $userenv{'portfolioquota'};
                   10338:                     }
                   10339:                     $inststatus = $userenv{'inststatus'};
                   10340:                 } else {
                   10341:                     undef(%userenv);
                   10342:                 }
                   10343:             }
                   10344:         }
                   10345:         if ($quota eq '' || wantarray) {
                   10346:             if ($quotaname eq 'course') {
                   10347:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  10348:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   10349:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  10350:                     $defquota = $domdefs{$crstype.'quota'};
                   10351:                 }
                   10352:                 if ($defquota eq '') {
                   10353:                     $defquota = 500;
                   10354:                 }
1.1075.2.41  raeburn  10355:             } else {
                   10356:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   10357:             }
                   10358:             if ($quota eq '') {
                   10359:                 $quota = $defquota;
                   10360:                 $quotatype = 'default';
                   10361:             } else {
                   10362:                 $quotatype = 'custom';
                   10363:             }
1.472     raeburn  10364:         }
                   10365:     }
1.536     raeburn  10366:     if (wantarray) {
                   10367:         return ($quota,$quotatype,$settingstatus,$defquota);
                   10368:     } else {
                   10369:         return $quota;
                   10370:     }
1.472     raeburn  10371: }
                   10372: 
                   10373: ###############################################
                   10374: 
                   10375: =pod
                   10376: 
                   10377: =item * &default_quota()
                   10378: 
1.536     raeburn  10379: Retrieves default quota assigned for storage of user portfolio files,
                   10380: given an (optional) user's institutional status.
1.472     raeburn  10381: 
                   10382: Incoming parameters:
1.1075.2.42  raeburn  10383: 
1.472     raeburn  10384: 1. domain
1.536     raeburn  10385: 2. (Optional) institutional status(es).  This is a : separated list of 
                   10386:    status types (e.g., faculty, staff, student etc.)
                   10387:    which apply to the user for whom the default is being retrieved.
                   10388:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  10389:    default quota will be returned.
                   10390: 3.  quota name - portfolio, author, or course
                   10391:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  10392: 
                   10393: Returns:
1.1075.2.42  raeburn  10394: 
1.1075.2.58  raeburn  10395: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  10396: 2. (Optional) institutional type which determined the value of the
                   10397:    default quota.
1.472     raeburn  10398: 
                   10399: If a value has been stored in the domain's configuration db,
                   10400: it will return that, otherwise it returns 20 (for backwards 
                   10401: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  10402: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  10403: 
1.536     raeburn  10404: If the user's status includes multiple types (e.g., staff and student),
                   10405: the largest default quota which applies to the user determines the
                   10406: default quota returned.
                   10407: 
1.472     raeburn  10408: =cut
                   10409: 
                   10410: ###############################################
                   10411: 
                   10412: 
                   10413: sub default_quota {
1.1075.2.41  raeburn  10414:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  10415:     my ($defquota,$settingstatus);
                   10416:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  10417:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  10418:     my $key = 'defaultquota';
                   10419:     if ($quotaname eq 'author') {
                   10420:         $key = 'authorquota';
                   10421:     }
1.622     raeburn  10422:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  10423:         if ($inststatus ne '') {
1.765     raeburn  10424:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  10425:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  10426:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10427:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  10428:                         if ($defquota eq '') {
1.1075.2.41  raeburn  10429:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10430:                             $settingstatus = $item;
1.1075.2.41  raeburn  10431:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   10432:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  10433:                             $settingstatus = $item;
                   10434:                         }
                   10435:                     }
1.1075.2.41  raeburn  10436:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  10437:                     if ($quotahash{'quotas'}{$item} ne '') {
                   10438:                         if ($defquota eq '') {
                   10439:                             $defquota = $quotahash{'quotas'}{$item};
                   10440:                             $settingstatus = $item;
                   10441:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   10442:                             $defquota = $quotahash{'quotas'}{$item};
                   10443:                             $settingstatus = $item;
                   10444:                         }
1.536     raeburn  10445:                     }
                   10446:                 }
                   10447:             }
                   10448:         }
                   10449:         if ($defquota eq '') {
1.1075.2.41  raeburn  10450:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   10451:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   10452:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  10453:                 $defquota = $quotahash{'quotas'}{'default'};
                   10454:             }
1.536     raeburn  10455:             $settingstatus = 'default';
1.1075.2.42  raeburn  10456:             if ($defquota eq '') {
                   10457:                 if ($quotaname eq 'author') {
                   10458:                     $defquota = 500;
                   10459:                 }
                   10460:             }
1.536     raeburn  10461:         }
                   10462:     } else {
                   10463:         $settingstatus = 'default';
1.1075.2.41  raeburn  10464:         if ($quotaname eq 'author') {
                   10465:             $defquota = 500;
                   10466:         } else {
                   10467:             $defquota = 20;
                   10468:         }
1.536     raeburn  10469:     }
                   10470:     if (wantarray) {
                   10471:         return ($defquota,$settingstatus);
1.472     raeburn  10472:     } else {
1.536     raeburn  10473:         return $defquota;
1.472     raeburn  10474:     }
                   10475: }
                   10476: 
1.1075.2.41  raeburn  10477: ###############################################
                   10478: 
                   10479: =pod
                   10480: 
1.1075.2.42  raeburn  10481: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  10482: 
                   10483: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  10484: of existing file within authoring space will cause quota for the authoring
                   10485: space to be exceeded.
                   10486: 
                   10487: Same, if upload of a file directly to a course/community via Course Editor
                   10488: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  10489: 
1.1075.2.61  raeburn  10490: Inputs: 7 
1.1075.2.42  raeburn  10491: 1. username or coursenum
1.1075.2.41  raeburn  10492: 2. domain
1.1075.2.42  raeburn  10493: 3. context ('author' or 'course')
1.1075.2.41  raeburn  10494: 4. filename of file for which action is being requested
                   10495: 5. filesize (kB) of file
                   10496: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  10497: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  10498: 
                   10499: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   10500:          otherwise return null.
                   10501: 
1.1075.2.42  raeburn  10502: =back
                   10503: 
1.1075.2.41  raeburn  10504: =cut
                   10505: 
1.1075.2.42  raeburn  10506: sub excess_filesize_warning {
1.1075.2.59  raeburn  10507:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  10508:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  10509:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  10510:     if ($context eq 'author') {
                   10511:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   10512:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   10513:     } else {
                   10514:         foreach my $subdir ('docs','supplemental') {
                   10515:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   10516:         }
                   10517:     }
1.1075.2.41  raeburn  10518:     $disk_quota = int($disk_quota * 1000);
                   10519:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  10520:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  10521:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  10522:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   10523:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  10524:                             $disk_quota,$current_disk_usage).
                   10525:                '</p>';
                   10526:     }
                   10527:     return;
                   10528: }
                   10529: 
                   10530: ###############################################
                   10531: 
                   10532: 
1.384     raeburn  10533: sub get_secgrprole_info {
                   10534:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   10535:     my %sections_count = &get_sections($cdom,$cnum);
                   10536:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   10537:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   10538:     my @groups = sort(keys(%curr_groups));
                   10539:     my $allroles = [];
                   10540:     my $rolehash;
                   10541:     my $accesshash = {
                   10542:                      active => 'Currently has access',
                   10543:                      future => 'Will have future access',
                   10544:                      previous => 'Previously had access',
                   10545:                   };
                   10546:     if ($needroles) {
                   10547:         $rolehash = {'all' => 'all'};
1.385     albertel 10548:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10549: 	if (&Apache::lonnet::error(%user_roles)) {
                   10550: 	    undef(%user_roles);
                   10551: 	}
                   10552:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  10553:             my ($role)=split(/\:/,$item,2);
                   10554:             if ($role eq 'cr') { next; }
                   10555:             if ($role =~ /^cr/) {
                   10556:                 $$rolehash{$role} = (split('/',$role))[3];
                   10557:             } else {
                   10558:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   10559:             }
                   10560:         }
                   10561:         foreach my $key (sort(keys(%{$rolehash}))) {
                   10562:             push(@{$allroles},$key);
                   10563:         }
                   10564:         push (@{$allroles},'st');
                   10565:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   10566:     }
                   10567:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   10568: }
                   10569: 
1.555     raeburn  10570: sub user_picker {
1.1075.2.127  raeburn  10571:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  10572:     my $currdom = $dom;
1.1075.2.114  raeburn  10573:     my @alldoms = &Apache::lonnet::all_domains();
                   10574:     if (@alldoms == 1) {
                   10575:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   10576:                                                ['directorysrch'],$alldoms[0]);
                   10577:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   10578:         my $showdom = $domdesc;
                   10579:         if ($showdom eq '') {
                   10580:             $showdom = $dom;
                   10581:         }
                   10582:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   10583:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   10584:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   10585:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   10586:             }
                   10587:         }
                   10588:     }
1.555     raeburn  10589:     my %curr_selected = (
                   10590:                         srchin => 'dom',
1.580     raeburn  10591:                         srchby => 'lastname',
1.555     raeburn  10592:                       );
                   10593:     my $srchterm;
1.625     raeburn  10594:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  10595:         if ($srch->{'srchby'} ne '') {
                   10596:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   10597:         }
                   10598:         if ($srch->{'srchin'} ne '') {
                   10599:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   10600:         }
                   10601:         if ($srch->{'srchtype'} ne '') {
                   10602:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   10603:         }
                   10604:         if ($srch->{'srchdomain'} ne '') {
                   10605:             $currdom = $srch->{'srchdomain'};
                   10606:         }
                   10607:         $srchterm = $srch->{'srchterm'};
                   10608:     }
1.1075.2.98  raeburn  10609:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  10610:                     'usr'       => 'Search criteria',
1.563     raeburn  10611:                     'doma'      => 'Domain/institution to search',
1.558     albertel 10612:                     'uname'     => 'username',
                   10613:                     'lastname'  => 'last name',
1.555     raeburn  10614:                     'lastfirst' => 'last name, first name',
1.558     albertel 10615:                     'crs'       => 'in this course',
1.576     raeburn  10616:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 10617:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  10618:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 10619:                     'exact'     => 'is',
                   10620:                     'contains'  => 'contains',
1.569     raeburn  10621:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  10622:                                        );
                   10623:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  10624:                     'youm'      => "You must include some text to search for.",
                   10625:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   10626:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   10627:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   10628:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   10629:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   10630:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   10631:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  10632:                                        );
1.1075.2.98  raeburn  10633:     &html_escape(\%html_lt);
                   10634:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  10635:     my $domform;
1.1075.2.126  raeburn  10636:     my $allow_blank = 1;
1.1075.2.115  raeburn  10637:     if ($fixeddom) {
1.1075.2.126  raeburn  10638:         $allow_blank = 0;
                   10639:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  10640:     } else {
1.1075.2.126  raeburn  10641:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  10642:     }
1.563     raeburn  10643:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  10644: 
                   10645:     my @srchins = ('crs','dom','alc','instd');
                   10646: 
                   10647:     foreach my $option (@srchins) {
                   10648:         # FIXME 'alc' option unavailable until 
                   10649:         #       loncreateuser::print_user_query_page()
                   10650:         #       has been completed.
                   10651:         next if ($option eq 'alc');
1.880     raeburn  10652:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  10653:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  10654:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  10655:         if ($curr_selected{'srchin'} eq $option) {
                   10656:             $srchinsel .= ' 
1.1075.2.98  raeburn  10657:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  10658:         } else {
                   10659:             $srchinsel .= '
1.1075.2.98  raeburn  10660:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  10661:         }
1.555     raeburn  10662:     }
1.563     raeburn  10663:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  10664: 
                   10665:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  10666:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  10667:         if ($curr_selected{'srchby'} eq $option) {
                   10668:             $srchbysel .= '
1.1075.2.98  raeburn  10669:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10670:         } else {
                   10671:             $srchbysel .= '
1.1075.2.98  raeburn  10672:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10673:          }
                   10674:     }
                   10675:     $srchbysel .= "\n  </select>\n";
                   10676: 
                   10677:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  10678:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  10679:         if ($curr_selected{'srchtype'} eq $option) {
                   10680:             $srchtypesel .= '
1.1075.2.98  raeburn  10681:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  10682:         } else {
                   10683:             $srchtypesel .= '
1.1075.2.98  raeburn  10684:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  10685:         }
                   10686:     }
                   10687:     $srchtypesel .= "\n  </select>\n";
                   10688: 
1.558     albertel 10689:     my ($newuserscript,$new_user_create);
1.994     raeburn  10690:     my $context_dom = $env{'request.role.domain'};
                   10691:     if ($context eq 'requestcrs') {
                   10692:         if ($env{'form.coursedom'} ne '') { 
                   10693:             $context_dom = $env{'form.coursedom'};
                   10694:         }
                   10695:     }
1.556     raeburn  10696:     if ($forcenewuser) {
1.576     raeburn  10697:         if (ref($srch) eq 'HASH') {
1.994     raeburn  10698:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  10699:                 if ($cancreate) {
                   10700:                     $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>';
                   10701:                 } else {
1.799     bisitz   10702:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  10703:                     my %usertypetext = (
                   10704:                         official   => 'institutional',
                   10705:                         unofficial => 'non-institutional',
                   10706:                     );
1.799     bisitz   10707:                     $new_user_create = '<p class="LC_warning">'
                   10708:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   10709:                                       .' '
                   10710:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   10711:                                           ,'<a href="'.$helplink.'">','</a>')
                   10712:                                       .'</p><br />';
1.627     raeburn  10713:                 }
1.576     raeburn  10714:             }
                   10715:         }
                   10716: 
1.556     raeburn  10717:         $newuserscript = <<"ENDSCRIPT";
                   10718: 
1.570     raeburn  10719: function setSearch(createnew,callingForm) {
1.556     raeburn  10720:     if (createnew == 1) {
1.570     raeburn  10721:         for (var i=0; i<callingForm.srchby.length; i++) {
                   10722:             if (callingForm.srchby.options[i].value == 'uname') {
                   10723:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  10724:             }
                   10725:         }
1.570     raeburn  10726:         for (var i=0; i<callingForm.srchin.length; i++) {
                   10727:             if ( callingForm.srchin.options[i].value == 'dom') {
                   10728: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  10729:             }
                   10730:         }
1.570     raeburn  10731:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   10732:             if (callingForm.srchtype.options[i].value == 'exact') {
                   10733:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  10734:             }
                   10735:         }
1.570     raeburn  10736:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  10737:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  10738:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  10739:             }
                   10740:         }
                   10741:     }
                   10742: }
                   10743: ENDSCRIPT
1.558     albertel 10744: 
1.556     raeburn  10745:     }
                   10746: 
1.555     raeburn  10747:     my $output = <<"END_BLOCK";
1.556     raeburn  10748: <script type="text/javascript">
1.824     bisitz   10749: // <![CDATA[
1.570     raeburn  10750: function validateEntry(callingForm) {
1.558     albertel 10751: 
1.556     raeburn  10752:     var checkok = 1;
1.558     albertel 10753:     var srchin;
1.570     raeburn  10754:     for (var i=0; i<callingForm.srchin.length; i++) {
                   10755: 	if ( callingForm.srchin[i].checked ) {
                   10756: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 10757: 	}
                   10758:     }
                   10759: 
1.570     raeburn  10760:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   10761:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   10762:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   10763:     var srchterm =  callingForm.srchterm.value;
                   10764:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  10765:     var msg = "";
                   10766: 
                   10767:     if (srchterm == "") {
                   10768:         checkok = 0;
1.1075.2.98  raeburn  10769:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  10770:     }
                   10771: 
1.569     raeburn  10772:     if (srchtype== 'begins') {
                   10773:         if (srchterm.length < 2) {
                   10774:             checkok = 0;
1.1075.2.98  raeburn  10775:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  10776:         }
                   10777:     }
                   10778: 
1.556     raeburn  10779:     if (srchtype== 'contains') {
                   10780:         if (srchterm.length < 3) {
                   10781:             checkok = 0;
1.1075.2.98  raeburn  10782:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  10783:         }
                   10784:     }
                   10785:     if (srchin == 'instd') {
                   10786:         if (srchdomain == '') {
                   10787:             checkok = 0;
1.1075.2.98  raeburn  10788:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  10789:         }
                   10790:     }
                   10791:     if (srchin == 'dom') {
                   10792:         if (srchdomain == '') {
                   10793:             checkok = 0;
1.1075.2.98  raeburn  10794:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  10795:         }
                   10796:     }
                   10797:     if (srchby == 'lastfirst') {
                   10798:         if (srchterm.indexOf(",") == -1) {
                   10799:             checkok = 0;
1.1075.2.98  raeburn  10800:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  10801:         }
                   10802:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   10803:             checkok = 0;
1.1075.2.98  raeburn  10804:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  10805:         }
                   10806:     }
                   10807:     if (checkok == 0) {
1.1075.2.98  raeburn  10808:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  10809:         return;
                   10810:     }
                   10811:     if (checkok == 1) {
1.570     raeburn  10812:         callingForm.submit();
1.556     raeburn  10813:     }
                   10814: }
                   10815: 
                   10816: $newuserscript
                   10817: 
1.824     bisitz   10818: // ]]>
1.556     raeburn  10819: </script>
1.558     albertel 10820: 
                   10821: $new_user_create
                   10822: 
1.555     raeburn  10823: END_BLOCK
1.558     albertel 10824: 
1.876     raeburn  10825:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  10826:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  10827:                $domform.
                   10828:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  10829:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  10830:                $srchbysel.
                   10831:                $srchtypesel. 
                   10832:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   10833:                $srchinsel.
                   10834:                &Apache::lonhtmlcommon::row_closure(1). 
                   10835:                &Apache::lonhtmlcommon::end_pick_box().
                   10836:                '<br />';
1.1075.2.114  raeburn  10837:     return ($output,1);
1.555     raeburn  10838: }
                   10839: 
1.612     raeburn  10840: sub user_rule_check {
1.615     raeburn  10841:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  10842:     my ($response,%inst_response);
1.612     raeburn  10843:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  10844:         if (keys(%{$usershash}) > 1) {
                   10845:             my (%by_username,%by_id,%userdoms);
                   10846:             my $checkid;
1.612     raeburn  10847:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  10848:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   10849:                     $checkid = 1;
                   10850:                 }
                   10851:             }
                   10852:             foreach my $user (keys(%{$usershash})) {
                   10853:                 my ($uname,$udom) = split(/:/,$user);
                   10854:                 if ($checkid) {
                   10855:                     if (ref($usershash->{$user}) eq 'HASH') {
                   10856:                         if ($usershash->{$user}->{'id'} ne '') {
                   10857:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   10858:                             $userdoms{$udom} = 1;
                   10859:                             if (ref($inst_results) eq 'HASH') {
                   10860:                                 $inst_results->{$uname.':'.$udom} = {};
                   10861:                             }
                   10862:                         }
                   10863:                     }
                   10864:                 } else {
                   10865:                     $by_username{$udom}{$uname} = 1;
                   10866:                     $userdoms{$udom} = 1;
                   10867:                     if (ref($inst_results) eq 'HASH') {
                   10868:                         $inst_results->{$uname.':'.$udom} = {};
                   10869:                     }
                   10870:                 }
                   10871:             }
                   10872:             foreach my $udom (keys(%userdoms)) {
                   10873:                 if (!$got_rules->{$udom}) {
                   10874:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10875:                                                              ['usercreation'],$udom);
                   10876:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10877:                         foreach my $item ('username','id') {
                   10878:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10879:                                 $$curr_rules{$udom}{$item} =
                   10880:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   10881:                             }
                   10882:                         }
                   10883:                     }
                   10884:                     $got_rules->{$udom} = 1;
                   10885:                 }
                   10886:             }
                   10887:             if ($checkid) {
                   10888:                 foreach my $udom (keys(%by_id)) {
                   10889:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   10890:                     if ($outcome eq 'ok') {
                   10891:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   10892:                             my $uname = $by_id{$udom}{$id};
                   10893:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10894:                         }
                   10895:                         if (ref($results) eq 'HASH') {
                   10896:                             foreach my $uname (keys(%{$results})) {
                   10897:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   10898:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   10899:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10900:                                 }
                   10901:                             }
                   10902:                         }
                   10903:                     }
1.612     raeburn  10904:                 }
1.615     raeburn  10905:             } else {
1.1075.2.99  raeburn  10906:                 foreach my $udom (keys(%by_username)) {
                   10907:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   10908:                     if ($outcome eq 'ok') {
                   10909:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   10910:                             $inst_response{$uname.':'.$udom} = $outcome;
                   10911:                         }
                   10912:                         if (ref($results) eq 'HASH') {
                   10913:                             foreach my $uname (keys(%{$results})) {
                   10914:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   10915:                             }
                   10916:                         }
                   10917:                     }
                   10918:                 }
1.612     raeburn  10919:             }
1.1075.2.99  raeburn  10920:         } elsif (keys(%{$usershash}) == 1) {
                   10921:             my $user = (keys(%{$usershash}))[0];
                   10922:             my ($uname,$udom) = split(/:/,$user);
                   10923:             if (($udom ne '') && ($uname ne '')) {
                   10924:                 if (ref($usershash->{$user}) eq 'HASH') {
                   10925:                     if (ref($checks) eq 'HASH') {
                   10926:                         if (defined($checks->{'username'})) {
                   10927:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   10928:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   10929:                         } elsif (defined($checks->{'id'})) {
                   10930:                             if ($usershash->{$user}->{'id'} ne '') {
                   10931:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10932:                                     &Apache::lonnet::get_instuser($udom,undef,
                   10933:                                                                   $usershash->{$user}->{'id'});
                   10934:                             } else {
                   10935:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10936:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10937:                             }
                   10938:                         }
                   10939:                     } else {
                   10940:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10941:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10942:                        return;
                   10943:                     }
                   10944:                     if (!$got_rules->{$udom}) {
                   10945:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10946:                                                                  ['usercreation'],$udom);
                   10947:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10948:                             foreach my $item ('username','id') {
                   10949:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10950:                                    $$curr_rules{$udom}{$item} =
                   10951:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10952:                                 }
                   10953:                             }
1.585     raeburn  10954:                         }
1.1075.2.99  raeburn  10955:                         $got_rules->{$udom} = 1;
1.585     raeburn  10956:                     }
                   10957:                 }
1.1075.2.99  raeburn  10958:             } else {
                   10959:                 return;
                   10960:             }
                   10961:         } else {
                   10962:             return;
                   10963:         }
                   10964:         foreach my $user (keys(%{$usershash})) {
                   10965:             my ($uname,$udom) = split(/:/,$user);
                   10966:             next if (($udom eq '') || ($uname eq ''));
                   10967:             my $id;
                   10968:             if (ref($inst_results) eq 'HASH') {
                   10969:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10970:                     $id = $inst_results->{$user}->{'id'};
                   10971:                 }
                   10972:             }
                   10973:             if ($id eq '') {
                   10974:                 if (ref($usershash->{$user})) {
                   10975:                     $id = $usershash->{$user}->{'id'};
                   10976:                 }
1.585     raeburn  10977:             }
1.612     raeburn  10978:             foreach my $item (keys(%{$checks})) {
                   10979:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10980:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10981:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10982:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10983:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10984:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10985:                                 if ($rule_check{$rule}) {
                   10986:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10987:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10988:                                         if (ref($inst_results) eq 'HASH') {
                   10989:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10990:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10991:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10992:                                                 } elsif ($item eq 'id') {
                   10993:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10994:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10995:                                                     }
1.615     raeburn  10996:                                                 }
1.612     raeburn  10997:                                             }
                   10998:                                         }
1.615     raeburn  10999:                                     }
                   11000:                                     last;
1.585     raeburn  11001:                                 }
                   11002:                             }
                   11003:                         }
                   11004:                     }
                   11005:                 }
                   11006:             }
                   11007:         }
                   11008:     }
1.612     raeburn  11009:     return;
                   11010: }
                   11011: 
                   11012: sub user_rule_formats {
                   11013:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11014:     my %text = ( 
                   11015:                  'username' => 'Usernames',
                   11016:                  'id'       => 'IDs',
                   11017:                );
                   11018:     my $output;
                   11019:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11020:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11021:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  11022:             $output = '<br />'.
                   11023:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11024:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11025:                       ' <ul>';
1.612     raeburn  11026:             foreach my $rule (@{$ruleorder}) {
                   11027:                 if (ref($curr_rules) eq 'ARRAY') {
                   11028:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11029:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11030:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11031:                                         $rules->{$rule}{'desc'}.'</li>';
                   11032:                         }
                   11033:                     }
                   11034:                 }
                   11035:             }
                   11036:             $output .= '</ul>';
                   11037:         }
                   11038:     }
                   11039:     return $output;
                   11040: }
                   11041: 
                   11042: sub instrule_disallow_msg {
1.615     raeburn  11043:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11044:     my $response;
                   11045:     my %text = (
                   11046:                   item   => 'username',
                   11047:                   items  => 'usernames',
                   11048:                   match  => 'matches',
                   11049:                   do     => 'does',
                   11050:                   action => 'a username',
                   11051:                   one    => 'one',
                   11052:                );
                   11053:     if ($count > 1) {
                   11054:         $text{'item'} = 'usernames';
                   11055:         $text{'match'} ='match';
                   11056:         $text{'do'} = 'do';
                   11057:         $text{'action'} = 'usernames',
                   11058:         $text{'one'} = 'ones';
                   11059:     }
                   11060:     if ($checkitem eq 'id') {
                   11061:         $text{'items'} = 'IDs';
                   11062:         $text{'item'} = 'ID';
                   11063:         $text{'action'} = 'an ID';
1.615     raeburn  11064:         if ($count > 1) {
                   11065:             $text{'item'} = 'IDs';
                   11066:             $text{'action'} = 'IDs';
                   11067:         }
1.612     raeburn  11068:     }
1.674     bisitz   11069:     $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  11070:     if ($mode eq 'upload') {
                   11071:         if ($checkitem eq 'username') {
                   11072:             $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'}.");
                   11073:         } elsif ($checkitem eq 'id') {
1.674     bisitz   11074:             $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  11075:         }
1.669     raeburn  11076:     } elsif ($mode eq 'selfcreate') {
                   11077:         if ($checkitem eq 'id') {
                   11078:             $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.");
                   11079:         }
1.615     raeburn  11080:     } else {
                   11081:         if ($checkitem eq 'username') {
                   11082:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   11083:         } elsif ($checkitem eq 'id') {
                   11084:             $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.");
                   11085:         }
1.612     raeburn  11086:     }
                   11087:     return $response;
1.585     raeburn  11088: }
                   11089: 
1.624     raeburn  11090: sub personal_data_fieldtitles {
                   11091:     my %fieldtitles = &Apache::lonlocal::texthash (
                   11092:                         id => 'Student/Employee ID',
                   11093:                         permanentemail => 'E-mail address',
                   11094:                         lastname => 'Last Name',
                   11095:                         firstname => 'First Name',
                   11096:                         middlename => 'Middle Name',
                   11097:                         generation => 'Generation',
                   11098:                         gen => 'Generation',
1.765     raeburn  11099:                         inststatus => 'Affiliation',
1.624     raeburn  11100:                    );
                   11101:     return %fieldtitles;
                   11102: }
                   11103: 
1.642     raeburn  11104: sub sorted_inst_types {
                   11105:     my ($dom) = @_;
1.1075.2.70  raeburn  11106:     my ($usertypes,$order);
                   11107:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   11108:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   11109:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   11110:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   11111:     } else {
                   11112:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   11113:     }
1.642     raeburn  11114:     my $othertitle = &mt('All users');
                   11115:     if ($env{'request.course.id'}) {
1.668     raeburn  11116:         $othertitle  = &mt('Any users');
1.642     raeburn  11117:     }
                   11118:     my @types;
                   11119:     if (ref($order) eq 'ARRAY') {
                   11120:         @types = @{$order};
                   11121:     }
                   11122:     if (@types == 0) {
                   11123:         if (ref($usertypes) eq 'HASH') {
                   11124:             @types = sort(keys(%{$usertypes}));
                   11125:         }
                   11126:     }
                   11127:     if (keys(%{$usertypes}) > 0) {
                   11128:         $othertitle = &mt('Other users');
                   11129:     }
                   11130:     return ($othertitle,$usertypes,\@types);
                   11131: }
                   11132: 
1.645     raeburn  11133: sub get_institutional_codes {
1.1075.2.157  raeburn  11134:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  11135: # Get complete list of course sections to update
                   11136:     my @currsections = ();
                   11137:     my @currxlists = ();
1.1075.2.157  raeburn  11138:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  11139:     my $coursecode = $$settings{'internal.coursecode'};
1.1075.2.157  raeburn  11140:     my $crskey = $crs.':'.$coursecode;
                   11141:     @{$unclutteredsec{$crskey}} = ();
                   11142:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  11143: 
                   11144:     if ($$settings{'internal.sectionnums'} ne '') {
                   11145:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   11146:     }
                   11147: 
                   11148:     if ($$settings{'internal.crosslistings'} ne '') {
                   11149:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   11150:     }
                   11151: 
                   11152:     if (@currxlists > 0) {
1.1075.2.157  raeburn  11153:         foreach my $xl (@currxlists) {
                   11154:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  11155:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  11156:                     push(@{$allcourses},$1);
1.645     raeburn  11157:                     $$LC_code{$1} = $2;
                   11158:                 }
                   11159:             }
                   11160:         }
                   11161:     }
1.1075.2.157  raeburn  11162: 
1.645     raeburn  11163:     if (@currsections > 0) {
1.1075.2.157  raeburn  11164:         foreach my $sec (@currsections) {
                   11165:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   11166:                 my $instsec = $1;
1.645     raeburn  11167:                 my $lc_sec = $2;
1.1075.2.157  raeburn  11168:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   11169:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   11170:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   11171:                 }
                   11172:             }
                   11173:         }
                   11174:     }
                   11175: 
                   11176:     if (@{$unclutteredsec{$crskey}} > 0) {
                   11177:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   11178:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   11179:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   11180:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   11181:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1075.2.119  raeburn  11182:                     push(@{$allcourses},$sec);
1.1075.2.157  raeburn  11183:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  11184:                 }
                   11185:             }
                   11186:         }
                   11187:     }
                   11188:     return;
                   11189: }
                   11190: 
1.971     raeburn  11191: sub get_standard_codeitems {
                   11192:     return ('Year','Semester','Department','Number','Section');
                   11193: }
                   11194: 
1.112     bowersj2 11195: =pod
                   11196: 
1.780     raeburn  11197: =head1 Slot Helpers
                   11198: 
                   11199: =over 4
                   11200: 
                   11201: =item * sorted_slots()
                   11202: 
1.1040    raeburn  11203: Sorts an array of slot names in order of an optional sort key,
                   11204: default sort is by slot start time (earliest first). 
1.780     raeburn  11205: 
                   11206: Inputs:
                   11207: 
                   11208: =over 4
                   11209: 
                   11210: slotsarr  - Reference to array of unsorted slot names.
                   11211: 
                   11212: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   11213: 
1.1040    raeburn  11214: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   11215: 
1.549     albertel 11216: =back
                   11217: 
1.780     raeburn  11218: Returns:
                   11219: 
                   11220: =over 4
                   11221: 
1.1040    raeburn  11222: sorted   - An array of slot names sorted by a specified sort key 
                   11223:            (default sort key is start time of the slot).
1.780     raeburn  11224: 
                   11225: =back
                   11226: 
                   11227: =cut
                   11228: 
                   11229: 
                   11230: sub sorted_slots {
1.1040    raeburn  11231:     my ($slotsarr,$slots,$sortkey) = @_;
                   11232:     if ($sortkey eq '') {
                   11233:         $sortkey = 'starttime';
                   11234:     }
1.780     raeburn  11235:     my @sorted;
                   11236:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   11237:         @sorted =
                   11238:             sort {
                   11239:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  11240:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  11241:                      }
                   11242:                      if (ref($slots->{$a})) { return -1;}
                   11243:                      if (ref($slots->{$b})) { return 1;}
                   11244:                      return 0;
                   11245:                  } @{$slotsarr};
                   11246:     }
                   11247:     return @sorted;
                   11248: }
                   11249: 
1.1040    raeburn  11250: =pod
                   11251: 
                   11252: =item * get_future_slots()
                   11253: 
                   11254: Inputs:
                   11255: 
                   11256: =over 4
                   11257: 
                   11258: cnum - course number
                   11259: 
                   11260: cdom - course domain
                   11261: 
                   11262: now - current UNIX time
                   11263: 
                   11264: symb - optional symb
                   11265: 
                   11266: =back
                   11267: 
                   11268: Returns:
                   11269: 
                   11270: =over 4
                   11271: 
                   11272: sorted_reservable - ref to array of student_schedulable slots currently 
                   11273:                     reservable, ordered by end date of reservation period.
                   11274: 
                   11275: reservable_now - ref to hash of student_schedulable slots currently
                   11276:                  reservable.
                   11277: 
                   11278:     Keys in inner hash are:
                   11279:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  11280:     (b) endreserve: end date of reservation period.
                   11281:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11282:         selected.
1.1040    raeburn  11283: 
                   11284: sorted_future - ref to array of student_schedulable slots reservable in
                   11285:                 the future, ordered by start date of reservation period.
                   11286: 
                   11287: future_reservable - ref to hash of student_schedulable slots reservable
                   11288:                     in the future.
                   11289: 
                   11290:     Keys in inner hash are:
                   11291:     (a) symb: either blank or symb to which slot use is restricted.
                   11292:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  11293:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   11294:         selected.
1.1040    raeburn  11295: 
                   11296: =back
                   11297: 
                   11298: =cut
                   11299: 
                   11300: sub get_future_slots {
                   11301:     my ($cnum,$cdom,$now,$symb) = @_;
                   11302:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   11303:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   11304:     foreach my $slot (keys(%slots)) {
                   11305:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   11306:         if ($symb) {
                   11307:             next if (($slots{$slot}->{'symb'} ne '') && 
                   11308:                      ($slots{$slot}->{'symb'} ne $symb));
                   11309:         }
                   11310:         if (($slots{$slot}->{'starttime'} > $now) &&
                   11311:             ($slots{$slot}->{'endtime'} > $now)) {
                   11312:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   11313:                 my $userallowed = 0;
                   11314:                 if ($slots{$slot}->{'allowedsections'}) {
                   11315:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   11316:                     if (!defined($env{'request.role.sec'})
                   11317:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   11318:                         $userallowed=1;
                   11319:                     } else {
                   11320:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   11321:                             $userallowed=1;
                   11322:                         }
                   11323:                     }
                   11324:                     unless ($userallowed) {
                   11325:                         if (defined($env{'request.course.groups'})) {
                   11326:                             my @groups = split(/:/,$env{'request.course.groups'});
                   11327:                             foreach my $group (@groups) {
                   11328:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   11329:                                     $userallowed=1;
                   11330:                                     last;
                   11331:                                 }
                   11332:                             }
                   11333:                         }
                   11334:                     }
                   11335:                 }
                   11336:                 if ($slots{$slot}->{'allowedusers'}) {
                   11337:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   11338:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   11339:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   11340:                         $userallowed = 1;
                   11341:                     }
                   11342:                 }
                   11343:                 next unless($userallowed);
                   11344:             }
                   11345:             my $startreserve = $slots{$slot}->{'startreserve'};
                   11346:             my $endreserve = $slots{$slot}->{'endreserve'};
                   11347:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  11348:             my $uniqueperiod;
                   11349:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   11350:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   11351:             }
1.1040    raeburn  11352:             if (($startreserve < $now) &&
                   11353:                 (!$endreserve || $endreserve > $now)) {
                   11354:                 my $lastres = $endreserve;
                   11355:                 if (!$lastres) {
                   11356:                     $lastres = $slots{$slot}->{'starttime'};
                   11357:                 }
                   11358:                 $reservable_now{$slot} = {
                   11359:                                            symb       => $symb,
1.1075.2.104  raeburn  11360:                                            endreserve => $lastres,
                   11361:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  11362:                                          };
                   11363:             } elsif (($startreserve > $now) &&
                   11364:                      (!$endreserve || $endreserve > $startreserve)) {
                   11365:                 $future_reservable{$slot} = {
                   11366:                                               symb         => $symb,
1.1075.2.104  raeburn  11367:                                               startreserve => $startreserve,
                   11368:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  11369:                                             };
                   11370:             }
                   11371:         }
                   11372:     }
                   11373:     my @unsorted_reservable = keys(%reservable_now);
                   11374:     if (@unsorted_reservable > 0) {
                   11375:         @sorted_reservable = 
                   11376:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   11377:     }
                   11378:     my @unsorted_future = keys(%future_reservable);
                   11379:     if (@unsorted_future > 0) {
                   11380:         @sorted_future =
                   11381:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   11382:     }
                   11383:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   11384: }
1.780     raeburn  11385: 
                   11386: =pod
                   11387: 
1.1057    foxr     11388: =back
                   11389: 
1.549     albertel 11390: =head1 HTTP Helpers
                   11391: 
                   11392: =over 4
                   11393: 
1.648     raeburn  11394: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 11395: 
1.258     albertel 11396: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 11397: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 11398: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 11399: 
                   11400: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   11401: $possible_names is an ref to an array of form element names.  As an example:
                   11402: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 11403: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 11404: 
                   11405: =cut
1.1       albertel 11406: 
1.6       albertel 11407: sub get_unprocessed_cgi {
1.25      albertel 11408:   my ($query,$possible_names)= @_;
1.26      matthew  11409:   # $Apache::lonxml::debug=1;
1.356     albertel 11410:   foreach my $pair (split(/&/,$query)) {
                   11411:     my ($name, $value) = split(/=/,$pair);
1.369     www      11412:     $name = &unescape($name);
1.25      albertel 11413:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   11414:       $value =~ tr/+/ /;
                   11415:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 11416:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 11417:     }
1.16      harris41 11418:   }
1.6       albertel 11419: }
                   11420: 
1.112     bowersj2 11421: =pod
                   11422: 
1.648     raeburn  11423: =item * &cacheheader() 
1.112     bowersj2 11424: 
                   11425: returns cache-controlling header code
                   11426: 
                   11427: =cut
                   11428: 
1.7       albertel 11429: sub cacheheader {
1.258     albertel 11430:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 11431:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   11432:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 11433:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   11434:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 11435:     return $output;
1.7       albertel 11436: }
                   11437: 
1.112     bowersj2 11438: =pod
                   11439: 
1.648     raeburn  11440: =item * &no_cache($r) 
1.112     bowersj2 11441: 
                   11442: specifies header code to not have cache
                   11443: 
                   11444: =cut
                   11445: 
1.9       albertel 11446: sub no_cache {
1.216     albertel 11447:     my ($r) = @_;
                   11448:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 11449: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 11450:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   11451:     $r->no_cache(1);
                   11452:     $r->header_out("Expires" => $date);
                   11453:     $r->header_out("Pragma" => "no-cache");
1.123     www      11454: }
                   11455: 
                   11456: sub content_type {
1.181     albertel 11457:     my ($r,$type,$charset) = @_;
1.299     foxr     11458:     if ($r) {
                   11459: 	#  Note that printout.pl calls this with undef for $r.
                   11460: 	&no_cache($r);
                   11461:     }
1.258     albertel 11462:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 11463:     unless ($charset) {
                   11464: 	$charset=&Apache::lonlocal::current_encoding;
                   11465:     }
                   11466:     if ($charset) { $type.='; charset='.$charset; }
                   11467:     if ($r) {
                   11468: 	$r->content_type($type);
                   11469:     } else {
                   11470: 	print("Content-type: $type\n\n");
                   11471:     }
1.9       albertel 11472: }
1.25      albertel 11473: 
1.112     bowersj2 11474: =pod
                   11475: 
1.648     raeburn  11476: =item * &add_to_env($name,$value) 
1.112     bowersj2 11477: 
1.258     albertel 11478: adds $name to the %env hash with value
1.112     bowersj2 11479: $value, if $name already exists, the entry is converted to an array
                   11480: reference and $value is added to the array.
                   11481: 
                   11482: =cut
                   11483: 
1.25      albertel 11484: sub add_to_env {
                   11485:   my ($name,$value)=@_;
1.258     albertel 11486:   if (defined($env{$name})) {
                   11487:     if (ref($env{$name})) {
1.25      albertel 11488:       #already have multiple values
1.258     albertel 11489:       push(@{ $env{$name} },$value);
1.25      albertel 11490:     } else {
                   11491:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 11492:       my $first=$env{$name};
                   11493:       undef($env{$name});
                   11494:       push(@{ $env{$name} },$first,$value);
1.25      albertel 11495:     }
                   11496:   } else {
1.258     albertel 11497:     $env{$name}=$value;
1.25      albertel 11498:   }
1.31      albertel 11499: }
1.149     albertel 11500: 
                   11501: =pod
                   11502: 
1.648     raeburn  11503: =item * &get_env_multiple($name) 
1.149     albertel 11504: 
1.258     albertel 11505: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 11506: values may be defined and end up as an array ref.
                   11507: 
                   11508: returns an array of values
                   11509: 
                   11510: =cut
                   11511: 
                   11512: sub get_env_multiple {
                   11513:     my ($name) = @_;
                   11514:     my @values;
1.258     albertel 11515:     if (defined($env{$name})) {
1.149     albertel 11516:         # exists is it an array
1.258     albertel 11517:         if (ref($env{$name})) {
                   11518:             @values=@{ $env{$name} };
1.149     albertel 11519:         } else {
1.258     albertel 11520:             $values[0]=$env{$name};
1.149     albertel 11521:         }
                   11522:     }
                   11523:     return(@values);
                   11524: }
                   11525: 
1.660     raeburn  11526: sub ask_for_embedded_content {
                   11527:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  11528:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  11529:         %currsubfile,%unused,$rem);
1.1071    raeburn  11530:     my $counter = 0;
                   11531:     my $numnew = 0;
1.987     raeburn  11532:     my $numremref = 0;
                   11533:     my $numinvalid = 0;
                   11534:     my $numpathchg = 0;
                   11535:     my $numexisting = 0;
1.1071    raeburn  11536:     my $numunused = 0;
                   11537:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  11538:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  11539:     my $heading = &mt('Upload embedded files');
                   11540:     my $buttontext = &mt('Upload');
                   11541: 
1.1075.2.11  raeburn  11542:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  11543:         if ($actionurl eq '/adm/dependencies') {
                   11544:             $navmap = Apache::lonnavmaps::navmap->new();
                   11545:         }
                   11546:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11547:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  11548:     }
1.1075.2.35  raeburn  11549:     if (($actionurl eq '/adm/portfolio') ||
                   11550:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  11551:         my $current_path='/';
                   11552:         if ($env{'form.currentpath'}) {
                   11553:             $current_path = $env{'form.currentpath'};
                   11554:         }
                   11555:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  11556:             $udom = $cdom;
                   11557:             $uname = $cnum;
1.984     raeburn  11558:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   11559:         } else {
                   11560:             $udom = $env{'user.domain'};
                   11561:             $uname = $env{'user.name'};
                   11562:             $url = '/userfiles/portfolio';
                   11563:         }
1.987     raeburn  11564:         $toplevel = $url.'/';
1.984     raeburn  11565:         $url .= $current_path;
                   11566:         $getpropath = 1;
1.987     raeburn  11567:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   11568:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      11569:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  11570:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  11571:         $toplevel = $url;
1.984     raeburn  11572:         if ($rest ne '') {
1.987     raeburn  11573:             $url .= $rest;
                   11574:         }
                   11575:     } elsif ($actionurl eq '/adm/coursedocs') {
                   11576:         if (ref($args) eq 'HASH') {
1.1071    raeburn  11577:             $url = $args->{'docs_url'};
                   11578:             $toplevel = $url;
1.1075.2.11  raeburn  11579:             if ($args->{'context'} eq 'paste') {
                   11580:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   11581:                 ($path) =
                   11582:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11583:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11584:                 $fileloc =~ s{^/}{};
                   11585:             }
1.1071    raeburn  11586:         }
                   11587:     } elsif ($actionurl eq '/adm/dependencies') {
                   11588:         if ($env{'request.course.id'} ne '') {
                   11589:             if (ref($args) eq 'HASH') {
                   11590:                 $url = $args->{'docs_url'};
                   11591:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  11592:                 $toplevel = $url;
                   11593:                 unless ($toplevel =~ m{^/}) {
                   11594:                     $toplevel = "/$url";
                   11595:                 }
1.1075.2.11  raeburn  11596:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  11597:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   11598:                     $path = $1;
                   11599:                 } else {
                   11600:                     ($path) =
                   11601:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   11602:                 }
1.1075.2.79  raeburn  11603:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   11604:                     $fileloc = $toplevel;
                   11605:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   11606:                     my ($udom,$uname,$fname) =
                   11607:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   11608:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   11609:                 } else {
                   11610:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   11611:                 }
1.1071    raeburn  11612:                 $fileloc =~ s{^/}{};
                   11613:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   11614:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   11615:             }
1.987     raeburn  11616:         }
1.1075.2.35  raeburn  11617:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11618:         $udom = $cdom;
                   11619:         $uname = $cnum;
                   11620:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   11621:         $toplevel = $url;
                   11622:         $path = $url;
                   11623:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   11624:         $fileloc =~ s{^/}{};
                   11625:     }
                   11626:     foreach my $file (keys(%{$allfiles})) {
                   11627:         my $embed_file;
                   11628:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   11629:             $embed_file = $1;
                   11630:         } else {
                   11631:             $embed_file = $file;
                   11632:         }
1.1075.2.55  raeburn  11633:         my ($absolutepath,$cleaned_file);
                   11634:         if ($embed_file =~ m{^\w+://}) {
                   11635:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  11636:             $newfiles{$cleaned_file} = 1;
                   11637:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11638:         } else {
1.1075.2.55  raeburn  11639:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  11640:             if ($embed_file =~ m{^/}) {
                   11641:                 $absolutepath = $embed_file;
                   11642:             }
1.1075.2.47  raeburn  11643:             if ($cleaned_file =~ m{/}) {
                   11644:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  11645:                 $path = &check_for_traversal($path,$url,$toplevel);
                   11646:                 my $item = $fname;
                   11647:                 if ($path ne '') {
                   11648:                     $item = $path.'/'.$fname;
                   11649:                     $subdependencies{$path}{$fname} = 1;
                   11650:                 } else {
                   11651:                     $dependencies{$item} = 1;
                   11652:                 }
                   11653:                 if ($absolutepath) {
                   11654:                     $mapping{$item} = $absolutepath;
                   11655:                 } else {
                   11656:                     $mapping{$item} = $embed_file;
                   11657:                 }
                   11658:             } else {
                   11659:                 $dependencies{$embed_file} = 1;
                   11660:                 if ($absolutepath) {
1.1075.2.47  raeburn  11661:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  11662:                 } else {
1.1075.2.47  raeburn  11663:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  11664:                 }
                   11665:             }
1.984     raeburn  11666:         }
                   11667:     }
1.1071    raeburn  11668:     my $dirptr = 16384;
1.984     raeburn  11669:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  11670:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  11671:         if (($actionurl eq '/adm/portfolio') ||
                   11672:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  11673:             my ($sublistref,$listerror) =
                   11674:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   11675:             if (ref($sublistref) eq 'ARRAY') {
                   11676:                 foreach my $line (@{$sublistref}) {
                   11677:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  11678:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  11679:                 }
1.984     raeburn  11680:             }
1.987     raeburn  11681:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11682:             if (opendir(my $dir,$url.'/'.$path)) {
                   11683:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  11684:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   11685:             }
1.1075.2.11  raeburn  11686:         } elsif (($actionurl eq '/adm/dependencies') ||
                   11687:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11688:                   ($args->{'context'} eq 'paste')) ||
                   11689:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11690:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  11691:                 my $dir;
                   11692:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   11693:                     $dir = $fileloc;
                   11694:                 } else {
                   11695:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11696:                 }
1.1071    raeburn  11697:                 if ($dir ne '') {
                   11698:                     my ($sublistref,$listerror) =
                   11699:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   11700:                     if (ref($sublistref) eq 'ARRAY') {
                   11701:                         foreach my $line (@{$sublistref}) {
                   11702:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   11703:                                 undef,$mtime)=split(/\&/,$line,12);
                   11704:                             unless (($testdir&$dirptr) ||
                   11705:                                     ($file_name =~ /^\.\.?$/)) {
                   11706:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   11707:                             }
                   11708:                         }
                   11709:                     }
                   11710:                 }
1.984     raeburn  11711:             }
                   11712:         }
                   11713:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  11714:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  11715:                 my $item = $path.'/'.$file;
                   11716:                 unless ($mapping{$item} eq $item) {
                   11717:                     $pathchanges{$item} = 1;
                   11718:                 }
                   11719:                 $existing{$item} = 1;
                   11720:                 $numexisting ++;
                   11721:             } else {
                   11722:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  11723:             }
                   11724:         }
1.1071    raeburn  11725:         if ($actionurl eq '/adm/dependencies') {
                   11726:             foreach my $path (keys(%currsubfile)) {
                   11727:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   11728:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   11729:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  11730:                              next if (($rem ne '') &&
                   11731:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   11732:                                        (ref($navmap) &&
                   11733:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   11734:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11735:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  11736:                              $unused{$path.'/'.$file} = 1; 
                   11737:                          }
                   11738:                     }
                   11739:                 }
                   11740:             }
                   11741:         }
1.984     raeburn  11742:     }
1.987     raeburn  11743:     my %currfile;
1.1075.2.35  raeburn  11744:     if (($actionurl eq '/adm/portfolio') ||
                   11745:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  11746:         my ($dirlistref,$listerror) =
                   11747:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   11748:         if (ref($dirlistref) eq 'ARRAY') {
                   11749:             foreach my $line (@{$dirlistref}) {
                   11750:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   11751:                 $currfile{$file_name} = 1;
                   11752:             }
1.984     raeburn  11753:         }
1.987     raeburn  11754:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  11755:         if (opendir(my $dir,$url)) {
1.987     raeburn  11756:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  11757:             map {$currfile{$_} = 1;} @dir_list;
                   11758:         }
1.1075.2.11  raeburn  11759:     } elsif (($actionurl eq '/adm/dependencies') ||
                   11760:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  11761:               ($args->{'context'} eq 'paste')) ||
                   11762:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  11763:         if ($env{'request.course.id'} ne '') {
                   11764:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   11765:             if ($dir ne '') {
                   11766:                 my ($dirlistref,$listerror) =
                   11767:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   11768:                 if (ref($dirlistref) eq 'ARRAY') {
                   11769:                     foreach my $line (@{$dirlistref}) {
                   11770:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   11771:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   11772:                         unless (($testdir&$dirptr) ||
                   11773:                                 ($file_name =~ /^\.\.?$/)) {
                   11774:                             $currfile{$file_name} = [$size,$mtime];
                   11775:                         }
                   11776:                     }
                   11777:                 }
                   11778:             }
                   11779:         }
1.984     raeburn  11780:     }
                   11781:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  11782:         if (exists($currfile{$file})) {
1.987     raeburn  11783:             unless ($mapping{$file} eq $file) {
                   11784:                 $pathchanges{$file} = 1;
                   11785:             }
                   11786:             $existing{$file} = 1;
                   11787:             $numexisting ++;
                   11788:         } else {
1.984     raeburn  11789:             $newfiles{$file} = 1;
                   11790:         }
                   11791:     }
1.1071    raeburn  11792:     foreach my $file (keys(%currfile)) {
                   11793:         unless (($file eq $filename) ||
                   11794:                 ($file eq $filename.'.bak') ||
                   11795:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  11796:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  11797:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   11798:                     next if (($rem ne '') &&
                   11799:                              (($env{"httpref.$rem".$file} ne '') ||
                   11800:                               (ref($navmap) &&
                   11801:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   11802:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   11803:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   11804:                 }
1.1075.2.11  raeburn  11805:             }
1.1071    raeburn  11806:             $unused{$file} = 1;
                   11807:         }
                   11808:     }
1.1075.2.11  raeburn  11809:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   11810:         ($args->{'context'} eq 'paste')) {
                   11811:         $counter = scalar(keys(%existing));
                   11812:         $numpathchg = scalar(keys(%pathchanges));
                   11813:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  11814:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   11815:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   11816:         $counter = scalar(keys(%existing));
                   11817:         $numpathchg = scalar(keys(%pathchanges));
                   11818:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  11819:     }
1.984     raeburn  11820:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  11821:         if ($actionurl eq '/adm/dependencies') {
                   11822:             next if ($embed_file =~ m{^\w+://});
                   11823:         }
1.660     raeburn  11824:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11825:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  11826:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  11827:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  11828:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   11829:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  11830:         }
1.1075.2.35  raeburn  11831:         $upload_output .= '</td>';
1.1071    raeburn  11832:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  11833:             $upload_output.='<td align="right">'.
                   11834:                             '<span class="LC_info LC_fontsize_medium">'.
                   11835:                             &mt("URL points to web address").'</span>';
1.987     raeburn  11836:             $numremref++;
1.660     raeburn  11837:         } elsif ($args->{'error_on_invalid_names'}
                   11838:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  11839:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   11840:                             &mt('Invalid characters').'</span>';
1.987     raeburn  11841:             $numinvalid++;
1.660     raeburn  11842:         } else {
1.1075.2.35  raeburn  11843:             $upload_output .= '<td>'.
                   11844:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  11845:                                                      $embed_file,\%mapping,
1.1071    raeburn  11846:                                                      $allfiles,$codebase,'upload');
                   11847:             $counter ++;
                   11848:             $numnew ++;
1.987     raeburn  11849:         }
                   11850:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   11851:     }
                   11852:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  11853:         if ($actionurl eq '/adm/dependencies') {
                   11854:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   11855:             $modify_output .= &start_data_table_row().
                   11856:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   11857:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   11858:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   11859:                               '<td>'.$size.'</td>'.
                   11860:                               '<td>'.$mtime.'</td>'.
                   11861:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   11862:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   11863:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   11864:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   11865:                               &embedded_file_element('upload_embedded',$counter,
                   11866:                                                      $embed_file,\%mapping,
                   11867:                                                      $allfiles,$codebase,'modify').
                   11868:                               '</div></td>'.
                   11869:                               &end_data_table_row()."\n";
                   11870:             $counter ++;
                   11871:         } else {
                   11872:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  11873:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   11874:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   11875:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  11876:                               &Apache::loncommon::end_data_table_row()."\n";
                   11877:         }
                   11878:     }
                   11879:     my $delidx = $counter;
                   11880:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   11881:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   11882:         $delete_output .= &start_data_table_row().
                   11883:                           '<td><img src="'.&icon($oldfile).'" />'.
                   11884:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   11885:                           '<td>'.$size.'</td>'.
                   11886:                           '<td>'.$mtime.'</td>'.
                   11887:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   11888:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   11889:                           &embedded_file_element('upload_embedded',$delidx,
                   11890:                                                  $oldfile,\%mapping,$allfiles,
                   11891:                                                  $codebase,'delete').'</td>'.
                   11892:                           &end_data_table_row()."\n"; 
                   11893:         $numunused ++;
                   11894:         $delidx ++;
1.987     raeburn  11895:     }
                   11896:     if ($upload_output) {
                   11897:         $upload_output = &start_data_table().
                   11898:                          $upload_output.
                   11899:                          &end_data_table()."\n";
                   11900:     }
1.1071    raeburn  11901:     if ($modify_output) {
                   11902:         $modify_output = &start_data_table().
                   11903:                          &start_data_table_header_row().
                   11904:                          '<th>'.&mt('File').'</th>'.
                   11905:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11906:                          '<th>'.&mt('Modified').'</th>'.
                   11907:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   11908:                          &end_data_table_header_row().
                   11909:                          $modify_output.
                   11910:                          &end_data_table()."\n";
                   11911:     }
                   11912:     if ($delete_output) {
                   11913:         $delete_output = &start_data_table().
                   11914:                          &start_data_table_header_row().
                   11915:                          '<th>'.&mt('File').'</th>'.
                   11916:                          '<th>'.&mt('Size (KB)').'</th>'.
                   11917:                          '<th>'.&mt('Modified').'</th>'.
                   11918:                          '<th>'.&mt('Delete?').'</th>'.
                   11919:                          &end_data_table_header_row().
                   11920:                          $delete_output.
                   11921:                          &end_data_table()."\n";
                   11922:     }
1.987     raeburn  11923:     my $applies = 0;
                   11924:     if ($numremref) {
                   11925:         $applies ++;
                   11926:     }
                   11927:     if ($numinvalid) {
                   11928:         $applies ++;
                   11929:     }
                   11930:     if ($numexisting) {
                   11931:         $applies ++;
                   11932:     }
1.1071    raeburn  11933:     if ($counter || $numunused) {
1.987     raeburn  11934:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   11935:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  11936:                   $state.'<h3>'.$heading.'</h3>'; 
                   11937:         if ($actionurl eq '/adm/dependencies') {
                   11938:             if ($numnew) {
                   11939:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   11940:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   11941:                            $upload_output.'<br />'."\n";
                   11942:             }
                   11943:             if ($numexisting) {
                   11944:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   11945:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   11946:                            $modify_output.'<br />'."\n";
                   11947:                            $buttontext = &mt('Save changes');
                   11948:             }
                   11949:             if ($numunused) {
                   11950:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   11951:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   11952:                            $delete_output.'<br />'."\n";
                   11953:                            $buttontext = &mt('Save changes');
                   11954:             }
                   11955:         } else {
                   11956:             $output .= $upload_output.'<br />'."\n";
                   11957:         }
                   11958:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11959:                    $counter.'" />'."\n";
                   11960:         if ($actionurl eq '/adm/dependencies') { 
                   11961:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11962:                        $numnew.'" />'."\n";
                   11963:         } elsif ($actionurl eq '') {
1.987     raeburn  11964:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11965:         }
                   11966:     } elsif ($applies) {
                   11967:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11968:         if ($applies > 1) {
                   11969:             $output .=  
1.1075.2.35  raeburn  11970:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11971:             if ($numremref) {
                   11972:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11973:             }
                   11974:             if ($numinvalid) {
                   11975:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11976:             }
                   11977:             if ($numexisting) {
                   11978:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11979:             }
                   11980:             $output .= '</ul><br />';
                   11981:         } elsif ($numremref) {
                   11982:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11983:         } elsif ($numinvalid) {
                   11984:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11985:         } elsif ($numexisting) {
                   11986:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11987:         }
                   11988:         $output .= $upload_output.'<br />';
                   11989:     }
                   11990:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11991:     $chgcount = $counter;
1.987     raeburn  11992:     if (keys(%pathchanges) > 0) {
                   11993:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11994:             if ($counter) {
1.987     raeburn  11995:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11996:                                                   $embed_file,\%mapping,
1.1071    raeburn  11997:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11998:             } else {
                   11999:                 $pathchange_output .= 
                   12000:                     &start_data_table_row().
                   12001:                     '<td><input type ="checkbox" name="namechange" value="'.
                   12002:                     $chgcount.'" checked="checked" /></td>'.
                   12003:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   12004:                     '<td>'.$embed_file.
                   12005:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  12006:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  12007:                     '</td>'.&end_data_table_row();
1.660     raeburn  12008:             }
1.987     raeburn  12009:             $numpathchg ++;
                   12010:             $chgcount ++;
1.660     raeburn  12011:         }
                   12012:     }
1.1075.2.35  raeburn  12013:     if (($counter) || ($numunused)) {
1.987     raeburn  12014:         if ($numpathchg) {
                   12015:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   12016:                        $numpathchg.'" />'."\n";
                   12017:         }
                   12018:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   12019:             ($actionurl eq '/adm/imsimport')) {
                   12020:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   12021:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   12022:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  12023:         } elsif ($actionurl eq '/adm/dependencies') {
                   12024:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  12025:         }
1.1075.2.35  raeburn  12026:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  12027:     } elsif ($numpathchg) {
                   12028:         my %pathchange = ();
                   12029:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   12030:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12031:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  12032:         }
1.987     raeburn  12033:     }
1.1071    raeburn  12034:     return ($output,$counter,$numpathchg);
1.987     raeburn  12035: }
                   12036: 
1.1075.2.47  raeburn  12037: =pod
                   12038: 
                   12039: =item * clean_path($name)
                   12040: 
                   12041: Performs clean-up of directories, subdirectories and filename in an
                   12042: embedded object, referenced in an HTML file which is being uploaded
                   12043: to a course or portfolio, where
                   12044: "Upload embedded images/multimedia files if HTML file" checkbox was
                   12045: checked.
                   12046: 
                   12047: Clean-up is similar to replacements in lonnet::clean_filename()
                   12048: except each / between sub-directory and next level is preserved.
                   12049: 
                   12050: =cut
                   12051: 
                   12052: sub clean_path {
                   12053:     my ($embed_file) = @_;
                   12054:     $embed_file =~s{^/+}{};
                   12055:     my @contents;
                   12056:     if ($embed_file =~ m{/}) {
                   12057:         @contents = split(/\//,$embed_file);
                   12058:     } else {
                   12059:         @contents = ($embed_file);
                   12060:     }
                   12061:     my $lastidx = scalar(@contents)-1;
                   12062:     for (my $i=0; $i<=$lastidx; $i++) {
                   12063:         $contents[$i]=~s{\\}{/}g;
                   12064:         $contents[$i]=~s/\s+/\_/g;
                   12065:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   12066:         if ($i == $lastidx) {
                   12067:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   12068:         }
                   12069:     }
                   12070:     if ($lastidx > 0) {
                   12071:         return join('/',@contents);
                   12072:     } else {
                   12073:         return $contents[0];
                   12074:     }
                   12075: }
                   12076: 
1.987     raeburn  12077: sub embedded_file_element {
1.1071    raeburn  12078:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  12079:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   12080:                    (ref($codebase) eq 'HASH'));
                   12081:     my $output;
1.1071    raeburn  12082:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  12083:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   12084:     }
                   12085:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   12086:                &escape($embed_file).'" />';
                   12087:     unless (($context eq 'upload_embedded') && 
                   12088:             ($mapping->{$embed_file} eq $embed_file)) {
                   12089:         $output .='
                   12090:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   12091:     }
                   12092:     my $attrib;
                   12093:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   12094:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   12095:     }
                   12096:     $output .=
                   12097:         "\n\t\t".
                   12098:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   12099:         $attrib.'" />';
                   12100:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   12101:         $output .=
                   12102:             "\n\t\t".
                   12103:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   12104:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  12105:     }
1.987     raeburn  12106:     return $output;
1.660     raeburn  12107: }
                   12108: 
1.1071    raeburn  12109: sub get_dependency_details {
                   12110:     my ($currfile,$currsubfile,$embed_file) = @_;
                   12111:     my ($size,$mtime,$showsize,$showmtime);
                   12112:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   12113:         if ($embed_file =~ m{/}) {
                   12114:             my ($path,$fname) = split(/\//,$embed_file);
                   12115:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   12116:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   12117:             }
                   12118:         } else {
                   12119:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   12120:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   12121:             }
                   12122:         }
                   12123:         $showsize = $size/1024.0;
                   12124:         $showsize = sprintf("%.1f",$showsize);
                   12125:         if ($mtime > 0) {
                   12126:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   12127:         }
                   12128:     }
                   12129:     return ($showsize,$showmtime);
                   12130: }
                   12131: 
                   12132: sub ask_embedded_js {
                   12133:     return <<"END";
                   12134: <script type="text/javascript"">
                   12135: // <![CDATA[
                   12136: function toggleBrowse(counter) {
                   12137:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   12138:     var fileid = document.getElementById('embedded_item_'+counter);
                   12139:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   12140:     if (chkboxid.checked == true) {
                   12141:         uploaddivid.style.display='block';
                   12142:     } else {
                   12143:         uploaddivid.style.display='none';
                   12144:         fileid.value = '';
                   12145:     }
                   12146: }
                   12147: // ]]>
                   12148: </script>
                   12149: 
                   12150: END
                   12151: }
                   12152: 
1.661     raeburn  12153: sub upload_embedded {
                   12154:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  12155:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   12156:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  12157:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   12158:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   12159:         my $orig_uploaded_filename =
                   12160:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  12161:         foreach my $type ('orig','ref','attrib','codebase') {
                   12162:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   12163:                 $env{'form.embedded_'.$type.'_'.$i} =
                   12164:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   12165:             }
                   12166:         }
1.661     raeburn  12167:         my ($path,$fname) =
                   12168:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   12169:         # no path, whole string is fname
                   12170:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   12171:         $fname = &Apache::lonnet::clean_filename($fname);
                   12172:         # See if there is anything left
                   12173:         next if ($fname eq '');
                   12174: 
                   12175:         # Check if file already exists as a file or directory.
                   12176:         my ($state,$msg);
                   12177:         if ($context eq 'portfolio') {
                   12178:             my $port_path = $dirpath;
                   12179:             if ($group ne '') {
                   12180:                 $port_path = "groups/$group/$port_path";
                   12181:             }
1.987     raeburn  12182:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   12183:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  12184:                                               $dir_root,$port_path,$disk_quota,
                   12185:                                               $current_disk_usage,$uname,$udom);
                   12186:             if ($state eq 'will_exceed_quota'
1.984     raeburn  12187:                 || $state eq 'file_locked') {
1.661     raeburn  12188:                 $output .= $msg;
                   12189:                 next;
                   12190:             }
                   12191:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   12192:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   12193:             if ($state eq 'exists') {
                   12194:                 $output .= $msg;
                   12195:                 next;
                   12196:             }
                   12197:         }
                   12198:         # Check if extension is valid
                   12199:         if (($fname =~ /\.(\w+)$/) &&
                   12200:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  12201:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   12202:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  12203:             next;
                   12204:         } elsif (($fname =~ /\.(\w+)$/) &&
                   12205:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  12206:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  12207:             next;
                   12208:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  12209:             $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  12210:             next;
                   12211:         }
                   12212:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  12213:         my $subdir = $path;
                   12214:         $subdir =~ s{/+$}{};
1.661     raeburn  12215:         if ($context eq 'portfolio') {
1.984     raeburn  12216:             my $result;
                   12217:             if ($state eq 'existingfile') {
                   12218:                 $result=
                   12219:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  12220:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  12221:             } else {
1.984     raeburn  12222:                 $result=
                   12223:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  12224:                                                     $dirpath.
1.1075.2.35  raeburn  12225:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  12226:                 if ($result !~ m|^/uploaded/|) {
                   12227:                     $output .= '<span class="LC_error">'
                   12228:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12229:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12230:                                .'</span><br />';
                   12231:                     next;
                   12232:                 } else {
1.987     raeburn  12233:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12234:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  12235:                 }
1.661     raeburn  12236:             }
1.1075.2.35  raeburn  12237:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   12238:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   12239:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  12240:             my $result =
1.1075.2.35  raeburn  12241:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  12242:             if ($result !~ m|^/uploaded/|) {
                   12243:                 $output .= '<span class="LC_error">'
                   12244:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   12245:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   12246:                            .'</span><br />';
                   12247:                     next;
                   12248:             } else {
                   12249:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12250:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  12251:                 if ($context eq 'syllabus') {
                   12252:                     &Apache::lonnet::make_public_indefinitely($result);
                   12253:                 }
1.987     raeburn  12254:             }
1.661     raeburn  12255:         } else {
                   12256: # Save the file
                   12257:             my $target = $env{'form.embedded_item_'.$i};
                   12258:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   12259:             my $dest = $fullpath.$fname;
                   12260:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  12261:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  12262:             my $count;
                   12263:             my $filepath = $dir_root;
1.1027    raeburn  12264:             foreach my $subdir (@parts) {
                   12265:                 $filepath .= "/$subdir";
                   12266:                 if (!-e $filepath) {
1.661     raeburn  12267:                     mkdir($filepath,0770);
                   12268:                 }
                   12269:             }
                   12270:             my $fh;
                   12271:             if (!open($fh,'>'.$dest)) {
                   12272:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   12273:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  12274:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   12275:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12276:                            '</span><br />';
                   12277:             } else {
                   12278:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   12279:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   12280:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  12281:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   12282:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  12283:                               '</span><br />';
                   12284:                 } else {
1.987     raeburn  12285:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   12286:                                $url.'</span>').'<br />';
                   12287:                     unless ($context eq 'testbank') {
                   12288:                         $footer .= &mt('View embedded file: [_1]',
                   12289:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   12290:                     }
                   12291:                 }
                   12292:                 close($fh);
                   12293:             }
                   12294:         }
                   12295:         if ($env{'form.embedded_ref_'.$i}) {
                   12296:             $pathchange{$i} = 1;
                   12297:         }
                   12298:     }
                   12299:     if ($output) {
                   12300:         $output = '<p>'.$output.'</p>';
                   12301:     }
                   12302:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   12303:     $returnflag = 'ok';
1.1071    raeburn  12304:     my $numpathchgs = scalar(keys(%pathchange));
                   12305:     if ($numpathchgs > 0) {
1.987     raeburn  12306:         if ($context eq 'portfolio') {
                   12307:             $output .= '<p>'.&mt('or').'</p>';
                   12308:         } elsif ($context eq 'testbank') {
1.1071    raeburn  12309:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   12310:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  12311:             $returnflag = 'modify_orightml';
                   12312:         }
                   12313:     }
1.1071    raeburn  12314:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  12315: }
                   12316: 
                   12317: sub modify_html_form {
                   12318:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   12319:     my $end = 0;
                   12320:     my $modifyform;
                   12321:     if ($context eq 'upload_embedded') {
                   12322:         return unless (ref($pathchange) eq 'HASH');
                   12323:         if ($env{'form.number_embedded_items'}) {
                   12324:             $end += $env{'form.number_embedded_items'};
                   12325:         }
                   12326:         if ($env{'form.number_pathchange_items'}) {
                   12327:             $end += $env{'form.number_pathchange_items'};
                   12328:         }
                   12329:         if ($end) {
                   12330:             for (my $i=0; $i<$end; $i++) {
                   12331:                 if ($i < $env{'form.number_embedded_items'}) {
                   12332:                     next unless($pathchange->{$i});
                   12333:                 }
                   12334:                 $modifyform .=
                   12335:                     &start_data_table_row().
                   12336:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   12337:                     'checked="checked" /></td>'.
                   12338:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   12339:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   12340:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   12341:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   12342:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   12343:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   12344:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   12345:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   12346:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   12347:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   12348:                     &end_data_table_row();
1.1071    raeburn  12349:             }
1.987     raeburn  12350:         }
                   12351:     } else {
                   12352:         $modifyform = $pathchgtable;
                   12353:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   12354:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   12355:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   12356:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   12357:         }
                   12358:     }
                   12359:     if ($modifyform) {
1.1071    raeburn  12360:         if ($actionurl eq '/adm/dependencies') {
                   12361:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   12362:         }
1.987     raeburn  12363:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   12364:                '<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".
                   12365:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   12366:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   12367:                '</ol></p>'."\n".'<p>'.
                   12368:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   12369:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   12370:                &start_data_table()."\n".
                   12371:                &start_data_table_header_row().
                   12372:                '<th>'.&mt('Change?').'</th>'.
                   12373:                '<th>'.&mt('Current reference').'</th>'.
                   12374:                '<th>'.&mt('Required reference').'</th>'.
                   12375:                &end_data_table_header_row()."\n".
                   12376:                $modifyform.
                   12377:                &end_data_table().'<br />'."\n".$hiddenstate.
                   12378:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   12379:                '</form>'."\n";
                   12380:     }
                   12381:     return;
                   12382: }
                   12383: 
                   12384: sub modify_html_refs {
1.1075.2.35  raeburn  12385:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  12386:     my $container;
                   12387:     if ($context eq 'portfolio') {
                   12388:         $container = $env{'form.container'};
                   12389:     } elsif ($context eq 'coursedoc') {
                   12390:         $container = $env{'form.primaryurl'};
1.1071    raeburn  12391:     } elsif ($context eq 'manage_dependencies') {
                   12392:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   12393:         $container = "/$container";
1.1075.2.35  raeburn  12394:     } elsif ($context eq 'syllabus') {
                   12395:         $container = $url;
1.987     raeburn  12396:     } else {
1.1027    raeburn  12397:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  12398:     }
                   12399:     my (%allfiles,%codebase,$output,$content);
                   12400:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  12401:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  12402:         if (wantarray) {
                   12403:             return ('',0,0); 
                   12404:         } else {
                   12405:             return;
                   12406:         }
                   12407:     }
                   12408:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12409:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  12410:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   12411:             if (wantarray) {
                   12412:                 return ('',0,0);
                   12413:             } else {
                   12414:                 return;
                   12415:             }
                   12416:         } 
1.987     raeburn  12417:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  12418:         if ($content eq '-1') {
                   12419:             if (wantarray) {
                   12420:                 return ('',0,0);
                   12421:             } else {
                   12422:                 return;
                   12423:             }
                   12424:         }
1.987     raeburn  12425:     } else {
1.1071    raeburn  12426:         unless ($container =~ /^\Q$dir_root\E/) {
                   12427:             if (wantarray) {
                   12428:                 return ('',0,0);
                   12429:             } else {
                   12430:                 return;
                   12431:             }
                   12432:         } 
1.1075.2.128  raeburn  12433:         if (open(my $fh,'<',$container)) {
1.987     raeburn  12434:             $content = join('', <$fh>);
                   12435:             close($fh);
                   12436:         } else {
1.1071    raeburn  12437:             if (wantarray) {
                   12438:                 return ('',0,0);
                   12439:             } else {
                   12440:                 return;
                   12441:             }
1.987     raeburn  12442:         }
                   12443:     }
                   12444:     my ($count,$codebasecount) = (0,0);
                   12445:     my $mm = new File::MMagic;
                   12446:     my $mime_type = $mm->checktype_contents($content);
                   12447:     if ($mime_type eq 'text/html') {
                   12448:         my $parse_result = 
                   12449:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   12450:                                                     \%codebase,\$content);
                   12451:         if ($parse_result eq 'ok') {
                   12452:             foreach my $i (@changes) {
                   12453:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   12454:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   12455:                 if ($allfiles{$ref}) {
                   12456:                     my $newname =  $orig;
                   12457:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  12458:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  12459:                     if ($attrib_regexp =~ /:/) {
                   12460:                         $attrib_regexp =~ s/\:/|/g;
                   12461:                     }
                   12462:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12463:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12464:                         $count += $numchg;
1.1075.2.35  raeburn  12465:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  12466:                         delete($allfiles{$ref});
1.987     raeburn  12467:                     }
                   12468:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  12469:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  12470:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   12471:                         $codebasecount ++;
                   12472:                     }
                   12473:                 }
                   12474:             }
1.1075.2.35  raeburn  12475:             my $skiprewrites;
1.987     raeburn  12476:             if ($count || $codebasecount) {
                   12477:                 my $saveresult;
1.1071    raeburn  12478:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  12479:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  12480:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12481:                     if ($url eq $container) {
                   12482:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   12483:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12484:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  12485:                                             $fname.'</span>').'</p>';
1.987     raeburn  12486:                     } else {
                   12487:                          $output = '<p class="LC_error">'.
                   12488:                                    &mt('Error: update failed for: [_1].',
                   12489:                                    '<span class="LC_filename">'.
                   12490:                                    $container.'</span>').'</p>';
                   12491:                     }
1.1075.2.35  raeburn  12492:                     if ($context eq 'syllabus') {
                   12493:                         unless ($saveresult eq 'ok') {
                   12494:                             $skiprewrites = 1;
                   12495:                         }
                   12496:                     }
1.987     raeburn  12497:                 } else {
1.1075.2.128  raeburn  12498:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  12499:                         print $fh $content;
                   12500:                         close($fh);
                   12501:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   12502:                                   $count,'<span class="LC_filename">'.
                   12503:                                   $container.'</span>').'</p>';
1.661     raeburn  12504:                     } else {
1.987     raeburn  12505:                          $output = '<p class="LC_error">'.
                   12506:                                    &mt('Error: could not update [_1].',
                   12507:                                    '<span class="LC_filename">'.
                   12508:                                    $container.'</span>').'</p>';
1.661     raeburn  12509:                     }
                   12510:                 }
                   12511:             }
1.1075.2.35  raeburn  12512:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   12513:                 my ($actionurl,$state);
                   12514:                 $actionurl = "/public/$udom/$uname/syllabus";
                   12515:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   12516:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   12517:                                               \%codebase,
                   12518:                                               {'context' => 'rewrites',
                   12519:                                                'ignore_remote_references' => 1,});
                   12520:                 if (ref($mapping) eq 'HASH') {
                   12521:                     my $rewrites = 0;
                   12522:                     foreach my $key (keys(%{$mapping})) {
                   12523:                         next if ($key =~ m{^https?://});
                   12524:                         my $ref = $mapping->{$key};
                   12525:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   12526:                         my $attrib;
                   12527:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   12528:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   12529:                         }
                   12530:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   12531:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   12532:                             $rewrites += $numchg;
                   12533:                         }
                   12534:                     }
                   12535:                     if ($rewrites) {
                   12536:                         my $saveresult;
                   12537:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   12538:                         if ($url eq $container) {
                   12539:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   12540:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   12541:                                             $count,'<span class="LC_filename">'.
                   12542:                                             $fname.'</span>').'</p>';
                   12543:                         } else {
                   12544:                             $output .= '<p class="LC_error">'.
                   12545:                                        &mt('Error: could not update links in [_1].',
                   12546:                                        '<span class="LC_filename">'.
                   12547:                                        $container.'</span>').'</p>';
                   12548: 
                   12549:                         }
                   12550:                     }
                   12551:                 }
                   12552:             }
1.987     raeburn  12553:         } else {
                   12554:             &logthis('Failed to parse '.$container.
                   12555:                      ' to modify references: '.$parse_result);
1.661     raeburn  12556:         }
                   12557:     }
1.1071    raeburn  12558:     if (wantarray) {
                   12559:         return ($output,$count,$codebasecount);
                   12560:     } else {
                   12561:         return $output;
                   12562:     }
1.661     raeburn  12563: }
                   12564: 
                   12565: sub check_for_existing {
                   12566:     my ($path,$fname,$element) = @_;
                   12567:     my ($state,$msg);
                   12568:     if (-d $path.'/'.$fname) {
                   12569:         $state = 'exists';
                   12570:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12571:     } elsif (-e $path.'/'.$fname) {
                   12572:         $state = 'exists';
                   12573:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   12574:     }
                   12575:     if ($state eq 'exists') {
                   12576:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   12577:     }
                   12578:     return ($state,$msg);
                   12579: }
                   12580: 
                   12581: sub check_for_upload {
                   12582:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   12583:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  12584:     my $filesize = length($env{'form.'.$element});
                   12585:     if (!$filesize) {
                   12586:         my $msg = '<span class="LC_error">'.
                   12587:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   12588:                       '<span class="LC_filename">'.$fname.'</span>',
                   12589:                       $filesize).'<br />'.
1.1007    raeburn  12590:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  12591:                   '</span>';
                   12592:         return ('zero_bytes',$msg);
                   12593:     }
                   12594:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  12595:     my $getpropath = 1;
1.1021    raeburn  12596:     my ($dirlistref,$listerror) =
                   12597:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  12598:     my $found_file = 0;
                   12599:     my $locked_file = 0;
1.991     raeburn  12600:     my @lockers;
                   12601:     my $navmap;
                   12602:     if ($env{'request.course.id'}) {
                   12603:         $navmap = Apache::lonnavmaps::navmap->new();
                   12604:     }
1.1021    raeburn  12605:     if (ref($dirlistref) eq 'ARRAY') {
                   12606:         foreach my $line (@{$dirlistref}) {
                   12607:             my ($file_name,$rest)=split(/\&/,$line,2);
                   12608:             if ($file_name eq $fname){
                   12609:                 $file_name = $path.$file_name;
                   12610:                 if ($group ne '') {
                   12611:                     $file_name = $group.$file_name;
                   12612:                 }
                   12613:                 $found_file = 1;
                   12614:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   12615:                     foreach my $lock (@lockers) {
                   12616:                         if (ref($lock) eq 'ARRAY') {
                   12617:                             my ($symb,$crsid) = @{$lock};
                   12618:                             if ($crsid eq $env{'request.course.id'}) {
                   12619:                                 if (ref($navmap)) {
                   12620:                                     my $res = $navmap->getBySymb($symb);
                   12621:                                     foreach my $part (@{$res->parts()}) { 
                   12622:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   12623:                                         unless (($slot_status == $res->RESERVED) ||
                   12624:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   12625:                                             $locked_file = 1;
                   12626:                                         }
1.991     raeburn  12627:                                     }
1.1021    raeburn  12628:                                 } else {
                   12629:                                     $locked_file = 1;
1.991     raeburn  12630:                                 }
                   12631:                             } else {
                   12632:                                 $locked_file = 1;
                   12633:                             }
                   12634:                         }
1.1021    raeburn  12635:                    }
                   12636:                 } else {
                   12637:                     my @info = split(/\&/,$rest);
                   12638:                     my $currsize = $info[6]/1000;
                   12639:                     if ($currsize < $filesize) {
                   12640:                         my $extra = $filesize - $currsize;
                   12641:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  12642:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  12643:                                       &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.1075.2.69  raeburn  12644:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   12645:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   12646:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  12647:                             return ('will_exceed_quota',$msg);
                   12648:                         }
1.984     raeburn  12649:                     }
                   12650:                 }
1.661     raeburn  12651:             }
                   12652:         }
                   12653:     }
                   12654:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  12655:         my $msg = '<p class="LC_warning">'.
                   12656:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   12657:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  12658:         return ('will_exceed_quota',$msg);
                   12659:     } elsif ($found_file) {
                   12660:         if ($locked_file) {
1.1075.2.69  raeburn  12661:             my $msg = '<p class="LC_warning">';
1.661     raeburn  12662:             $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.1075.2.69  raeburn  12663:             $msg .= '</p>';
1.661     raeburn  12664:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   12665:             return ('file_locked',$msg);
                   12666:         } else {
1.1075.2.69  raeburn  12667:             my $msg = '<p class="LC_error">';
1.984     raeburn  12668:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  12669:             $msg .= '</p>';
1.984     raeburn  12670:             return ('existingfile',$msg);
1.661     raeburn  12671:         }
                   12672:     }
                   12673: }
                   12674: 
1.987     raeburn  12675: sub check_for_traversal {
                   12676:     my ($path,$url,$toplevel) = @_;
                   12677:     my @parts=split(/\//,$path);
                   12678:     my $cleanpath;
                   12679:     my $fullpath = $url;
                   12680:     for (my $i=0;$i<@parts;$i++) {
                   12681:         next if ($parts[$i] eq '.');
                   12682:         if ($parts[$i] eq '..') {
                   12683:             $fullpath =~ s{([^/]+/)$}{};
                   12684:         } else {
                   12685:             $fullpath .= $parts[$i].'/';
                   12686:         }
                   12687:     }
                   12688:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   12689:         $cleanpath = $1;
                   12690:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   12691:         my $curr_toprel = $1;
                   12692:         my @parts = split(/\//,$curr_toprel);
                   12693:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   12694:         my @urlparts = split(/\//,$url_toprel);
                   12695:         my $doubledots;
                   12696:         my $startdiff = -1;
                   12697:         for (my $i=0; $i<@urlparts; $i++) {
                   12698:             if ($startdiff == -1) {
                   12699:                 unless ($urlparts[$i] eq $parts[$i]) {
                   12700:                     $startdiff = $i;
                   12701:                     $doubledots .= '../';
                   12702:                 }
                   12703:             } else {
                   12704:                 $doubledots .= '../';
                   12705:             }
                   12706:         }
                   12707:         if ($startdiff > -1) {
                   12708:             $cleanpath = $doubledots;
                   12709:             for (my $i=$startdiff; $i<@parts; $i++) {
                   12710:                 $cleanpath .= $parts[$i].'/';
                   12711:             }
                   12712:         }
                   12713:     }
                   12714:     $cleanpath =~ s{(/)$}{};
                   12715:     return $cleanpath;
                   12716: }
1.31      albertel 12717: 
1.1053    raeburn  12718: sub is_archive_file {
                   12719:     my ($mimetype) = @_;
                   12720:     if (($mimetype eq 'application/octet-stream') ||
                   12721:         ($mimetype eq 'application/x-stuffit') ||
                   12722:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   12723:         return 1;
                   12724:     }
                   12725:     return;
                   12726: }
                   12727: 
                   12728: sub decompress_form {
1.1065    raeburn  12729:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  12730:     my %lt = &Apache::lonlocal::texthash (
                   12731:         this => 'This file is an archive file.',
1.1067    raeburn  12732:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  12733:         itsc => 'Its contents are as follows:',
1.1053    raeburn  12734:         youm => 'You may wish to extract its contents.',
                   12735:         extr => 'Extract contents',
1.1067    raeburn  12736:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   12737:         proa => 'Process automatically?',
1.1053    raeburn  12738:         yes  => 'Yes',
                   12739:         no   => 'No',
1.1067    raeburn  12740:         fold => 'Title for folder containing movie',
                   12741:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  12742:     );
1.1065    raeburn  12743:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  12744:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  12745:     my $info = &list_archive_contents($fileloc,\@paths);
                   12746:     if (@paths) {
                   12747:         foreach my $path (@paths) {
                   12748:             $path =~ s{^/}{};
1.1067    raeburn  12749:             if ($path =~ m{^([^/]+)/$}) {
                   12750:                 $topdir = $1;
                   12751:             }
1.1065    raeburn  12752:             if ($path =~ m{^([^/]+)/}) {
                   12753:                 $toplevel{$1} = $path;
                   12754:             } else {
                   12755:                 $toplevel{$path} = $path;
                   12756:             }
                   12757:         }
                   12758:     }
1.1067    raeburn  12759:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  12760:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  12761:                         "$topdir/media/",
                   12762:                         "$topdir/media/$topdir.mp4",
                   12763:                         "$topdir/media/FirstFrame.png",
                   12764:                         "$topdir/media/player.swf",
                   12765:                         "$topdir/media/swfobject.js",
                   12766:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  12767:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  12768:                          "$topdir/$topdir.mp4",
                   12769:                          "$topdir/$topdir\_config.xml",
                   12770:                          "$topdir/$topdir\_controller.swf",
                   12771:                          "$topdir/$topdir\_embed.css",
                   12772:                          "$topdir/$topdir\_First_Frame.png",
                   12773:                          "$topdir/$topdir\_player.html",
                   12774:                          "$topdir/$topdir\_Thumbnails.png",
                   12775:                          "$topdir/playerProductInstall.swf",
                   12776:                          "$topdir/scripts/",
                   12777:                          "$topdir/scripts/config_xml.js",
                   12778:                          "$topdir/scripts/handlebars.js",
                   12779:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   12780:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   12781:                          "$topdir/scripts/modernizr.js",
                   12782:                          "$topdir/scripts/player-min.js",
                   12783:                          "$topdir/scripts/swfobject.js",
                   12784:                          "$topdir/skins/",
                   12785:                          "$topdir/skins/configuration_express.xml",
                   12786:                          "$topdir/skins/express_show/",
                   12787:                          "$topdir/skins/express_show/player-min.css",
                   12788:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  12789:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   12790:                          "$topdir/$topdir.mp4",
                   12791:                          "$topdir/$topdir\_config.xml",
                   12792:                          "$topdir/$topdir\_controller.swf",
                   12793:                          "$topdir/$topdir\_embed.css",
                   12794:                          "$topdir/$topdir\_First_Frame.png",
                   12795:                          "$topdir/$topdir\_player.html",
                   12796:                          "$topdir/$topdir\_Thumbnails.png",
                   12797:                          "$topdir/playerProductInstall.swf",
                   12798:                          "$topdir/scripts/",
                   12799:                          "$topdir/scripts/config_xml.js",
                   12800:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   12801:                          "$topdir/skins/",
                   12802:                          "$topdir/skins/configuration_express.xml",
                   12803:                          "$topdir/skins/express_show/",
                   12804:                          "$topdir/skins/express_show/spritesheet.min.css",
                   12805:                          "$topdir/skins/express_show/spritesheet.png",
                   12806:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  12807:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  12808:         if (@diffs == 0) {
1.1075.2.59  raeburn  12809:             $is_camtasia = 6;
                   12810:         } else {
1.1075.2.81  raeburn  12811:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  12812:             if (@diffs == 0) {
                   12813:                 $is_camtasia = 8;
1.1075.2.81  raeburn  12814:             } else {
                   12815:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   12816:                 if (@diffs == 0) {
                   12817:                     $is_camtasia = 8;
                   12818:                 }
1.1075.2.59  raeburn  12819:             }
1.1067    raeburn  12820:         }
                   12821:     }
                   12822:     my $output;
                   12823:     if ($is_camtasia) {
                   12824:         $output = <<"ENDCAM";
                   12825: <script type="text/javascript" language="Javascript">
                   12826: // <![CDATA[
                   12827: 
                   12828: function camtasiaToggle() {
                   12829:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   12830:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  12831:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  12832:                 document.getElementById('camtasia_titles').style.display='block';
                   12833:             } else {
                   12834:                 document.getElementById('camtasia_titles').style.display='none';
                   12835:             }
                   12836:         }
                   12837:     }
                   12838:     return;
                   12839: }
                   12840: 
                   12841: // ]]>
                   12842: </script>
                   12843: <p>$lt{'camt'}</p>
                   12844: ENDCAM
1.1065    raeburn  12845:     } else {
1.1067    raeburn  12846:         $output = '<p>'.$lt{'this'};
                   12847:         if ($info eq '') {
                   12848:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   12849:         } else {
                   12850:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   12851:                        '<div><pre>'.$info.'</pre></div>';
                   12852:         }
1.1065    raeburn  12853:     }
1.1067    raeburn  12854:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  12855:     my $duplicates;
                   12856:     my $num = 0;
                   12857:     if (ref($dirlist) eq 'ARRAY') {
                   12858:         foreach my $item (@{$dirlist}) {
                   12859:             if (ref($item) eq 'ARRAY') {
                   12860:                 if (exists($toplevel{$item->[0]})) {
                   12861:                     $duplicates .= 
                   12862:                         &start_data_table_row().
                   12863:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12864:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   12865:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   12866:                         'value="1" />'.&mt('Yes').'</label>'.
                   12867:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   12868:                         '<td>'.$item->[0].'</td>';
                   12869:                     if ($item->[2]) {
                   12870:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   12871:                     } else {
                   12872:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   12873:                     }
                   12874:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   12875:                                    '<td>'.
                   12876:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   12877:                                    '</td>'.
                   12878:                                    &end_data_table_row();
                   12879:                     $num ++;
                   12880:                 }
                   12881:             }
                   12882:         }
                   12883:     }
                   12884:     my $itemcount;
                   12885:     if (@paths > 0) {
                   12886:         $itemcount = scalar(@paths);
                   12887:     } else {
                   12888:         $itemcount = 1;
                   12889:     }
1.1067    raeburn  12890:     if ($is_camtasia) {
                   12891:         $output .= $lt{'auto'}.'<br />'.
                   12892:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  12893:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  12894:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   12895:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   12896:                    $lt{'no'}.'</label></span><br />'.
                   12897:                    '<div id="camtasia_titles" style="display:block">'.
                   12898:                    &Apache::lonhtmlcommon::start_pick_box().
                   12899:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   12900:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   12901:                    &Apache::lonhtmlcommon::row_closure().
                   12902:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   12903:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   12904:                    &Apache::lonhtmlcommon::row_closure(1).
                   12905:                    &Apache::lonhtmlcommon::end_pick_box().
                   12906:                    '</div>';
                   12907:     }
1.1065    raeburn  12908:     $output .= 
                   12909:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  12910:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   12911:         "\n";
1.1065    raeburn  12912:     if ($duplicates ne '') {
                   12913:         $output .= '<p><span class="LC_warning">'.
                   12914:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   12915:                    &start_data_table().
                   12916:                    &start_data_table_header_row().
                   12917:                    '<th>'.&mt('Overwrite?').'</th>'.
                   12918:                    '<th>'.&mt('Name').'</th>'.
                   12919:                    '<th>'.&mt('Type').'</th>'.
                   12920:                    '<th>'.&mt('Size').'</th>'.
                   12921:                    '<th>'.&mt('Last modified').'</th>'.
                   12922:                    &end_data_table_header_row().
                   12923:                    $duplicates.
                   12924:                    &end_data_table().
                   12925:                    '</p>';
                   12926:     }
1.1067    raeburn  12927:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  12928:     if (ref($hiddenelements) eq 'HASH') {
                   12929:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   12930:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   12931:         }
                   12932:     }
                   12933:     $output .= <<"END";
1.1067    raeburn  12934: <br />
1.1053    raeburn  12935: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   12936: </form>
                   12937: $noextract
                   12938: END
                   12939:     return $output;
                   12940: }
                   12941: 
1.1065    raeburn  12942: sub decompression_utility {
                   12943:     my ($program) = @_;
                   12944:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   12945:     my $location;
                   12946:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   12947:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   12948:                          '/usr/sbin/') {
                   12949:             if (-x $dir.$program) {
                   12950:                 $location = $dir.$program;
                   12951:                 last;
                   12952:             }
                   12953:         }
                   12954:     }
                   12955:     return $location;
                   12956: }
                   12957: 
                   12958: sub list_archive_contents {
                   12959:     my ($file,$pathsref) = @_;
                   12960:     my (@cmd,$output);
                   12961:     my $needsregexp;
                   12962:     if ($file =~ /\.zip$/) {
                   12963:         @cmd = (&decompression_utility('unzip'),"-l");
                   12964:         $needsregexp = 1;
                   12965:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12966:              ($file =~ /\.tgz$/)) {
                   12967:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12968:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12969:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12970:     } elsif ($file =~ m|\.tar$|) {
                   12971:         @cmd = (&decompression_utility('tar'),"-tf");
                   12972:     }
                   12973:     if (@cmd) {
                   12974:         undef($!);
                   12975:         undef($@);
                   12976:         if (open(my $fh,"-|", @cmd, $file)) {
                   12977:             while (my $line = <$fh>) {
                   12978:                 $output .= $line;
                   12979:                 chomp($line);
                   12980:                 my $item;
                   12981:                 if ($needsregexp) {
                   12982:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12983:                 } else {
                   12984:                     $item = $line;
                   12985:                 }
                   12986:                 if ($item ne '') {
                   12987:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12988:                         push(@{$pathsref},$item);
                   12989:                     } 
                   12990:                 }
                   12991:             }
                   12992:             close($fh);
                   12993:         }
                   12994:     }
                   12995:     return $output;
                   12996: }
                   12997: 
1.1053    raeburn  12998: sub decompress_uploaded_file {
                   12999:     my ($file,$dir) = @_;
                   13000:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   13001:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   13002:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   13003:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   13004:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   13005:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   13006:     my $decompressed = $env{'cgi.decompressed'};
                   13007:     &Apache::lonnet::delenv('cgi.file');
                   13008:     &Apache::lonnet::delenv('cgi.dir');
                   13009:     &Apache::lonnet::delenv('cgi.decompressed');
                   13010:     return ($decompressed,$result);
                   13011: }
                   13012: 
1.1055    raeburn  13013: sub process_decompression {
                   13014:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  13015:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   13016:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13017:                &mt('Unexpected file path.').'</p>'."\n";
                   13018:     }
                   13019:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   13020:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13021:                &mt('Unexpected course context.').'</p>'."\n";
                   13022:     }
                   13023:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   13024:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13025:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   13026:     }
1.1055    raeburn  13027:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  13028:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  13029:         $error = &mt('Filename not a supported archive file type.').
                   13030:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  13031:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   13032:     } else {
                   13033:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13034:         if ($docuhome eq 'no_host') {
                   13035:             $error = &mt('Could not determine home server for course.');
                   13036:         } else {
                   13037:             my @ids=&Apache::lonnet::current_machine_ids();
                   13038:             my $currdir = "$dir_root/$destination";
                   13039:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13040:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   13041:                        "$dir_root/$destination";
                   13042:             } else {
                   13043:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   13044:                        "$dir_root/$docudom/$docuname/$destination";
                   13045:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   13046:                     $error = &mt('Archive file not found.');
                   13047:                 }
                   13048:             }
1.1065    raeburn  13049:             my (@to_overwrite,@to_skip);
                   13050:             if ($env{'form.archive_overwrite_total'} > 0) {
                   13051:                 my $total = $env{'form.archive_overwrite_total'};
                   13052:                 for (my $i=0; $i<$total; $i++) {
                   13053:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   13054:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   13055:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   13056:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   13057:                     }
                   13058:                 }
                   13059:             }
                   13060:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  13061:             my $numoverwrite = scalar(@to_overwrite);
                   13062:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  13063:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   13064:             } elsif ($dir eq '') {
1.1055    raeburn  13065:                 $error = &mt('Directory containing archive file unavailable.');
                   13066:             } elsif (!$error) {
1.1065    raeburn  13067:                 my ($decompressed,$display);
1.1075.2.128  raeburn  13068:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  13069:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   13070:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  13071:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   13072:                         ($decompressed,$display) =
                   13073:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   13074:                         foreach my $item (@to_skip) {
                   13075:                             if (($item ne '') && ($item !~ /\.\./)) {
                   13076:                                 if (-f "$dir/$tempdir/$item") {
                   13077:                                     unlink("$dir/$tempdir/$item");
                   13078:                                 } elsif (-d "$dir/$tempdir/$item") {
                   13079:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   13080:                                 }
                   13081:                             }
                   13082:                         }
                   13083:                         foreach my $item (@to_overwrite) {
                   13084:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   13085:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   13086:                                     if (-f "$dir/$item") {
                   13087:                                         unlink("$dir/$item");
                   13088:                                     } elsif (-d "$dir/$item") {
                   13089:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   13090:                                     }
                   13091:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   13092:                                 }
1.1065    raeburn  13093:                             }
                   13094:                         }
1.1075.2.128  raeburn  13095:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   13096:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   13097:                         }
1.1065    raeburn  13098:                     }
                   13099:                 } else {
                   13100:                     ($decompressed,$display) = 
                   13101:                         &decompress_uploaded_file($file,$dir);
                   13102:                 }
1.1055    raeburn  13103:                 if ($decompressed eq 'ok') {
1.1065    raeburn  13104:                     $output = '<p class="LC_info">'.
                   13105:                               &mt('Files extracted successfully from archive.').
                   13106:                               '</p>'."\n";
1.1055    raeburn  13107:                     my ($warning,$result,@contents);
                   13108:                     my ($newdirlistref,$newlisterror) =
                   13109:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   13110:                                                  $docuname,1);
                   13111:                     my (%is_dir,%changes,@newitems);
                   13112:                     my $dirptr = 16384;
1.1065    raeburn  13113:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  13114:                         foreach my $dir_line (@{$newdirlistref}) {
                   13115:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  13116:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  13117:                                 push(@newitems,$item);
                   13118:                                 if ($dirptr&$testdir) {
                   13119:                                     $is_dir{$item} = 1;
                   13120:                                 }
                   13121:                                 $changes{$item} = 1;
                   13122:                             }
                   13123:                         }
                   13124:                     }
                   13125:                     if (keys(%changes) > 0) {
                   13126:                         foreach my $item (sort(@newitems)) {
                   13127:                             if ($changes{$item}) {
                   13128:                                 push(@contents,$item);
                   13129:                             }
                   13130:                         }
                   13131:                     }
                   13132:                     if (@contents > 0) {
1.1067    raeburn  13133:                         my $wantform;
                   13134:                         unless ($env{'form.autoextract_camtasia'}) {
                   13135:                             $wantform = 1;
                   13136:                         }
1.1056    raeburn  13137:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  13138:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   13139:                                                                 $currdir,\%is_dir,
                   13140:                                                                 \%children,\%parent,
1.1056    raeburn  13141:                                                                 \@contents,\%dirorder,
                   13142:                                                                 \%titles,$wantform);
1.1055    raeburn  13143:                         if ($datatable ne '') {
                   13144:                             $output .= &archive_options_form('decompressed',$datatable,
                   13145:                                                              $count,$hiddenelem);
1.1065    raeburn  13146:                             my $startcount = 6;
1.1055    raeburn  13147:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  13148:                                                            \%titles,\%children);
1.1055    raeburn  13149:                         }
1.1067    raeburn  13150:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  13151:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  13152:                             my %displayed;
                   13153:                             my $total = 1;
                   13154:                             $env{'form.archive_directory'} = [];
                   13155:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   13156:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   13157:                                 $path =~ s{/$}{};
                   13158:                                 my $item;
                   13159:                                 if ($path ne '') {
                   13160:                                     $item = "$path/$titles{$i}";
                   13161:                                 } else {
                   13162:                                     $item = $titles{$i};
                   13163:                                 }
                   13164:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   13165:                                 if ($item eq $contents[0]) {
                   13166:                                     push(@{$env{'form.archive_directory'}},$i);
                   13167:                                     $env{'form.archive_'.$i} = 'display';
                   13168:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   13169:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  13170:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   13171:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  13172:                                     $env{'form.archive_'.$i} = 'display';
                   13173:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   13174:                                     $displayed{'web'} = $i;
                   13175:                                 } else {
1.1075.2.59  raeburn  13176:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   13177:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   13178:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  13179:                                         push(@{$env{'form.archive_directory'}},$i);
                   13180:                                     }
                   13181:                                     $env{'form.archive_'.$i} = 'dependency';
                   13182:                                 }
                   13183:                                 $total ++;
                   13184:                             }
                   13185:                             for (my $i=1; $i<$total; $i++) {
                   13186:                                 next if ($i == $displayed{'web'});
                   13187:                                 next if ($i == $displayed{'folder'});
                   13188:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   13189:                             }
                   13190:                             $env{'form.phase'} = 'decompress_cleanup';
                   13191:                             $env{'form.archivedelete'} = 1;
                   13192:                             $env{'form.archive_count'} = $total-1;
                   13193:                             $output .=
                   13194:                                 &process_extracted_files('coursedocs',$docudom,
                   13195:                                                          $docuname,$destination,
                   13196:                                                          $dir_root,$hiddenelem);
                   13197:                         }
1.1055    raeburn  13198:                     } else {
                   13199:                         $warning = &mt('No new items extracted from archive file.');
                   13200:                     }
                   13201:                 } else {
                   13202:                     $output = $display;
                   13203:                     $error = &mt('An error occurred during extraction from the archive file.');
                   13204:                 }
                   13205:             }
                   13206:         }
                   13207:     }
                   13208:     if ($error) {
                   13209:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13210:                    $error.'</p>'."\n";
                   13211:     }
                   13212:     if ($warning) {
                   13213:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13214:     }
                   13215:     return $output;
                   13216: }
                   13217: 
                   13218: sub get_extracted {
1.1056    raeburn  13219:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   13220:         $titles,$wantform) = @_;
1.1055    raeburn  13221:     my $count = 0;
                   13222:     my $depth = 0;
                   13223:     my $datatable;
1.1056    raeburn  13224:     my @hierarchy;
1.1055    raeburn  13225:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  13226:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   13227:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  13228:     foreach my $item (@{$contents}) {
                   13229:         $count ++;
1.1056    raeburn  13230:         @{$dirorder->{$count}} = @hierarchy;
                   13231:         $titles->{$count} = $item;
1.1055    raeburn  13232:         &archive_hierarchy($depth,$count,$parent,$children);
                   13233:         if ($wantform) {
                   13234:             $datatable .= &archive_row($is_dir->{$item},$item,
                   13235:                                        $currdir,$depth,$count);
                   13236:         }
                   13237:         if ($is_dir->{$item}) {
                   13238:             $depth ++;
1.1056    raeburn  13239:             push(@hierarchy,$count);
                   13240:             $parent->{$depth} = $count;
1.1055    raeburn  13241:             $datatable .=
                   13242:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  13243:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   13244:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  13245:             $depth --;
1.1056    raeburn  13246:             pop(@hierarchy);
1.1055    raeburn  13247:         }
                   13248:     }
                   13249:     return ($count,$datatable);
                   13250: }
                   13251: 
                   13252: sub recurse_extracted_archive {
1.1056    raeburn  13253:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   13254:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  13255:     my $result='';
1.1056    raeburn  13256:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   13257:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   13258:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  13259:         return $result;
                   13260:     }
                   13261:     my $dirptr = 16384;
                   13262:     my ($newdirlistref,$newlisterror) =
                   13263:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   13264:     if (ref($newdirlistref) eq 'ARRAY') {
                   13265:         foreach my $dir_line (@{$newdirlistref}) {
                   13266:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   13267:             unless ($item =~ /^\.+$/) {
                   13268:                 $$count ++;
1.1056    raeburn  13269:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   13270:                 $titles->{$$count} = $item;
1.1055    raeburn  13271:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  13272: 
1.1055    raeburn  13273:                 my $is_dir;
                   13274:                 if ($dirptr&$testdir) {
                   13275:                     $is_dir = 1;
                   13276:                 }
                   13277:                 if ($wantform) {
                   13278:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   13279:                 }
                   13280:                 if ($is_dir) {
                   13281:                     $$depth ++;
1.1056    raeburn  13282:                     push(@{$hierarchy},$$count);
                   13283:                     $parent->{$$depth} = $$count;
1.1055    raeburn  13284:                     $result .=
                   13285:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   13286:                                                    $docuname,$depth,$count,
1.1056    raeburn  13287:                                                    $hierarchy,$dirorder,$children,
                   13288:                                                    $parent,$titles,$wantform);
1.1055    raeburn  13289:                     $$depth --;
1.1056    raeburn  13290:                     pop(@{$hierarchy});
1.1055    raeburn  13291:                 }
                   13292:             }
                   13293:         }
                   13294:     }
                   13295:     return $result;
                   13296: }
                   13297: 
                   13298: sub archive_hierarchy {
                   13299:     my ($depth,$count,$parent,$children) =@_;
                   13300:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   13301:         if (exists($parent->{$depth})) {
                   13302:              $children->{$parent->{$depth}} .= $count.':';
                   13303:         }
                   13304:     }
                   13305:     return;
                   13306: }
                   13307: 
                   13308: sub archive_row {
                   13309:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   13310:     my ($name) = ($item =~ m{([^/]+)$});
                   13311:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  13312:                                        'display'    => 'Add as file',
1.1055    raeburn  13313:                                        'dependency' => 'Include as dependency',
                   13314:                                        'discard'    => 'Discard',
                   13315:                                       );
                   13316:     if ($is_dir) {
1.1059    raeburn  13317:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  13318:     }
1.1056    raeburn  13319:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   13320:     my $offset = 0;
1.1055    raeburn  13321:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  13322:         $offset ++;
1.1065    raeburn  13323:         if ($action ne 'display') {
                   13324:             $offset ++;
                   13325:         }  
1.1055    raeburn  13326:         $output .= '<td><span class="LC_nobreak">'.
                   13327:                    '<label><input type="radio" name="archive_'.$count.
                   13328:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   13329:         my $text = $choices{$action};
                   13330:         if ($is_dir) {
                   13331:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   13332:             if ($action eq 'display') {
1.1059    raeburn  13333:                 $text = &mt('Add as folder');
1.1055    raeburn  13334:             }
1.1056    raeburn  13335:         } else {
                   13336:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   13337: 
                   13338:         }
                   13339:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   13340:         if ($action eq 'dependency') {
                   13341:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   13342:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   13343:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   13344:                        '<option value=""></option>'."\n".
                   13345:                        '</select>'."\n".
                   13346:                        '</div>';
1.1059    raeburn  13347:         } elsif ($action eq 'display') {
                   13348:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   13349:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   13350:                        '</div>';
1.1055    raeburn  13351:         }
1.1056    raeburn  13352:         $output .= '</td>';
1.1055    raeburn  13353:     }
                   13354:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   13355:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   13356:     for (my $i=0; $i<$depth; $i++) {
                   13357:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   13358:     }
                   13359:     if ($is_dir) {
                   13360:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   13361:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   13362:     } else {
                   13363:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   13364:     }
                   13365:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   13366:                &end_data_table_row();
                   13367:     return $output;
                   13368: }
                   13369: 
                   13370: sub archive_options_form {
1.1065    raeburn  13371:     my ($form,$display,$count,$hiddenelem) = @_;
                   13372:     my %lt = &Apache::lonlocal::texthash(
                   13373:                perm => 'Permanently remove archive file?',
                   13374:                hows => 'How should each extracted item be incorporated in the course?',
                   13375:                cont => 'Content actions for all',
                   13376:                addf => 'Add as folder/file',
                   13377:                incd => 'Include as dependency for a displayed file',
                   13378:                disc => 'Discard',
                   13379:                no   => 'No',
                   13380:                yes  => 'Yes',
                   13381:                save => 'Save',
                   13382:     );
                   13383:     my $output = <<"END";
                   13384: <form name="$form" method="post" action="">
                   13385: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   13386: <label>
                   13387:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   13388: </label>
                   13389: &nbsp;
                   13390: <label>
                   13391:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   13392: </span>
                   13393: </p>
                   13394: <input type="hidden" name="phase" value="decompress_cleanup" />
                   13395: <br />$lt{'hows'}
                   13396: <div class="LC_columnSection">
                   13397:   <fieldset>
                   13398:     <legend>$lt{'cont'}</legend>
                   13399:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   13400:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   13401:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   13402:   </fieldset>
                   13403: </div>
                   13404: END
                   13405:     return $output.
1.1055    raeburn  13406:            &start_data_table()."\n".
1.1065    raeburn  13407:            $display."\n".
1.1055    raeburn  13408:            &end_data_table()."\n".
                   13409:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   13410:            $hiddenelem.
1.1065    raeburn  13411:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  13412:            '</form>';
                   13413: }
                   13414: 
                   13415: sub archive_javascript {
1.1056    raeburn  13416:     my ($startcount,$numitems,$titles,$children) = @_;
                   13417:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  13418:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  13419:     my $scripttag = <<START;
                   13420: <script type="text/javascript">
                   13421: // <![CDATA[
                   13422: 
                   13423: function checkAll(form,prefix) {
                   13424:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   13425:     for (var i=0; i < form.elements.length; i++) {
                   13426:         var id = form.elements[i].id;
                   13427:         if ((id != '') && (id != undefined)) {
                   13428:             if (idstr.test(id)) {
                   13429:                 if (form.elements[i].type == 'radio') {
                   13430:                     form.elements[i].checked = true;
1.1056    raeburn  13431:                     var nostart = i-$startcount;
1.1059    raeburn  13432:                     var offset = nostart%7;
                   13433:                     var count = (nostart-offset)/7;    
1.1056    raeburn  13434:                     dependencyCheck(form,count,offset);
1.1055    raeburn  13435:                 }
                   13436:             }
                   13437:         }
                   13438:     }
                   13439: }
                   13440: 
                   13441: function propagateCheck(form,count) {
                   13442:     if (count > 0) {
1.1059    raeburn  13443:         var startelement = $startcount + ((count-1) * 7);
                   13444:         for (var j=1; j<6; j++) {
                   13445:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  13446:                 var item = startelement + j; 
                   13447:                 if (form.elements[item].type == 'radio') {
                   13448:                     if (form.elements[item].checked) {
                   13449:                         containerCheck(form,count,j);
                   13450:                         break;
                   13451:                     }
1.1055    raeburn  13452:                 }
                   13453:             }
                   13454:         }
                   13455:     }
                   13456: }
                   13457: 
                   13458: numitems = $numitems
1.1056    raeburn  13459: var titles = new Array(numitems);
                   13460: var parents = new Array(numitems);
1.1055    raeburn  13461: for (var i=0; i<numitems; i++) {
1.1056    raeburn  13462:     parents[i] = new Array;
1.1055    raeburn  13463: }
1.1059    raeburn  13464: var maintitle = '$maintitle';
1.1055    raeburn  13465: 
                   13466: START
                   13467: 
1.1056    raeburn  13468:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   13469:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  13470:         for (my $i=0; $i<@contents; $i ++) {
                   13471:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   13472:         }
                   13473:     }
                   13474: 
1.1056    raeburn  13475:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   13476:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   13477:     }
                   13478: 
1.1055    raeburn  13479:     $scripttag .= <<END;
                   13480: 
                   13481: function containerCheck(form,count,offset) {
                   13482:     if (count > 0) {
1.1056    raeburn  13483:         dependencyCheck(form,count,offset);
1.1059    raeburn  13484:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  13485:         form.elements[item].checked = true;
                   13486:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13487:             if (parents[count].length > 0) {
                   13488:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  13489:                     containerCheck(form,parents[count][j],offset);
                   13490:                 }
                   13491:             }
                   13492:         }
                   13493:     }
                   13494: }
                   13495: 
                   13496: function dependencyCheck(form,count,offset) {
                   13497:     if (count > 0) {
1.1059    raeburn  13498:         var chosen = (offset+$startcount)+7*(count-1);
                   13499:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  13500:         var currtype = form.elements[depitem].type;
                   13501:         if (form.elements[chosen].value == 'dependency') {
                   13502:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   13503:             form.elements[depitem].options.length = 0;
                   13504:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  13505:             for (var i=1; i<=numitems; i++) {
                   13506:                 if (i == count) {
                   13507:                     continue;
                   13508:                 }
1.1059    raeburn  13509:                 var startelement = $startcount + (i-1) * 7;
                   13510:                 for (var j=1; j<6; j++) {
                   13511:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  13512:                         var item = startelement + j;
                   13513:                         if (form.elements[item].type == 'radio') {
                   13514:                             if (form.elements[item].checked) {
                   13515:                                 if (form.elements[item].value == 'display') {
                   13516:                                     var n = form.elements[depitem].options.length;
                   13517:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   13518:                                 }
                   13519:                             }
                   13520:                         }
                   13521:                     }
                   13522:                 }
                   13523:             }
                   13524:         } else {
                   13525:             document.getElementById('arc_depon_'+count).style.display='none';
                   13526:             form.elements[depitem].options.length = 0;
                   13527:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   13528:         }
1.1059    raeburn  13529:         titleCheck(form,count,offset);
1.1056    raeburn  13530:     }
                   13531: }
                   13532: 
                   13533: function propagateSelect(form,count,offset) {
                   13534:     if (count > 0) {
1.1065    raeburn  13535:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  13536:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   13537:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13538:             if (parents[count].length > 0) {
                   13539:                 for (var j=0; j<parents[count].length; j++) {
                   13540:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  13541:                 }
                   13542:             }
                   13543:         }
                   13544:     }
                   13545: }
1.1056    raeburn  13546: 
                   13547: function containerSelect(form,count,offset,picked) {
                   13548:     if (count > 0) {
1.1065    raeburn  13549:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  13550:         if (form.elements[item].type == 'radio') {
                   13551:             if (form.elements[item].value == 'dependency') {
                   13552:                 if (form.elements[item+1].type == 'select-one') {
                   13553:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   13554:                         if (form.elements[item+1].options[i].value == picked) {
                   13555:                             form.elements[item+1].selectedIndex = i;
                   13556:                             break;
                   13557:                         }
                   13558:                     }
                   13559:                 }
                   13560:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   13561:                     if (parents[count].length > 0) {
                   13562:                         for (var j=0; j<parents[count].length; j++) {
                   13563:                             containerSelect(form,parents[count][j],offset,picked);
                   13564:                         }
                   13565:                     }
                   13566:                 }
                   13567:             }
                   13568:         }
                   13569:     }
                   13570: }
                   13571: 
1.1059    raeburn  13572: function titleCheck(form,count,offset) {
                   13573:     if (count > 0) {
                   13574:         var chosen = (offset+$startcount)+7*(count-1);
                   13575:         var depitem = $startcount + ((count-1) * 7) + 2;
                   13576:         var currtype = form.elements[depitem].type;
                   13577:         if (form.elements[chosen].value == 'display') {
                   13578:             document.getElementById('arc_title_'+count).style.display='block';
                   13579:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   13580:                 document.getElementById('archive_title_'+count).value=maintitle;
                   13581:             }
                   13582:         } else {
                   13583:             document.getElementById('arc_title_'+count).style.display='none';
                   13584:             if (currtype == 'text') { 
                   13585:                 document.getElementById('archive_title_'+count).value='';
                   13586:             }
                   13587:         }
                   13588:     }
                   13589:     return;
                   13590: }
                   13591: 
1.1055    raeburn  13592: // ]]>
                   13593: </script>
                   13594: END
                   13595:     return $scripttag;
                   13596: }
                   13597: 
                   13598: sub process_extracted_files {
1.1067    raeburn  13599:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  13600:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  13601:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  13602:     my @ids=&Apache::lonnet::current_machine_ids();
                   13603:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  13604:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  13605:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   13606:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   13607:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   13608:         $pathtocheck = "$dir_root/$destination";
                   13609:         $dir = $dir_root;
                   13610:         $ishome = 1;
                   13611:     } else {
                   13612:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   13613:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  13614:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  13615:     }
                   13616:     my $currdir = "$dir_root/$destination";
                   13617:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   13618:     if ($env{'form.folderpath'}) {
                   13619:         my @items = split('&',$env{'form.folderpath'});
                   13620:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  13621:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   13622:             $containers{'0'}='page';
                   13623:         } else {
                   13624:             $containers{'0'}='sequence';
                   13625:         }
1.1055    raeburn  13626:     }
                   13627:     my @archdirs = &get_env_multiple('form.archive_directory');
                   13628:     if ($numitems) {
                   13629:         for (my $i=1; $i<=$numitems; $i++) {
                   13630:             my $path = $env{'form.archive_content_'.$i};
                   13631:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   13632:                 my $item = $1;
                   13633:                 $toplevelitems{$item} = $i;
                   13634:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   13635:                     $is_dir{$item} = 1;
                   13636:                 }
                   13637:             }
                   13638:         }
                   13639:     }
1.1067    raeburn  13640:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  13641:     if (keys(%toplevelitems) > 0) {
                   13642:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  13643:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   13644:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  13645:     }
1.1066    raeburn  13646:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  13647:     if ($numitems) {
                   13648:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  13649:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  13650:             my $path = $env{'form.archive_content_'.$i};
                   13651:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13652:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   13653:                     if ($prefix ne '' && $path ne '') {
                   13654:                         if (-e $prefix.$path) {
1.1066    raeburn  13655:                             if ((@archdirs > 0) && 
                   13656:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   13657:                                 $todeletedir{$prefix.$path} = 1;
                   13658:                             } else {
                   13659:                                 $todelete{$prefix.$path} = 1;
                   13660:                             }
1.1055    raeburn  13661:                         }
                   13662:                     }
                   13663:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  13664:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  13665:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  13666:                     $docstitle = $env{'form.archive_title_'.$i};
                   13667:                     if ($docstitle eq '') {
                   13668:                         $docstitle = $title;
                   13669:                     }
1.1055    raeburn  13670:                     $outer = 0;
1.1056    raeburn  13671:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13672:                         if (@{$dirorder{$i}} > 0) {
                   13673:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  13674:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   13675:                                     $outer = $item;
                   13676:                                     last;
                   13677:                                 }
                   13678:                             }
                   13679:                         }
                   13680:                     }
                   13681:                     my ($errtext,$fatal) = 
                   13682:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   13683:                                                '/'.$folders{$outer}.'.'.
                   13684:                                                $containers{$outer});
                   13685:                     next if ($fatal);
                   13686:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   13687:                         if ($context eq 'coursedocs') {
1.1056    raeburn  13688:                             $mapinner{$i} = time;
1.1055    raeburn  13689:                             $folders{$i} = 'default_'.$mapinner{$i};
                   13690:                             $containers{$i} = 'sequence';
                   13691:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13692:                                       $folders{$i}.'.'.$containers{$i};
                   13693:                             my $newidx = &LONCAPA::map::getresidx();
                   13694:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  13695:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  13696:                             push(@LONCAPA::map::order,$newidx);
                   13697:                             my ($outtext,$errtext) =
                   13698:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13699:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  13700:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  13701:                             $newseqid{$i} = $newidx;
1.1067    raeburn  13702:                             unless ($errtext) {
1.1075.2.128  raeburn  13703:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   13704:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   13705:                                             '</li>'."\n";
1.1067    raeburn  13706:                             }
1.1055    raeburn  13707:                         }
                   13708:                     } else {
                   13709:                         if ($context eq 'coursedocs') {
                   13710:                             my $newidx=&LONCAPA::map::getresidx();
                   13711:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   13712:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   13713:                                       $title;
1.1075.2.161.  .13(raeb 13714:-23):                             if (($outer !~ /\D/) &&
                   13715:-23):                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   13716:-23):                                 ($newidx !~ /\D/)) {
1.1075.2.128  raeburn  13717:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   13718:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  13719:                                 }
1.1075.2.128  raeburn  13720:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13721:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   13722:                                 }
                   13723:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   13724:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   13725:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   13726:                                         unless ($ishome) {
                   13727:                                             my $fetch = "$newdest{$i}/$title";
                   13728:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   13729:                                             $prompttofetch{$fetch} = 1;
                   13730:                                         }
                   13731:                                    }
                   13732:                                 }
                   13733:                                 $LONCAPA::map::resources[$newidx]=
                   13734:                                     $docstitle.':'.$url.':false:normal:res';
                   13735:                                 push(@LONCAPA::map::order, $newidx);
                   13736:                                 my ($outtext,$errtext)=
                   13737:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   13738:                                                             $docuname.'/'.$folders{$outer}.
                   13739:                                                             '.'.$containers{$outer},1,1);
                   13740:                                 unless ($errtext) {
                   13741:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   13742:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   13743:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   13744:                                                    '</li>'."\n";
                   13745:                                     }
1.1067    raeburn  13746:                                 }
1.1075.2.128  raeburn  13747:                             } else {
                   13748:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13749:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  13750:                             }
1.1055    raeburn  13751:                         }
                   13752:                     }
1.1075.2.11  raeburn  13753:                 }
                   13754:             } else {
1.1075.2.128  raeburn  13755:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13756:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  13757:             }
                   13758:         }
                   13759:         for (my $i=1; $i<=$numitems; $i++) {
                   13760:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   13761:             my $path = $env{'form.archive_content_'.$i};
                   13762:             if ($path =~ /^\Q$pathtocheck\E/) {
                   13763:                 my ($title) = ($path =~ m{/([^/]+)$});
                   13764:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   13765:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   13766:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   13767:                         my ($itemidx,$fullpath,$relpath);
                   13768:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   13769:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  13770:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  13771:                                 if ($dirorder{$i}->[$j] eq $container) {
                   13772:                                     $itemidx = $j;
1.1056    raeburn  13773:                                 }
                   13774:                             }
1.1075.2.11  raeburn  13775:                         }
                   13776:                         if ($itemidx eq '') {
                   13777:                             $itemidx =  0;
                   13778:                         }
                   13779:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   13780:                             if ($mapinner{$referrer{$i}}) {
                   13781:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   13782:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13783:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13784:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13785:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13786:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13787:                                             if (!-e $fullpath) {
                   13788:                                                 mkdir($fullpath,0755);
1.1056    raeburn  13789:                                             }
                   13790:                                         }
1.1075.2.11  raeburn  13791:                                     } else {
                   13792:                                         last;
1.1056    raeburn  13793:                                     }
1.1075.2.11  raeburn  13794:                                 }
                   13795:                             }
                   13796:                         } elsif ($newdest{$referrer{$i}}) {
                   13797:                             $fullpath = $newdest{$referrer{$i}};
                   13798:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   13799:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   13800:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   13801:                                     last;
                   13802:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   13803:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   13804:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13805:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   13806:                                         if (!-e $fullpath) {
                   13807:                                             mkdir($fullpath,0755);
1.1056    raeburn  13808:                                         }
                   13809:                                     }
1.1075.2.11  raeburn  13810:                                 } else {
                   13811:                                     last;
1.1056    raeburn  13812:                                 }
1.1075.2.11  raeburn  13813:                             }
                   13814:                         }
                   13815:                         if ($fullpath ne '') {
                   13816:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  13817:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   13818:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   13819:                                 }
1.1075.2.11  raeburn  13820:                             }
                   13821:                             if (-e "$fullpath/$title") {
                   13822:                                 my $showpath;
                   13823:                                 if ($relpath ne '') {
                   13824:                                     $showpath = "$relpath/$title";
                   13825:                                 } else {
                   13826:                                     $showpath = "/$title";
1.1056    raeburn  13827:                                 }
1.1075.2.128  raeburn  13828:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   13829:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   13830:                                            '</li>'."\n";
                   13831:                                 unless ($ishome) {
                   13832:                                     my $fetch = "$fullpath/$title";
                   13833:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   13834:                                     $prompttofetch{$fetch} = 1;
                   13835:                                 }
1.1055    raeburn  13836:                             }
                   13837:                         }
                   13838:                     }
1.1075.2.11  raeburn  13839:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   13840:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  13841:                                     &HTML::Entities::encode($path,'<>&"'),
                   13842:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   13843:                                 '<br />';
1.1055    raeburn  13844:                 }
                   13845:             } else {
1.1075.2.128  raeburn  13846:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   13847:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  13848:             }
                   13849:         }
                   13850:         if (keys(%todelete)) {
                   13851:             foreach my $key (keys(%todelete)) {
                   13852:                 unlink($key);
1.1066    raeburn  13853:             }
                   13854:         }
                   13855:         if (keys(%todeletedir)) {
                   13856:             foreach my $key (keys(%todeletedir)) {
                   13857:                 rmdir($key);
                   13858:             }
                   13859:         }
                   13860:         foreach my $dir (sort(keys(%is_dir))) {
                   13861:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   13862:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  13863:             }
                   13864:         }
1.1067    raeburn  13865:         if ($result ne '') {
                   13866:             $output .= '<ul>'."\n".
                   13867:                        $result."\n".
                   13868:                        '</ul>';
                   13869:         }
                   13870:         unless ($ishome) {
                   13871:             my $replicationfail;
                   13872:             foreach my $item (keys(%prompttofetch)) {
                   13873:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   13874:                 unless ($fetchresult eq 'ok') {
                   13875:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   13876:                 }
                   13877:             }
                   13878:             if ($replicationfail) {
                   13879:                 $output .= '<p class="LC_error">'.
                   13880:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   13881:                            $replicationfail.
                   13882:                            '</ul></p>';
                   13883:             }
                   13884:         }
1.1055    raeburn  13885:     } else {
                   13886:         $warning = &mt('No items found in archive.');
                   13887:     }
                   13888:     if ($error) {
                   13889:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   13890:                    $error.'</p>'."\n";
                   13891:     }
                   13892:     if ($warning) {
                   13893:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   13894:     }
                   13895:     return $output;
                   13896: }
                   13897: 
1.1066    raeburn  13898: sub cleanup_empty_dirs {
                   13899:     my ($path) = @_;
                   13900:     if (($path ne '') && (-d $path)) {
                   13901:         if (opendir(my $dirh,$path)) {
                   13902:             my @dircontents = grep(!/^\./,readdir($dirh));
                   13903:             my $numitems = 0;
                   13904:             foreach my $item (@dircontents) {
                   13905:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  13906:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  13907:                     if (-e "$path/$item") {
                   13908:                         $numitems ++;
                   13909:                     }
                   13910:                 } else {
                   13911:                     $numitems ++;
                   13912:                 }
                   13913:             }
                   13914:             if ($numitems == 0) {
                   13915:                 rmdir($path);
                   13916:             }
                   13917:             closedir($dirh);
                   13918:         }
                   13919:     }
                   13920:     return;
                   13921: }
                   13922: 
1.41      ng       13923: =pod
1.45      matthew  13924: 
1.1075.2.56  raeburn  13925: =item * &get_folder_hierarchy()
1.1068    raeburn  13926: 
                   13927: Provides hierarchy of names of folders/sub-folders containing the current
                   13928: item,
                   13929: 
                   13930: Inputs: 3
                   13931:      - $navmap - navmaps object
                   13932: 
                   13933:      - $map - url for map (either the trigger itself, or map containing
                   13934:                            the resource, which is the trigger).
                   13935: 
                   13936:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   13937: 
                   13938: Outputs: 1 @pathitems - array of folder/subfolder names.
                   13939: 
                   13940: =cut
                   13941: 
                   13942: sub get_folder_hierarchy {
                   13943:     my ($navmap,$map,$showitem) = @_;
                   13944:     my @pathitems;
                   13945:     if (ref($navmap)) {
                   13946:         my $mapres = $navmap->getResourceByUrl($map);
                   13947:         if (ref($mapres)) {
                   13948:             my $pcslist = $mapres->map_hierarchy();
                   13949:             if ($pcslist ne '') {
                   13950:                 my @pcs = split(/,/,$pcslist);
                   13951:                 foreach my $pc (@pcs) {
                   13952:                     if ($pc == 1) {
1.1075.2.38  raeburn  13953:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  13954:                     } else {
                   13955:                         my $res = $navmap->getByMapPc($pc);
                   13956:                         if (ref($res)) {
                   13957:                             my $title = $res->compTitle();
                   13958:                             $title =~ s/\W+/_/g;
                   13959:                             if ($title ne '') {
                   13960:                                 push(@pathitems,$title);
                   13961:                             }
                   13962:                         }
                   13963:                     }
                   13964:                 }
                   13965:             }
1.1071    raeburn  13966:             if ($showitem) {
                   13967:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13968:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13969:                 } else {
                   13970:                     my $maptitle = $mapres->compTitle();
                   13971:                     $maptitle =~ s/\W+/_/g;
                   13972:                     if ($maptitle ne '') {
                   13973:                         push(@pathitems,$maptitle);
                   13974:                     }
1.1068    raeburn  13975:                 }
                   13976:             }
                   13977:         }
                   13978:     }
                   13979:     return @pathitems;
                   13980: }
                   13981: 
                   13982: =pod
                   13983: 
1.1015    raeburn  13984: =item * &get_turnedin_filepath()
                   13985: 
                   13986: Determines path in a user's portfolio file for storage of files uploaded
                   13987: to a specific essayresponse or dropbox item.
                   13988: 
                   13989: Inputs: 3 required + 1 optional.
                   13990: $symb is symb for resource, $uname and $udom are for current user (required).
                   13991: $caller is optional (can be "submission", if routine is called when storing
                   13992: an upoaded file when "Submit Answer" button was pressed).
                   13993: 
                   13994: Returns array containing $path and $multiresp. 
                   13995: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13996: than one file upload item.  Callers of routine should append partid as a 
                   13997: subdirectory to $path in cases where $multiresp is 1.
                   13998: 
                   13999: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   14000: 
                   14001: =cut
                   14002: 
                   14003: sub get_turnedin_filepath {
                   14004:     my ($symb,$uname,$udom,$caller) = @_;
                   14005:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   14006:     my $turnindir;
                   14007:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   14008:     $turnindir = $userhash{'turnindir'};
                   14009:     my ($path,$multiresp);
                   14010:     if ($turnindir eq '') {
                   14011:         if ($caller eq 'submission') {
                   14012:             $turnindir = &mt('turned in');
                   14013:             $turnindir =~ s/\W+/_/g;
                   14014:             my %newhash = (
                   14015:                             'turnindir' => $turnindir,
                   14016:                           );
                   14017:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   14018:         }
                   14019:     }
                   14020:     if ($turnindir ne '') {
                   14021:         $path = '/'.$turnindir.'/';
                   14022:         my ($multipart,$turnin,@pathitems);
                   14023:         my $navmap = Apache::lonnavmaps::navmap->new();
                   14024:         if (defined($navmap)) {
                   14025:             my $mapres = $navmap->getResourceByUrl($map);
                   14026:             if (ref($mapres)) {
                   14027:                 my $pcslist = $mapres->map_hierarchy();
                   14028:                 if ($pcslist ne '') {
                   14029:                     foreach my $pc (split(/,/,$pcslist)) {
                   14030:                         my $res = $navmap->getByMapPc($pc);
                   14031:                         if (ref($res)) {
                   14032:                             my $title = $res->compTitle();
                   14033:                             $title =~ s/\W+/_/g;
                   14034:                             if ($title ne '') {
1.1075.2.48  raeburn  14035:                                 if (($pc > 1) && (length($title) > 12)) {
                   14036:                                     $title = substr($title,0,12);
                   14037:                                 }
1.1015    raeburn  14038:                                 push(@pathitems,$title);
                   14039:                             }
                   14040:                         }
                   14041:                     }
                   14042:                 }
                   14043:                 my $maptitle = $mapres->compTitle();
                   14044:                 $maptitle =~ s/\W+/_/g;
                   14045:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  14046:                     if (length($maptitle) > 12) {
                   14047:                         $maptitle = substr($maptitle,0,12);
                   14048:                     }
1.1015    raeburn  14049:                     push(@pathitems,$maptitle);
                   14050:                 }
                   14051:                 unless ($env{'request.state'} eq 'construct') {
                   14052:                     my $res = $navmap->getBySymb($symb);
                   14053:                     if (ref($res)) {
                   14054:                         my $partlist = $res->parts();
                   14055:                         my $totaluploads = 0;
                   14056:                         if (ref($partlist) eq 'ARRAY') {
                   14057:                             foreach my $part (@{$partlist}) {
                   14058:                                 my @types = $res->responseType($part);
                   14059:                                 my @ids = $res->responseIds($part);
                   14060:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   14061:                                     if ($types[$i] eq 'essay') {
                   14062:                                         my $partid = $part.'_'.$ids[$i];
                   14063:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   14064:                                             $totaluploads ++;
                   14065:                                         }
                   14066:                                     }
                   14067:                                 }
                   14068:                             }
                   14069:                             if ($totaluploads > 1) {
                   14070:                                 $multiresp = 1;
                   14071:                             }
                   14072:                         }
                   14073:                     }
                   14074:                 }
                   14075:             } else {
                   14076:                 return;
                   14077:             }
                   14078:         } else {
                   14079:             return;
                   14080:         }
                   14081:         my $restitle=&Apache::lonnet::gettitle($symb);
                   14082:         $restitle =~ s/\W+/_/g;
                   14083:         if ($restitle eq '') {
                   14084:             $restitle = ($resurl =~ m{/[^/]+$});
                   14085:             if ($restitle eq '') {
                   14086:                 $restitle = time;
                   14087:             }
                   14088:         }
1.1075.2.48  raeburn  14089:         if (length($restitle) > 12) {
                   14090:             $restitle = substr($restitle,0,12);
                   14091:         }
1.1015    raeburn  14092:         push(@pathitems,$restitle);
                   14093:         $path .= join('/',@pathitems);
                   14094:     }
                   14095:     return ($path,$multiresp);
                   14096: }
                   14097: 
                   14098: =pod
                   14099: 
1.464     albertel 14100: =back
1.41      ng       14101: 
1.112     bowersj2 14102: =head1 CSV Upload/Handling functions
1.38      albertel 14103: 
1.41      ng       14104: =over 4
                   14105: 
1.648     raeburn  14106: =item * &upfile_store($r)
1.41      ng       14107: 
                   14108: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 14109: needs $env{'form.upfile'}
1.41      ng       14110: returns $datatoken to be put into hidden field
                   14111: 
                   14112: =cut
1.31      albertel 14113: 
                   14114: sub upfile_store {
                   14115:     my $r=shift;
1.258     albertel 14116:     $env{'form.upfile'}=~s/\r/\n/gs;
                   14117:     $env{'form.upfile'}=~s/\f/\n/gs;
                   14118:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   14119:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 14120: 
1.1075.2.128  raeburn  14121:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   14122:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   14123:                                      time.'_'.$$);
                   14124:     return if ($datatoken eq '');
                   14125: 
1.31      albertel 14126:     {
1.158     raeburn  14127:         my $datafile = $r->dir_config('lonDaemons').
                   14128:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  14129:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 14130:             print $fh $env{'form.upfile'};
1.158     raeburn  14131:             close($fh);
                   14132:         }
1.31      albertel 14133:     }
                   14134:     return $datatoken;
                   14135: }
                   14136: 
1.56      matthew  14137: =pod
                   14138: 
1.1075.2.128  raeburn  14139: =item * &load_tmp_file($r,$datatoken)
1.41      ng       14140: 
                   14141: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  14142: $datatoken is the name to assign to the temporary file.
1.258     albertel 14143: sets $env{'form.upfile'} to the contents of the file
1.41      ng       14144: 
                   14145: =cut
1.31      albertel 14146: 
                   14147: sub load_tmp_file {
1.1075.2.128  raeburn  14148:     my ($r,$datatoken) = @_;
                   14149:     return if ($datatoken eq '');
1.31      albertel 14150:     my @studentdata=();
                   14151:     {
1.158     raeburn  14152:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  14153:                               '/tmp/'.$datatoken.'.tmp';
                   14154:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  14155:             @studentdata=<$fh>;
                   14156:             close($fh);
                   14157:         }
1.31      albertel 14158:     }
1.258     albertel 14159:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 14160: }
                   14161: 
1.1075.2.128  raeburn  14162: sub valid_datatoken {
                   14163:     my ($datatoken) = @_;
1.1075.2.131  raeburn  14164:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  14165:         return $datatoken;
                   14166:     }
                   14167:     return;
                   14168: }
                   14169: 
1.56      matthew  14170: =pod
                   14171: 
1.648     raeburn  14172: =item * &upfile_record_sep()
1.41      ng       14173: 
                   14174: Separate uploaded file into records
                   14175: returns array of records,
1.258     albertel 14176: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       14177: 
                   14178: =cut
1.31      albertel 14179: 
                   14180: sub upfile_record_sep {
1.258     albertel 14181:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 14182:     } else {
1.248     albertel 14183: 	my @records;
1.258     albertel 14184: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 14185: 	    if ($line=~/^\s*$/) { next; }
                   14186: 	    push(@records,$line);
                   14187: 	}
                   14188: 	return @records;
1.31      albertel 14189:     }
                   14190: }
                   14191: 
1.56      matthew  14192: =pod
                   14193: 
1.648     raeburn  14194: =item * &record_sep($record)
1.41      ng       14195: 
1.258     albertel 14196: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       14197: 
                   14198: =cut
                   14199: 
1.263     www      14200: sub takeleft {
                   14201:     my $index=shift;
                   14202:     return substr('0000'.$index,-4,4);
                   14203: }
                   14204: 
1.31      albertel 14205: sub record_sep {
                   14206:     my $record=shift;
                   14207:     my %components=();
1.258     albertel 14208:     if ($env{'form.upfiletype'} eq 'xml') {
                   14209:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 14210:         my $i=0;
1.356     albertel 14211:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 14212:             $field=~s/^(\"|\')//;
                   14213:             $field=~s/(\"|\')$//;
1.263     www      14214:             $components{&takeleft($i)}=$field;
1.31      albertel 14215:             $i++;
                   14216:         }
1.258     albertel 14217:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 14218:         my $i=0;
1.356     albertel 14219:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 14220:             $field=~s/^(\"|\')//;
                   14221:             $field=~s/(\"|\')$//;
1.263     www      14222:             $components{&takeleft($i)}=$field;
1.31      albertel 14223:             $i++;
                   14224:         }
                   14225:     } else {
1.561     www      14226:         my $separator=',';
1.480     banghart 14227:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      14228:             $separator=';';
1.480     banghart 14229:         }
1.31      albertel 14230:         my $i=0;
1.561     www      14231: # the character we are looking for to indicate the end of a quote or a record 
                   14232:         my $looking_for=$separator;
                   14233: # do not add the characters to the fields
                   14234:         my $ignore=0;
                   14235: # we just encountered a separator (or the beginning of the record)
                   14236:         my $just_found_separator=1;
                   14237: # store the field we are working on here
                   14238:         my $field='';
                   14239: # work our way through all characters in record
                   14240:         foreach my $character ($record=~/(.)/g) {
                   14241:             if ($character eq $looking_for) {
                   14242:                if ($character ne $separator) {
                   14243: # Found the end of a quote, again looking for separator
                   14244:                   $looking_for=$separator;
                   14245:                   $ignore=1;
                   14246:                } else {
                   14247: # Found a separator, store away what we got
                   14248:                   $components{&takeleft($i)}=$field;
                   14249: 	          $i++;
                   14250:                   $just_found_separator=1;
                   14251:                   $ignore=0;
                   14252:                   $field='';
                   14253:                }
                   14254:                next;
                   14255:             }
                   14256: # single or double quotation marks after a separator indicate beginning of a quote
                   14257: # we are now looking for the end of the quote and need to ignore separators
                   14258:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   14259:                $looking_for=$character;
                   14260:                next;
                   14261:             }
                   14262: # ignore would be true after we reached the end of a quote
                   14263:             if ($ignore) { next; }
                   14264:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   14265:             $field.=$character;
                   14266:             $just_found_separator=0; 
1.31      albertel 14267:         }
1.561     www      14268: # catch the very last entry, since we never encountered the separator
                   14269:         $components{&takeleft($i)}=$field;
1.31      albertel 14270:     }
                   14271:     return %components;
                   14272: }
                   14273: 
1.144     matthew  14274: ######################################################
                   14275: ######################################################
                   14276: 
1.56      matthew  14277: =pod
                   14278: 
1.648     raeburn  14279: =item * &upfile_select_html()
1.41      ng       14280: 
1.144     matthew  14281: Return HTML code to select a file from the users machine and specify 
                   14282: the file type.
1.41      ng       14283: 
                   14284: =cut
                   14285: 
1.144     matthew  14286: ######################################################
                   14287: ######################################################
1.31      albertel 14288: sub upfile_select_html {
1.144     matthew  14289:     my %Types = (
                   14290:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 14291:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  14292:                  space => &mt('Space separated'),
                   14293:                  tab   => &mt('Tabulator separated'),
                   14294: #                 xml   => &mt('HTML/XML'),
                   14295:                  );
                   14296:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  14297:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  14298:     foreach my $type (sort(keys(%Types))) {
                   14299:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   14300:     }
                   14301:     $Str .= "</select>\n";
                   14302:     return $Str;
1.31      albertel 14303: }
                   14304: 
1.301     albertel 14305: sub get_samples {
                   14306:     my ($records,$toget) = @_;
                   14307:     my @samples=({});
                   14308:     my $got=0;
                   14309:     foreach my $rec (@$records) {
                   14310: 	my %temp = &record_sep($rec);
                   14311: 	if (! grep(/\S/, values(%temp))) { next; }
                   14312: 	if (%temp) {
                   14313: 	    $samples[$got]=\%temp;
                   14314: 	    $got++;
                   14315: 	    if ($got == $toget) { last; }
                   14316: 	}
                   14317:     }
                   14318:     return \@samples;
                   14319: }
                   14320: 
1.144     matthew  14321: ######################################################
                   14322: ######################################################
                   14323: 
1.56      matthew  14324: =pod
                   14325: 
1.648     raeburn  14326: =item * &csv_print_samples($r,$records)
1.41      ng       14327: 
                   14328: Prints a table of sample values from each column uploaded $r is an
                   14329: Apache Request ref, $records is an arrayref from
                   14330: &Apache::loncommon::upfile_record_sep
                   14331: 
                   14332: =cut
                   14333: 
1.144     matthew  14334: ######################################################
                   14335: ######################################################
1.31      albertel 14336: sub csv_print_samples {
                   14337:     my ($r,$records) = @_;
1.662     bisitz   14338:     my $samples = &get_samples($records,5);
1.301     albertel 14339: 
1.594     raeburn  14340:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   14341:               &start_data_table_header_row());
1.356     albertel 14342:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   14343:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  14344:     $r->print(&end_data_table_header_row());
1.301     albertel 14345:     foreach my $hash (@$samples) {
1.594     raeburn  14346: 	$r->print(&start_data_table_row());
1.356     albertel 14347: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 14348: 	    $r->print('<td>');
1.356     albertel 14349: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 14350: 	    $r->print('</td>');
                   14351: 	}
1.594     raeburn  14352: 	$r->print(&end_data_table_row());
1.31      albertel 14353:     }
1.594     raeburn  14354:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 14355: }
                   14356: 
1.144     matthew  14357: ######################################################
                   14358: ######################################################
                   14359: 
1.56      matthew  14360: =pod
                   14361: 
1.648     raeburn  14362: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       14363: 
                   14364: Prints a table to create associations between values and table columns.
1.144     matthew  14365: 
1.41      ng       14366: $r is an Apache Request ref,
                   14367: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  14368: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       14369: 
                   14370: =cut
                   14371: 
1.144     matthew  14372: ######################################################
                   14373: ######################################################
1.31      albertel 14374: sub csv_print_select_table {
                   14375:     my ($r,$records,$d) = @_;
1.301     albertel 14376:     my $i=0;
                   14377:     my $samples = &get_samples($records,1);
1.144     matthew  14378:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  14379: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  14380:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  14381:               '<th>'.&mt('Column').'</th>'.
                   14382:               &end_data_table_header_row()."\n");
1.356     albertel 14383:     foreach my $array_ref (@$d) {
                   14384: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  14385: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 14386: 
1.875     bisitz   14387: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  14388: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 14389: 	$r->print('<option value="none"></option>');
1.356     albertel 14390: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   14391: 	    $r->print('<option value="'.$sample.'"'.
                   14392:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   14393:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 14394: 	}
1.594     raeburn  14395: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 14396: 	$i++;
                   14397:     }
1.594     raeburn  14398:     $r->print(&end_data_table());
1.31      albertel 14399:     $i--;
                   14400:     return $i;
                   14401: }
1.56      matthew  14402: 
1.144     matthew  14403: ######################################################
                   14404: ######################################################
                   14405: 
1.56      matthew  14406: =pod
1.31      albertel 14407: 
1.648     raeburn  14408: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       14409: 
                   14410: Prints a table of sample values from the upload and can make associate samples to internal names.
                   14411: 
                   14412: $r is an Apache Request ref,
                   14413: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   14414: $d is an array of 2 element arrays (internal name, displayed name)
                   14415: 
                   14416: =cut
                   14417: 
1.144     matthew  14418: ######################################################
                   14419: ######################################################
1.31      albertel 14420: sub csv_samples_select_table {
                   14421:     my ($r,$records,$d) = @_;
                   14422:     my $i=0;
1.144     matthew  14423:     #
1.662     bisitz   14424:     my $max_samples = 5;
                   14425:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  14426:     $r->print(&start_data_table().
                   14427:               &start_data_table_header_row().'<th>'.
                   14428:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   14429:               &end_data_table_header_row());
1.301     albertel 14430: 
                   14431:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  14432: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  14433: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 14434: 	foreach my $option (@$d) {
                   14435: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  14436: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 14437:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  14438:                       $display.'</option>');
1.31      albertel 14439: 	}
                   14440: 	$r->print('</select></td><td>');
1.662     bisitz   14441: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 14442: 	    if (defined($samples->[$line]{$key})) { 
                   14443: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   14444: 	    }
                   14445: 	}
1.594     raeburn  14446: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 14447: 	$i++;
                   14448:     }
1.594     raeburn  14449:     $r->print(&end_data_table());
1.31      albertel 14450:     $i--;
                   14451:     return($i);
1.115     matthew  14452: }
                   14453: 
1.144     matthew  14454: ######################################################
                   14455: ######################################################
                   14456: 
1.115     matthew  14457: =pod
                   14458: 
1.648     raeburn  14459: =item * &clean_excel_name($name)
1.115     matthew  14460: 
                   14461: Returns a replacement for $name which does not contain any illegal characters.
                   14462: 
                   14463: =cut
                   14464: 
1.144     matthew  14465: ######################################################
                   14466: ######################################################
1.115     matthew  14467: sub clean_excel_name {
                   14468:     my ($name) = @_;
                   14469:     $name =~ s/[:\*\?\/\\]//g;
                   14470:     if (length($name) > 31) {
                   14471:         $name = substr($name,0,31);
                   14472:     }
                   14473:     return $name;
1.25      albertel 14474: }
1.84      albertel 14475: 
1.85      albertel 14476: =pod
                   14477: 
1.648     raeburn  14478: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 14479: 
                   14480: Returns either 1 or undef
                   14481: 
                   14482: 1 if the part is to be hidden, undef if it is to be shown
                   14483: 
                   14484: Arguments are:
                   14485: 
                   14486: $id the id of the part to be checked
                   14487: $symb, optional the symb of the resource to check
                   14488: $udom, optional the domain of the user to check for
                   14489: $uname, optional the username of the user to check for
                   14490: 
                   14491: =cut
1.84      albertel 14492: 
                   14493: sub check_if_partid_hidden {
                   14494:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 14495:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 14496: 					 $symb,$udom,$uname);
1.141     albertel 14497:     my $truth=1;
                   14498:     #if the string starts with !, then the list is the list to show not hide
                   14499:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 14500:     my @hiddenlist=split(/,/,$hiddenparts);
                   14501:     foreach my $checkid (@hiddenlist) {
1.141     albertel 14502: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 14503:     }
1.141     albertel 14504:     return !$truth;
1.84      albertel 14505: }
1.127     matthew  14506: 
1.138     matthew  14507: 
                   14508: ############################################################
                   14509: ############################################################
                   14510: 
                   14511: =pod
                   14512: 
1.157     matthew  14513: =back 
                   14514: 
1.138     matthew  14515: =head1 cgi-bin script and graphing routines
                   14516: 
1.157     matthew  14517: =over 4
                   14518: 
1.648     raeburn  14519: =item * &get_cgi_id()
1.138     matthew  14520: 
                   14521: Inputs: none
                   14522: 
                   14523: Returns an id which can be used to pass environment variables
                   14524: to various cgi-bin scripts.  These environment variables will
                   14525: be removed from the users environment after a given time by
                   14526: the routine &Apache::lonnet::transfer_profile_to_env.
                   14527: 
                   14528: =cut
                   14529: 
                   14530: ############################################################
                   14531: ############################################################
1.152     albertel 14532: my $uniq=0;
1.136     matthew  14533: sub get_cgi_id {
1.154     albertel 14534:     $uniq=($uniq+1)%100000;
1.280     albertel 14535:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  14536: }
                   14537: 
1.127     matthew  14538: ############################################################
                   14539: ############################################################
                   14540: 
                   14541: =pod
                   14542: 
1.648     raeburn  14543: =item * &DrawBarGraph()
1.127     matthew  14544: 
1.138     matthew  14545: Facilitates the plotting of data in a (stacked) bar graph.
                   14546: Puts plot definition data into the users environment in order for 
                   14547: graph.png to plot it.  Returns an <img> tag for the plot.
                   14548: The bars on the plot are labeled '1','2',...,'n'.
                   14549: 
                   14550: Inputs:
                   14551: 
                   14552: =over 4
                   14553: 
                   14554: =item $Title: string, the title of the plot
                   14555: 
                   14556: =item $xlabel: string, text describing the X-axis of the plot
                   14557: 
                   14558: =item $ylabel: string, text describing the Y-axis of the plot
                   14559: 
                   14560: =item $Max: scalar, the maximum Y value to use in the plot
                   14561: If $Max is < any data point, the graph will not be rendered.
                   14562: 
1.140     matthew  14563: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  14564: they are plotted.  If undefined, default values will be used.
                   14565: 
1.178     matthew  14566: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   14567: 
1.138     matthew  14568: =item @Values: An array of array references.  Each array reference holds data
                   14569: to be plotted in a stacked bar chart.
                   14570: 
1.239     matthew  14571: =item If the final element of @Values is a hash reference the key/value
                   14572: pairs will be added to the graph definition.
                   14573: 
1.138     matthew  14574: =back
                   14575: 
                   14576: Returns:
                   14577: 
                   14578: An <img> tag which references graph.png and the appropriate identifying
                   14579: information for the plot.
                   14580: 
1.127     matthew  14581: =cut
                   14582: 
                   14583: ############################################################
                   14584: ############################################################
1.134     matthew  14585: sub DrawBarGraph {
1.178     matthew  14586:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  14587:     #
                   14588:     if (! defined($colors)) {
                   14589:         $colors = ['#33ff00', 
                   14590:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   14591:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   14592:                   ]; 
                   14593:     }
1.228     matthew  14594:     my $extra_settings = {};
                   14595:     if (ref($Values[-1]) eq 'HASH') {
                   14596:         $extra_settings = pop(@Values);
                   14597:     }
1.127     matthew  14598:     #
1.136     matthew  14599:     my $identifier = &get_cgi_id();
                   14600:     my $id = 'cgi.'.$identifier;        
1.129     matthew  14601:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  14602:         return '';
                   14603:     }
1.225     matthew  14604:     #
                   14605:     my @Labels;
                   14606:     if (defined($labels)) {
                   14607:         @Labels = @$labels;
                   14608:     } else {
                   14609:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  14610:             push(@Labels,$i+1);
1.225     matthew  14611:         }
                   14612:     }
                   14613:     #
1.129     matthew  14614:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  14615:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  14616:     my %ValuesHash;
                   14617:     my $NumSets=1;
                   14618:     foreach my $array (@Values) {
                   14619:         next if (! ref($array));
1.136     matthew  14620:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  14621:             join(',',@$array);
1.129     matthew  14622:     }
1.127     matthew  14623:     #
1.136     matthew  14624:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  14625:     if ($NumBars < 3) {
                   14626:         $width = 120+$NumBars*32;
1.220     matthew  14627:         $xskip = 1;
1.225     matthew  14628:         $bar_width = 30;
                   14629:     } elsif ($NumBars < 5) {
                   14630:         $width = 120+$NumBars*20;
                   14631:         $xskip = 1;
                   14632:         $bar_width = 20;
1.220     matthew  14633:     } elsif ($NumBars < 10) {
1.136     matthew  14634:         $width = 120+$NumBars*15;
                   14635:         $xskip = 1;
                   14636:         $bar_width = 15;
                   14637:     } elsif ($NumBars <= 25) {
                   14638:         $width = 120+$NumBars*11;
                   14639:         $xskip = 5;
                   14640:         $bar_width = 8;
                   14641:     } elsif ($NumBars <= 50) {
                   14642:         $width = 120+$NumBars*8;
                   14643:         $xskip = 5;
                   14644:         $bar_width = 4;
                   14645:     } else {
                   14646:         $width = 120+$NumBars*8;
                   14647:         $xskip = 5;
                   14648:         $bar_width = 4;
                   14649:     }
                   14650:     #
1.137     matthew  14651:     $Max = 1 if ($Max < 1);
                   14652:     if ( int($Max) < $Max ) {
                   14653:         $Max++;
                   14654:         $Max = int($Max);
                   14655:     }
1.127     matthew  14656:     $Title  = '' if (! defined($Title));
                   14657:     $xlabel = '' if (! defined($xlabel));
                   14658:     $ylabel = '' if (! defined($ylabel));
1.369     www      14659:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   14660:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   14661:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  14662:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  14663:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   14664:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   14665:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   14666:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14667:     $ValuesHash{$id.'.height'}   = $height;
                   14668:     $ValuesHash{$id.'.width'}    = $width;
                   14669:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   14670:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   14671:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  14672:     #
1.228     matthew  14673:     # Deal with other parameters
                   14674:     while (my ($key,$value) = each(%$extra_settings)) {
                   14675:         $ValuesHash{$id.'.'.$key} = $value;
                   14676:     }
                   14677:     #
1.646     raeburn  14678:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  14679:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14680: }
                   14681: 
                   14682: ############################################################
                   14683: ############################################################
                   14684: 
                   14685: =pod
                   14686: 
1.648     raeburn  14687: =item * &DrawXYGraph()
1.137     matthew  14688: 
1.138     matthew  14689: Facilitates the plotting of data in an XY graph.
                   14690: Puts plot definition data into the users environment in order for 
                   14691: graph.png to plot it.  Returns an <img> tag for the plot.
                   14692: 
                   14693: Inputs:
                   14694: 
                   14695: =over 4
                   14696: 
                   14697: =item $Title: string, the title of the plot
                   14698: 
                   14699: =item $xlabel: string, text describing the X-axis of the plot
                   14700: 
                   14701: =item $ylabel: string, text describing the Y-axis of the plot
                   14702: 
                   14703: =item $Max: scalar, the maximum Y value to use in the plot
                   14704: If $Max is < any data point, the graph will not be rendered.
                   14705: 
                   14706: =item $colors: Array ref containing the hex color codes for the data to be 
                   14707: plotted in.  If undefined, default values will be used.
                   14708: 
                   14709: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14710: 
                   14711: =item $Ydata: Array ref containing Array refs.  
1.185     www      14712: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  14713: 
                   14714: =item %Values: hash indicating or overriding any default values which are 
                   14715: passed to graph.png.  
                   14716: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14717: 
                   14718: =back
                   14719: 
                   14720: Returns:
                   14721: 
                   14722: An <img> tag which references graph.png and the appropriate identifying
                   14723: information for the plot.
                   14724: 
1.137     matthew  14725: =cut
                   14726: 
                   14727: ############################################################
                   14728: ############################################################
                   14729: sub DrawXYGraph {
                   14730:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   14731:     #
                   14732:     # Create the identifier for the graph
                   14733:     my $identifier = &get_cgi_id();
                   14734:     my $id = 'cgi.'.$identifier;
                   14735:     #
                   14736:     $Title  = '' if (! defined($Title));
                   14737:     $xlabel = '' if (! defined($xlabel));
                   14738:     $ylabel = '' if (! defined($ylabel));
                   14739:     my %ValuesHash = 
                   14740:         (
1.369     www      14741:          $id.'.title'  => &escape($Title),
                   14742:          $id.'.xlabel' => &escape($xlabel),
                   14743:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  14744:          $id.'.y_max_value'=> $Max,
                   14745:          $id.'.labels'     => join(',',@$Xlabels),
                   14746:          $id.'.PlotType'   => 'XY',
                   14747:          );
                   14748:     #
                   14749:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14750:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14751:     }
                   14752:     #
                   14753:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   14754:         return '';
                   14755:     }
                   14756:     my $NumSets=1;
1.138     matthew  14757:     foreach my $array (@{$Ydata}){
1.137     matthew  14758:         next if (! ref($array));
                   14759:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   14760:     }
1.138     matthew  14761:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  14762:     #
                   14763:     # Deal with other parameters
                   14764:     while (my ($key,$value) = each(%Values)) {
                   14765:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  14766:     }
                   14767:     #
1.646     raeburn  14768:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  14769:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   14770: }
                   14771: 
                   14772: ############################################################
                   14773: ############################################################
                   14774: 
                   14775: =pod
                   14776: 
1.648     raeburn  14777: =item * &DrawXYYGraph()
1.138     matthew  14778: 
                   14779: Facilitates the plotting of data in an XY graph with two Y axes.
                   14780: Puts plot definition data into the users environment in order for 
                   14781: graph.png to plot it.  Returns an <img> tag for the plot.
                   14782: 
                   14783: Inputs:
                   14784: 
                   14785: =over 4
                   14786: 
                   14787: =item $Title: string, the title of the plot
                   14788: 
                   14789: =item $xlabel: string, text describing the X-axis of the plot
                   14790: 
                   14791: =item $ylabel: string, text describing the Y-axis of the plot
                   14792: 
                   14793: =item $colors: Array ref containing the hex color codes for the data to be 
                   14794: plotted in.  If undefined, default values will be used.
                   14795: 
                   14796: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   14797: 
                   14798: =item $Ydata1: The first data set
                   14799: 
                   14800: =item $Min1: The minimum value of the left Y-axis
                   14801: 
                   14802: =item $Max1: The maximum value of the left Y-axis
                   14803: 
                   14804: =item $Ydata2: The second data set
                   14805: 
                   14806: =item $Min2: The minimum value of the right Y-axis
                   14807: 
                   14808: =item $Max2: The maximum value of the left Y-axis
                   14809: 
                   14810: =item %Values: hash indicating or overriding any default values which are 
                   14811: passed to graph.png.  
                   14812: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   14813: 
                   14814: =back
                   14815: 
                   14816: Returns:
                   14817: 
                   14818: An <img> tag which references graph.png and the appropriate identifying
                   14819: information for the plot.
1.136     matthew  14820: 
                   14821: =cut
                   14822: 
                   14823: ############################################################
                   14824: ############################################################
1.137     matthew  14825: sub DrawXYYGraph {
                   14826:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   14827:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  14828:     #
                   14829:     # Create the identifier for the graph
                   14830:     my $identifier = &get_cgi_id();
                   14831:     my $id = 'cgi.'.$identifier;
                   14832:     #
                   14833:     $Title  = '' if (! defined($Title));
                   14834:     $xlabel = '' if (! defined($xlabel));
                   14835:     $ylabel = '' if (! defined($ylabel));
                   14836:     my %ValuesHash = 
                   14837:         (
1.369     www      14838:          $id.'.title'  => &escape($Title),
                   14839:          $id.'.xlabel' => &escape($xlabel),
                   14840:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  14841:          $id.'.labels' => join(',',@$Xlabels),
                   14842:          $id.'.PlotType' => 'XY',
                   14843:          $id.'.NumSets' => 2,
1.137     matthew  14844:          $id.'.two_axes' => 1,
                   14845:          $id.'.y1_max_value' => $Max1,
                   14846:          $id.'.y1_min_value' => $Min1,
                   14847:          $id.'.y2_max_value' => $Max2,
                   14848:          $id.'.y2_min_value' => $Min2,
1.136     matthew  14849:          );
                   14850:     #
1.137     matthew  14851:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   14852:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   14853:     }
                   14854:     #
                   14855:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   14856:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  14857:         return '';
                   14858:     }
                   14859:     my $NumSets=1;
1.137     matthew  14860:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  14861:         next if (! ref($array));
                   14862:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  14863:     }
                   14864:     #
                   14865:     # Deal with other parameters
                   14866:     while (my ($key,$value) = each(%Values)) {
                   14867:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  14868:     }
                   14869:     #
1.646     raeburn  14870:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 14871:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  14872: }
                   14873: 
                   14874: ############################################################
                   14875: ############################################################
                   14876: 
                   14877: =pod
                   14878: 
1.157     matthew  14879: =back 
                   14880: 
1.139     matthew  14881: =head1 Statistics helper routines?  
                   14882: 
                   14883: Bad place for them but what the hell.
                   14884: 
1.157     matthew  14885: =over 4
                   14886: 
1.648     raeburn  14887: =item * &chartlink()
1.139     matthew  14888: 
                   14889: Returns a link to the chart for a specific student.  
                   14890: 
                   14891: Inputs:
                   14892: 
                   14893: =over 4
                   14894: 
                   14895: =item $linktext: The text of the link
                   14896: 
                   14897: =item $sname: The students username
                   14898: 
                   14899: =item $sdomain: The students domain
                   14900: 
                   14901: =back
                   14902: 
1.157     matthew  14903: =back
                   14904: 
1.139     matthew  14905: =cut
                   14906: 
                   14907: ############################################################
                   14908: ############################################################
                   14909: sub chartlink {
                   14910:     my ($linktext, $sname, $sdomain) = @_;
                   14911:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      14912:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 14913:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  14914:        '">'.$linktext.'</a>';
1.153     matthew  14915: }
                   14916: 
                   14917: #######################################################
                   14918: #######################################################
                   14919: 
                   14920: =pod
                   14921: 
                   14922: =head1 Course Environment Routines
1.157     matthew  14923: 
                   14924: =over 4
1.153     matthew  14925: 
1.648     raeburn  14926: =item * &restore_course_settings()
1.153     matthew  14927: 
1.648     raeburn  14928: =item * &store_course_settings()
1.153     matthew  14929: 
                   14930: Restores/Store indicated form parameters from the course environment.
                   14931: Will not overwrite existing values of the form parameters.
                   14932: 
                   14933: Inputs: 
                   14934: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   14935: 
                   14936: a hash ref describing the data to be stored.  For example:
                   14937:    
                   14938: %Save_Parameters = ('Status' => 'scalar',
                   14939:     'chartoutputmode' => 'scalar',
                   14940:     'chartoutputdata' => 'scalar',
                   14941:     'Section' => 'array',
1.373     raeburn  14942:     'Group' => 'array',
1.153     matthew  14943:     'StudentData' => 'array',
                   14944:     'Maps' => 'array');
                   14945: 
                   14946: Returns: both routines return nothing
                   14947: 
1.631     raeburn  14948: =back
                   14949: 
1.153     matthew  14950: =cut
                   14951: 
                   14952: #######################################################
                   14953: #######################################################
                   14954: sub store_course_settings {
1.496     albertel 14955:     return &store_settings($env{'request.course.id'},@_);
                   14956: }
                   14957: 
                   14958: sub store_settings {
1.153     matthew  14959:     # save to the environment
                   14960:     # appenv the same items, just to be safe
1.300     albertel 14961:     my $udom  = $env{'user.domain'};
                   14962:     my $uname = $env{'user.name'};
1.496     albertel 14963:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14964:     my %SaveHash;
                   14965:     my %AppHash;
                   14966:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14967:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14968:         my $envname = 'environment.'.$basename;
1.258     albertel 14969:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14970:             # Save this value away
                   14971:             if ($type eq 'scalar' &&
1.258     albertel 14972:                 (! exists($env{$envname}) || 
                   14973:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14974:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14975:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14976:             } elsif ($type eq 'array') {
                   14977:                 my $stored_form;
1.258     albertel 14978:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14979:                     $stored_form = join(',',
                   14980:                                         map {
1.369     www      14981:                                             &escape($_);
1.258     albertel 14982:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14983:                 } else {
                   14984:                     $stored_form = 
1.369     www      14985:                         &escape($env{'form.'.$setting});
1.153     matthew  14986:                 }
                   14987:                 # Determine if the array contents are the same.
1.258     albertel 14988:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14989:                     $SaveHash{$basename} = $stored_form;
                   14990:                     $AppHash{$envname}   = $stored_form;
                   14991:                 }
                   14992:             }
                   14993:         }
                   14994:     }
                   14995:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14996:                                           $udom,$uname);
1.153     matthew  14997:     if ($put_result !~ /^(ok|delayed)/) {
                   14998:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14999:                                  'got error:'.$put_result);
                   15000:     }
                   15001:     # Make sure these settings stick around in this session, too
1.646     raeburn  15002:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  15003:     return;
                   15004: }
                   15005: 
                   15006: sub restore_course_settings {
1.499     albertel 15007:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 15008: }
                   15009: 
                   15010: sub restore_settings {
                   15011:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15012:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 15013:         next if (exists($env{'form.'.$setting}));
1.496     albertel 15014:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  15015:             '.'.$setting;
1.258     albertel 15016:         if (exists($env{$envname})) {
1.153     matthew  15017:             if ($type eq 'scalar') {
1.258     albertel 15018:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  15019:             } elsif ($type eq 'array') {
1.258     albertel 15020:                 $env{'form.'.$setting} = [ 
1.153     matthew  15021:                                            map { 
1.369     www      15022:                                                &unescape($_); 
1.258     albertel 15023:                                            } split(',',$env{$envname})
1.153     matthew  15024:                                            ];
                   15025:             }
                   15026:         }
                   15027:     }
1.127     matthew  15028: }
                   15029: 
1.618     raeburn  15030: #######################################################
                   15031: #######################################################
                   15032: 
                   15033: =pod
                   15034: 
                   15035: =head1 Domain E-mail Routines  
                   15036: 
                   15037: =over 4
                   15038: 
1.648     raeburn  15039: =item * &build_recipient_list()
1.618     raeburn  15040: 
1.1075.2.44  raeburn  15041: Build recipient lists for following types of e-mail:
1.766     raeburn  15042: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  15043: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   15044: module change checking, student/employee ID conflict checks, as
                   15045: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   15046: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  15047: 
                   15048: Inputs:
1.1075.2.44  raeburn  15049: defmail (scalar - email address of default recipient),
                   15050: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   15051: requestsmail, updatesmail, or idconflictsmail).
                   15052: 
1.619     raeburn  15053: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  15054: 
                   15055: origmail (scalar - email address of recipient from loncapa.conf,
                   15056: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  15057: 
1.1075.2.139  raeburn  15058: $requname username of requester (if mailing type is helpdeskmail)
                   15059: 
                   15060: $requdom domain of requester (if mailing type is helpdeskmail)
                   15061: 
                   15062: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   15063: 
1.655     raeburn  15064: Returns: comma separated list of addresses to which to send e-mail.
                   15065: 
                   15066: =back
1.618     raeburn  15067: 
                   15068: =cut
                   15069: 
                   15070: ############################################################
                   15071: ############################################################
                   15072: sub build_recipient_list {
1.1075.2.139  raeburn  15073:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  15074:     my @recipients;
1.1075.2.122  raeburn  15075:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  15076:     my %domconfig =
1.1075.2.122  raeburn  15077:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  15078:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  15079:         if (exists($domconfig{'contacts'}{$mailing})) {
                   15080:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   15081:                 my @contacts = ('adminemail','supportemail');
                   15082:                 foreach my $item (@contacts) {
                   15083:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   15084:                         my $addr = $domconfig{'contacts'}{$item}; 
                   15085:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15086:                             push(@recipients,$addr);
                   15087:                         }
1.619     raeburn  15088:                     }
1.1075.2.122  raeburn  15089:                 }
                   15090:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   15091:                 if ($mailing eq 'helpdeskmail') {
                   15092:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   15093:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   15094:                         my @ok_bccs;
                   15095:                         foreach my $bcc (@bccs) {
                   15096:                             $bcc =~ s/^\s+//g;
                   15097:                             $bcc =~ s/\s+$//g;
                   15098:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15099:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15100:                                     push(@ok_bccs,$bcc);
                   15101:                                 }
                   15102:                             }
                   15103:                         }
                   15104:                         if (@ok_bccs > 0) {
                   15105:                             $allbcc = join(', ',@ok_bccs);
                   15106:                         }
                   15107:                     }
                   15108:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  15109:                 }
                   15110:             }
1.766     raeburn  15111:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15112:             $lastresort = $origmail;
1.618     raeburn  15113:         }
1.1075.2.139  raeburn  15114:         if ($mailing eq 'helpdeskmail') {
                   15115:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   15116:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   15117:                 my ($inststatus,$inststatus_checked);
                   15118:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   15119:                     ($env{'user.domain'} ne 'public')) {
                   15120:                     $inststatus_checked = 1;
                   15121:                     $inststatus = $env{'environment.inststatus'};
                   15122:                 }
                   15123:                 unless ($inststatus_checked) {
                   15124:                     if (($requname ne '') && ($requdom ne '')) {
                   15125:                         if (($requname =~ /^$match_username$/) &&
                   15126:                             ($requdom =~ /^$match_domain$/) &&
                   15127:                             (&Apache::lonnet::domain($requdom))) {
                   15128:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   15129:                                                                       $requdom);
                   15130:                             unless ($requhome eq 'no_host') {
                   15131:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   15132:                                 $inststatus = $userenv{'inststatus'};
                   15133:                                 $inststatus_checked = 1;
                   15134:                             }
                   15135:                         }
                   15136:                     }
                   15137:                 }
                   15138:                 unless ($inststatus_checked) {
                   15139:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   15140:                         my %srch = (srchby     => 'email',
                   15141:                                     srchdomain => $defdom,
                   15142:                                     srchterm   => $reqemail,
                   15143:                                     srchtype   => 'exact');
                   15144:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   15145:                         foreach my $uname (keys(%srch_results)) {
                   15146:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15147:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15148:                                 $inststatus_checked = 1;
                   15149:                                 last;
                   15150:                             }
                   15151:                         }
                   15152:                         unless ($inststatus_checked) {
                   15153:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   15154:                             if ($dirsrchres eq 'ok') {
                   15155:                                 foreach my $uname (keys(%srch_results)) {
                   15156:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   15157:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   15158:                                         $inststatus_checked = 1;
                   15159:                                         last;
                   15160:                                     }
                   15161:                                 }
                   15162:                             }
                   15163:                         }
                   15164:                     }
                   15165:                 }
                   15166:                 if ($inststatus ne '') {
                   15167:                     foreach my $status (split(/\:/,$inststatus)) {
                   15168:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   15169:                             my @contacts = ('adminemail','supportemail');
                   15170:                             foreach my $item (@contacts) {
                   15171:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   15172:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   15173:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15174:                                         push(@recipients,$addr);
                   15175:                                     }
                   15176:                                 }
                   15177:                             }
                   15178:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   15179:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   15180:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   15181:                                 my @ok_bccs;
                   15182:                                 foreach my $bcc (@bccs) {
                   15183:                                     $bcc =~ s/^\s+//g;
                   15184:                                     $bcc =~ s/\s+$//g;
                   15185:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15186:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15187:                                             push(@ok_bccs,$bcc);
                   15188:                                         }
                   15189:                                     }
                   15190:                                 }
                   15191:                                 if (@ok_bccs > 0) {
                   15192:                                     $allbcc = join(', ',@ok_bccs);
                   15193:                                 }
                   15194:                             }
                   15195:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   15196:                             last;
                   15197:                         }
                   15198:                     }
                   15199:                 }
                   15200:             }
                   15201:         }
1.619     raeburn  15202:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  15203:         $lastresort = $origmail;
                   15204:     }
1.1075.2.128  raeburn  15205:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  15206:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   15207:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   15208:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   15209:             my %what = (
                   15210:                           perlvar => 1,
                   15211:                        );
                   15212:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   15213:             if ($primary) {
                   15214:                 my $gotaddr;
                   15215:                 my ($result,$returnhash) =
                   15216:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   15217:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   15218:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   15219:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   15220:                         $gotaddr = 1;
                   15221:                     }
                   15222:                 }
                   15223:                 unless ($gotaddr) {
                   15224:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   15225:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   15226:                     unless ($uintdom eq $intdom) {
                   15227:                         my %domconfig =
                   15228:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   15229:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   15230:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   15231:                                 my @contacts = ('adminemail','supportemail');
                   15232:                                 foreach my $item (@contacts) {
                   15233:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   15234:                                         my $addr = $domconfig{'contacts'}{$item};
                   15235:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15236:                                             push(@recipients,$addr);
                   15237:                                         }
                   15238:                                     }
                   15239:                                 }
                   15240:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   15241:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   15242:                                 }
                   15243:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   15244:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   15245:                                     my @ok_bccs;
                   15246:                                     foreach my $bcc (@bccs) {
                   15247:                                         $bcc =~ s/^\s+//g;
                   15248:                                         $bcc =~ s/\s+$//g;
                   15249:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   15250:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   15251:                                                 push(@ok_bccs,$bcc);
                   15252:                                             }
                   15253:                                         }
                   15254:                                     }
                   15255:                                     if (@ok_bccs > 0) {
                   15256:                                         $allbcc = join(', ',@ok_bccs);
                   15257:                                     }
                   15258:                                 }
                   15259:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   15260:                             }
                   15261:                         }
                   15262:                     }
                   15263:                 }
                   15264:             }
                   15265:         }
1.618     raeburn  15266:     }
1.688     raeburn  15267:     if (defined($defmail)) {
                   15268:         if ($defmail ne '') {
                   15269:             push(@recipients,$defmail);
                   15270:         }
1.618     raeburn  15271:     }
                   15272:     if ($otheremails) {
1.619     raeburn  15273:         my @others;
                   15274:         if ($otheremails =~ /,/) {
                   15275:             @others = split(/,/,$otheremails);
1.618     raeburn  15276:         } else {
1.619     raeburn  15277:             push(@others,$otheremails);
                   15278:         }
                   15279:         foreach my $addr (@others) {
                   15280:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   15281:                 push(@recipients,$addr);
                   15282:             }
1.618     raeburn  15283:         }
                   15284:     }
1.1075.2.128  raeburn  15285:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  15286:         if ((!@recipients) && ($lastresort ne '')) {
                   15287:             push(@recipients,$lastresort);
                   15288:         }
                   15289:     } elsif ($lastresort ne '') {
                   15290:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   15291:             push(@recipients,$lastresort);
                   15292:         }
                   15293:     }
                   15294:     my $recipientlist = join(',',@recipients);
                   15295:     if (wantarray) {
                   15296:         return ($recipientlist,$allbcc,$addtext);
                   15297:     } else {
                   15298:         return $recipientlist;
                   15299:     }
1.618     raeburn  15300: }
                   15301: 
1.127     matthew  15302: ############################################################
                   15303: ############################################################
1.154     albertel 15304: 
1.655     raeburn  15305: =pod
                   15306: 
                   15307: =head1 Course Catalog Routines
                   15308: 
                   15309: =over 4
                   15310: 
                   15311: =item * &gather_categories()
                   15312: 
                   15313: Converts category definitions - keys of categories hash stored in  
                   15314: coursecategories in configuration.db on the primary library server in a 
                   15315: domain - to an array.  Also generates javascript and idx hash used to 
                   15316: generate Domain Coordinator interface for editing Course Categories.
                   15317: 
                   15318: Inputs:
1.663     raeburn  15319: 
1.655     raeburn  15320: categories (reference to hash of category definitions).
1.663     raeburn  15321: 
1.655     raeburn  15322: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15323:       categories and subcategories).
1.663     raeburn  15324: 
1.655     raeburn  15325: idx (reference to hash of counters used in Domain Coordinator interface for 
                   15326:       editing Course Categories).
1.663     raeburn  15327: 
1.655     raeburn  15328: jsarray (reference to array of categories used to create Javascript arrays for
                   15329:          Domain Coordinator interface for editing Course Categories).
                   15330: 
                   15331: Returns: nothing
                   15332: 
                   15333: Side effects: populates cats, idx and jsarray. 
                   15334: 
                   15335: =cut
                   15336: 
                   15337: sub gather_categories {
                   15338:     my ($categories,$cats,$idx,$jsarray) = @_;
                   15339:     my %counters;
                   15340:     my $num = 0;
                   15341:     foreach my $item (keys(%{$categories})) {
                   15342:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   15343:         if ($container eq '' && $depth == 0) {
                   15344:             $cats->[$depth][$categories->{$item}] = $cat;
                   15345:         } else {
                   15346:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   15347:         }
                   15348:         my ($escitem,$tail) = split(/:/,$item,2);
                   15349:         if ($counters{$tail} eq '') {
                   15350:             $counters{$tail} = $num;
                   15351:             $num ++;
                   15352:         }
                   15353:         if (ref($idx) eq 'HASH') {
                   15354:             $idx->{$item} = $counters{$tail};
                   15355:         }
                   15356:         if (ref($jsarray) eq 'ARRAY') {
                   15357:             push(@{$jsarray->[$counters{$tail}]},$item);
                   15358:         }
                   15359:     }
                   15360:     return;
                   15361: }
                   15362: 
                   15363: =pod
                   15364: 
                   15365: =item * &extract_categories()
                   15366: 
                   15367: Used to generate breadcrumb trails for course categories.
                   15368: 
                   15369: Inputs:
1.663     raeburn  15370: 
1.655     raeburn  15371: categories (reference to hash of category definitions).
1.663     raeburn  15372: 
1.655     raeburn  15373: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15374:       categories and subcategories).
1.663     raeburn  15375: 
1.655     raeburn  15376: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  15377: 
1.655     raeburn  15378: allitems (reference to hash - key is category key 
                   15379:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15380: 
1.655     raeburn  15381: idx (reference to hash of counters used in Domain Coordinator interface for
                   15382:       editing Course Categories).
1.663     raeburn  15383: 
1.655     raeburn  15384: jsarray (reference to array of categories used to create Javascript arrays for
                   15385:          Domain Coordinator interface for editing Course Categories).
                   15386: 
1.665     raeburn  15387: subcats (reference to hash of arrays containing all subcategories within each 
                   15388:          category, -recursive)
                   15389: 
1.1075.2.132  raeburn  15390: maxd (reference to hash used to hold max depth for all top-level categories).
                   15391: 
1.655     raeburn  15392: Returns: nothing
                   15393: 
                   15394: Side effects: populates trails and allitems hash references.
                   15395: 
                   15396: =cut
                   15397: 
                   15398: sub extract_categories {
1.1075.2.132  raeburn  15399:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  15400:     if (ref($categories) eq 'HASH') {
                   15401:         &gather_categories($categories,$cats,$idx,$jsarray);
                   15402:         if (ref($cats->[0]) eq 'ARRAY') {
                   15403:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   15404:                 my $name = $cats->[0][$i];
                   15405:                 my $item = &escape($name).'::0';
                   15406:                 my $trailstr;
                   15407:                 if ($name eq 'instcode') {
                   15408:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  15409:                 } elsif ($name eq 'communities') {
                   15410:                     $trailstr = &mt('Communities');
1.655     raeburn  15411:                 } else {
                   15412:                     $trailstr = $name;
                   15413:                 }
                   15414:                 if ($allitems->{$item} eq '') {
                   15415:                     push(@{$trails},$trailstr);
                   15416:                     $allitems->{$item} = scalar(@{$trails})-1;
                   15417:                 }
                   15418:                 my @parents = ($name);
                   15419:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   15420:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   15421:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  15422:                         if (ref($subcats) eq 'HASH') {
                   15423:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   15424:                         }
1.1075.2.132  raeburn  15425:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  15426:                     }
                   15427:                 } else {
                   15428:                     if (ref($subcats) eq 'HASH') {
                   15429:                         $subcats->{$item} = [];
1.655     raeburn  15430:                     }
1.1075.2.132  raeburn  15431:                     if (ref($maxd) eq 'HASH') {
                   15432:                         $maxd->{$name} = 1;
                   15433:                     }
1.655     raeburn  15434:                 }
                   15435:             }
                   15436:         }
                   15437:     }
                   15438:     return;
                   15439: }
                   15440: 
                   15441: =pod
                   15442: 
1.1075.2.56  raeburn  15443: =item * &recurse_categories()
1.655     raeburn  15444: 
                   15445: Recursively used to generate breadcrumb trails for course categories.
                   15446: 
                   15447: Inputs:
1.663     raeburn  15448: 
1.655     raeburn  15449: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   15450:       categories and subcategories).
1.663     raeburn  15451: 
1.655     raeburn  15452: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  15453: 
                   15454: category (current course category, for which breadcrumb trail is being generated).
                   15455: 
                   15456: trails (reference to array of breadcrumb trails for each category).
                   15457: 
1.655     raeburn  15458: allitems (reference to hash - key is category key
                   15459:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  15460: 
1.655     raeburn  15461: parents (array containing containers directories for current category, 
                   15462:          back to top level). 
                   15463: 
                   15464: Returns: nothing
                   15465: 
                   15466: Side effects: populates trails and allitems hash references
                   15467: 
                   15468: =cut
                   15469: 
                   15470: sub recurse_categories {
1.1075.2.132  raeburn  15471:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  15472:     my $shallower = $depth - 1;
                   15473:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   15474:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   15475:             my $name = $cats->[$depth]{$category}[$k];
                   15476:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.161.  .4(raebu 15477:22):             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15478:             if ($allitems->{$item} eq '') {
                   15479:                 push(@{$trails},$trailstr);
                   15480:                 $allitems->{$item} = scalar(@{$trails})-1;
                   15481:             }
                   15482:             my $deeper = $depth+1;
                   15483:             push(@{$parents},$category);
1.665     raeburn  15484:             if (ref($subcats) eq 'HASH') {
                   15485:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   15486:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   15487:                     my $higher;
                   15488:                     if ($j > 0) {
                   15489:                         $higher = &escape($parents->[$j]).':'.
                   15490:                                   &escape($parents->[$j-1]).':'.$j;
                   15491:                     } else {
                   15492:                         $higher = &escape($parents->[$j]).'::'.$j;
                   15493:                     }
                   15494:                     push(@{$subcats->{$higher}},$subcat);
                   15495:                 }
                   15496:             }
                   15497:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  15498:                                 $subcats,$maxd);
1.655     raeburn  15499:             pop(@{$parents});
                   15500:         }
                   15501:     } else {
                   15502:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  15503:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  15504:         if ($allitems->{$item} eq '') {
                   15505:             push(@{$trails},$trailstr);
                   15506:             $allitems->{$item} = scalar(@{$trails})-1;
                   15507:         }
1.1075.2.132  raeburn  15508:         if (ref($maxd) eq 'HASH') {
                   15509:             if ($depth > $maxd->{$parents->[0]}) {
                   15510:                 $maxd->{$parents->[0]} = $depth;
                   15511:             }
                   15512:         }
1.655     raeburn  15513:     }
                   15514:     return;
                   15515: }
                   15516: 
1.663     raeburn  15517: =pod
                   15518: 
1.1075.2.56  raeburn  15519: =item * &assign_categories_table()
1.663     raeburn  15520: 
                   15521: Create a datatable for display of hierarchical categories in a domain,
                   15522: with checkboxes to allow a course to be categorized. 
                   15523: 
                   15524: Inputs:
                   15525: 
                   15526: cathash - reference to hash of categories defined for the domain (from
                   15527:           configuration.db)
                   15528: 
                   15529: currcat - scalar with an & separated list of categories assigned to a course. 
                   15530: 
1.919     raeburn  15531: type    - scalar contains course type (Course or Community).
                   15532: 
1.1075.2.117  raeburn  15533: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15534:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15535: 
1.663     raeburn  15536: Returns: $output (markup to be displayed) 
                   15537: 
                   15538: =cut
                   15539: 
                   15540: sub assign_categories_table {
1.1075.2.117  raeburn  15541:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  15542:     my $output;
                   15543:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  15544:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   15545:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  15546:         $maxdepth = scalar(@cats);
                   15547:         if (@cats > 0) {
                   15548:             my $itemcount = 0;
                   15549:             if (ref($cats[0]) eq 'ARRAY') {
                   15550:                 my @currcategories;
                   15551:                 if ($currcat ne '') {
                   15552:                     @currcategories = split('&',$currcat);
                   15553:                 }
1.919     raeburn  15554:                 my $table;
1.663     raeburn  15555:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   15556:                     my $parent = $cats[0][$i];
1.919     raeburn  15557:                     next if ($parent eq 'instcode');
                   15558:                     if ($type eq 'Community') {
                   15559:                         next unless ($parent eq 'communities');
                   15560:                     } else {
                   15561:                         next if ($parent eq 'communities');
                   15562:                     }
1.663     raeburn  15563:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   15564:                     my $item = &escape($parent).'::0';
                   15565:                     my $checked = '';
                   15566:                     if (@currcategories > 0) {
                   15567:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   15568:                             $checked = ' checked="checked"';
1.663     raeburn  15569:                         }
                   15570:                     }
1.919     raeburn  15571:                     my $parent_title = $parent;
                   15572:                     if ($parent eq 'communities') {
                   15573:                         $parent_title = &mt('Communities');
                   15574:                     }
                   15575:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   15576:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15577:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  15578:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  15579:                     my $depth = 1;
                   15580:                     push(@path,$parent);
1.1075.2.117  raeburn  15581:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  15582:                     pop(@path);
1.919     raeburn  15583:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  15584:                     $itemcount ++;
                   15585:                 }
1.919     raeburn  15586:                 if ($itemcount) {
                   15587:                     $output = &Apache::loncommon::start_data_table().
                   15588:                               $table.
                   15589:                               &Apache::loncommon::end_data_table();
                   15590:                 }
1.663     raeburn  15591:             }
                   15592:         }
                   15593:     }
                   15594:     return $output;
                   15595: }
                   15596: 
                   15597: =pod
                   15598: 
1.1075.2.56  raeburn  15599: =item * &assign_category_rows()
1.663     raeburn  15600: 
                   15601: Create a datatable row for display of nested categories in a domain,
                   15602: with checkboxes to allow a course to be categorized,called recursively.
                   15603: 
                   15604: Inputs:
                   15605: 
                   15606: itemcount - track row number for alternating colors
                   15607: 
                   15608: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   15609:       categories and subcategories.
                   15610: 
                   15611: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   15612: 
                   15613: parent - parent of current category item
                   15614: 
                   15615: path - Array containing all categories back up through the hierarchy from the
                   15616:        current category to the top level.
                   15617: 
                   15618: currcategories - reference to array of current categories assigned to the course
                   15619: 
1.1075.2.117  raeburn  15620: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   15621:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   15622: 
1.663     raeburn  15623: Returns: $output (markup to be displayed).
                   15624: 
                   15625: =cut
                   15626: 
                   15627: sub assign_category_rows {
1.1075.2.117  raeburn  15628:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  15629:     my ($text,$name,$item,$chgstr);
                   15630:     if (ref($cats) eq 'ARRAY') {
                   15631:         my $maxdepth = scalar(@{$cats});
                   15632:         if (ref($cats->[$depth]) eq 'HASH') {
                   15633:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   15634:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   15635:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  15636:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  15637:                 for (my $j=0; $j<$numchildren; $j++) {
                   15638:                     $name = $cats->[$depth]{$parent}[$j];
                   15639:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   15640:                     my $deeper = $depth+1;
                   15641:                     my $checked = '';
                   15642:                     if (ref($currcategories) eq 'ARRAY') {
                   15643:                         if (@{$currcategories} > 0) {
                   15644:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   15645:                                 $checked = ' checked="checked"';
1.663     raeburn  15646:                             }
                   15647:                         }
                   15648:                     }
1.664     raeburn  15649:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   15650:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  15651:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  15652:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   15653:                              '</td><td>';
1.663     raeburn  15654:                     if (ref($path) eq 'ARRAY') {
                   15655:                         push(@{$path},$name);
1.1075.2.117  raeburn  15656:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  15657:                         pop(@{$path});
                   15658:                     }
                   15659:                     $text .= '</td></tr>';
                   15660:                 }
                   15661:                 $text .= '</table></td>';
                   15662:             }
                   15663:         }
                   15664:     }
                   15665:     return $text;
                   15666: }
                   15667: 
1.1075.2.69  raeburn  15668: =pod
                   15669: 
                   15670: =back
                   15671: 
                   15672: =cut
                   15673: 
1.655     raeburn  15674: ############################################################
                   15675: ############################################################
                   15676: 
                   15677: 
1.443     albertel 15678: sub commit_customrole {
1.664     raeburn  15679:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  15680:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 15681:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   15682:                          ($end?', ending '.localtime($end):'').': <b>'.
                   15683:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  15684:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 15685:                  '</b><br />';
                   15686:     return $output;
                   15687: }
                   15688: 
                   15689: sub commit_standardrole {
1.1075.2.31  raeburn  15690:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  15691:     my ($output,$logmsg,$linefeed);
                   15692:     if ($context eq 'auto') {
                   15693:         $linefeed = "\n";
                   15694:     } else {
                   15695:         $linefeed = "<br />\n";
                   15696:     }  
1.443     albertel 15697:     if ($three eq 'st') {
1.541     raeburn  15698:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  15699:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  15700:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  15701:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   15702:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 15703:         } else {
1.541     raeburn  15704:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 15705:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15706:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   15707:             if ($context eq 'auto') {
                   15708:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   15709:             } else {
                   15710:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   15711:                &mt('Add to classlist').': <b>ok</b>';
                   15712:             }
                   15713:             $output .= $linefeed;
1.443     albertel 15714:         }
                   15715:     } else {
                   15716:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   15717:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  15718:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  15719:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  15720:         if ($context eq 'auto') {
                   15721:             $output .= $result.$linefeed;
                   15722:         } else {
                   15723:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   15724:         }
1.443     albertel 15725:     }
                   15726:     return $output;
                   15727: }
                   15728: 
                   15729: sub commit_studentrole {
1.1075.2.31  raeburn  15730:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   15731:         $credits) = @_;
1.626     raeburn  15732:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  15733:     if ($context eq 'auto') {
                   15734:         $linefeed = "\n";
                   15735:     } else {
                   15736:         $linefeed = '<br />'."\n";
                   15737:     }
1.443     albertel 15738:     if (defined($one) && defined($two)) {
                   15739:         my $cid=$one.'_'.$two;
                   15740:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   15741:         my $secchange = 0;
                   15742:         my $expire_role_result;
                   15743:         my $modify_section_result;
1.628     raeburn  15744:         if ($oldsec ne '-1') { 
                   15745:             if ($oldsec ne $sec) {
1.443     albertel 15746:                 $secchange = 1;
1.628     raeburn  15747:                 my $now = time;
1.443     albertel 15748:                 my $uurl='/'.$cid;
                   15749:                 $uurl=~s/\_/\//g;
                   15750:                 if ($oldsec) {
                   15751:                     $uurl.='/'.$oldsec;
                   15752:                 }
1.626     raeburn  15753:                 $oldsecurl = $uurl;
1.628     raeburn  15754:                 $expire_role_result = 
1.1075.2.161.  .14(raeb 15755:-23):                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','','',$context);
1.628     raeburn  15756:                 if ($env{'request.course.sec'} ne '') { 
                   15757:                     if ($expire_role_result eq 'refused') {
                   15758:                         my @roles = ('st');
                   15759:                         my @statuses = ('previous');
                   15760:                         my @roledoms = ($one);
                   15761:                         my $withsec = 1;
                   15762:                         my %roleshash = 
                   15763:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   15764:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   15765:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   15766:                             my ($oldstart,$oldend) = 
                   15767:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   15768:                             if ($oldend > 0 && $oldend <= $now) {
                   15769:                                 $expire_role_result = 'ok';
                   15770:                             }
                   15771:                         }
                   15772:                     }
                   15773:                 }
1.443     albertel 15774:                 $result = $expire_role_result;
                   15775:             }
                   15776:         }
                   15777:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  15778:             $modify_section_result = 
                   15779:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   15780:                                                            undef,undef,undef,$sec,
                   15781:                                                            $end,$start,'','',$cid,
                   15782:                                                            '',$context,$credits);
1.443     albertel 15783:             if ($modify_section_result =~ /^ok/) {
                   15784:                 if ($secchange == 1) {
1.628     raeburn  15785:                     if ($sec eq '') {
                   15786:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   15787:                     } else {
                   15788:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   15789:                     }
1.443     albertel 15790:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  15791:                     if ($sec eq '') {
                   15792:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   15793:                     } else {
                   15794:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15795:                     }
1.443     albertel 15796:                 } else {
1.628     raeburn  15797:                     if ($sec eq '') {
                   15798:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   15799:                     } else {
                   15800:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   15801:                     }
1.443     albertel 15802:                 }
                   15803:             } else {
1.628     raeburn  15804:                 if ($secchange) {       
                   15805:                     $$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;
                   15806:                 } else {
                   15807:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   15808:                 }
1.443     albertel 15809:             }
                   15810:             $result = $modify_section_result;
                   15811:         } elsif ($secchange == 1) {
1.628     raeburn  15812:             if ($oldsec eq '') {
1.1075.2.20  raeburn  15813:                 $$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  15814:             } else {
                   15815:                 $$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;
                   15816:             }
1.626     raeburn  15817:             if ($expire_role_result eq 'refused') {
                   15818:                 my $newsecurl = '/'.$cid;
                   15819:                 $newsecurl =~ s/\_/\//g;
                   15820:                 if ($sec ne '') {
                   15821:                     $newsecurl.='/'.$sec;
                   15822:                 }
                   15823:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   15824:                     if ($sec eq '') {
                   15825:                         $$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;
                   15826:                     } else {
                   15827:                         $$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;
                   15828:                     }
                   15829:                 }
                   15830:             }
1.443     albertel 15831:         }
                   15832:     } else {
1.626     raeburn  15833:         $$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 15834:         $result = "error: incomplete course id\n";
                   15835:     }
                   15836:     return $result;
                   15837: }
                   15838: 
1.1075.2.25  raeburn  15839: sub show_role_extent {
                   15840:     my ($scope,$context,$role) = @_;
                   15841:     $scope =~ s{^/}{};
                   15842:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   15843:     push(@courseroles,'co');
                   15844:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   15845:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   15846:         $scope =~ s{/}{_};
                   15847:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   15848:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   15849:         my ($audom,$auname) = split(/\//,$scope);
                   15850:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   15851:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   15852:     } else {
                   15853:         $scope =~ s{/$}{};
                   15854:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   15855:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   15856:     }
                   15857: }
                   15858: 
1.443     albertel 15859: ############################################################
                   15860: ############################################################
                   15861: 
1.566     albertel 15862: sub check_clone {
1.578     raeburn  15863:     my ($args,$linefeed) = @_;
1.566     albertel 15864:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   15865:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   15866:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1075.2.161.  .1(raebu 15867:21):     my $clonetitle;
                   15868:21):     my @clonemsg;
1.566     albertel 15869:     my $can_clone = 0;
1.944     raeburn  15870:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  15871:     if ($lctype ne 'community') {
                   15872:         $lctype = 'course';
                   15873:     }
1.566     albertel 15874:     if ($clonehome eq 'no_host') {
1.944     raeburn  15875:         if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15876:21):             push(@clonemsg,({
                   15877:21):                               mt => 'No new community created.',
                   15878:21):                               args => [],
                   15879:21):                             },
                   15880:21):                             {
                   15881:21):                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   15882:21):                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   15883:21):                             }));
1.908     raeburn  15884:         } else {
1.1075.2.161.  .1(raebu 15885:21):             push(@clonemsg,({
                   15886:21):                               mt => 'No new course created.',
                   15887:21):                               args => [],
                   15888:21):                             },
                   15889:21):                             {
                   15890:21):                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   15891:21):                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15892:21):                             }));
                   15893:21):         }
1.566     albertel 15894:     } else {
                   15895: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1075.2.161.  .1(raebu 15896:21):         $clonetitle = $clonedesc{'description'};
1.944     raeburn  15897:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  15898:             if ($clonedesc{'type'} ne 'Community') {
1.1075.2.161.  .1(raebu 15899:21):                 push(@clonemsg,({
                   15900:21):                                   mt => 'No new community created.',
                   15901:21):                                   args => [],
                   15902:21):                                 },
                   15903:21):                                 {
                   15904:21):                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   15905:21):                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   15906:21):                                 }));
                   15907:21):                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  15908:             }
                   15909:         }
1.1075.2.119  raeburn  15910: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  15911:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 15912: 	    $can_clone = 1;
                   15913: 	} else {
1.1075.2.95  raeburn  15914: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 15915: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  15916:             if ($clonehash{'cloners'} eq '') {
                   15917:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   15918:                 if ($domdefs{'canclone'}) {
                   15919:                     unless ($domdefs{'canclone'} eq 'none') {
                   15920:                         if ($domdefs{'canclone'} eq 'domain') {
                   15921:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   15922:                                 $can_clone = 1;
                   15923:                             }
                   15924:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15925:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   15926:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   15927:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   15928:                                 $can_clone = 1;
                   15929:                             }
                   15930:                         }
                   15931:                     }
1.908     raeburn  15932:                 }
1.1075.2.95  raeburn  15933:             } else {
                   15934: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   15935:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  15936:                     $can_clone = 1;
1.1075.2.95  raeburn  15937:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  15938:                     $can_clone = 1;
1.1075.2.96  raeburn  15939:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   15940:                     $can_clone = 1;
1.1075.2.95  raeburn  15941:                 }
                   15942:                 unless ($can_clone) {
1.1075.2.96  raeburn  15943:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   15944:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  15945:                         my (%gotdomdefaults,%gotcodedefaults);
                   15946:                         foreach my $cloner (@cloners) {
                   15947:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   15948:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   15949:                                 my (%codedefaults,@code_order);
                   15950:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   15951:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   15952:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   15953:                                     }
                   15954:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   15955:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   15956:                                     }
                   15957:                                 } else {
                   15958:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   15959:                                                                             \%codedefaults,
                   15960:                                                                             \@code_order);
                   15961:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   15962:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   15963:                                 }
                   15964:                                 if (@code_order > 0) {
                   15965:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   15966:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   15967:                                                                                 $args->{'crscode'})) {
                   15968:                                         $can_clone = 1;
                   15969:                                         last;
                   15970:                                     }
                   15971:                                 }
                   15972:                             }
                   15973:                         }
                   15974:                     }
1.1075.2.96  raeburn  15975:                 }
                   15976:             }
                   15977:             unless ($can_clone) {
                   15978:                 my $ccrole = 'cc';
                   15979:                 if ($args->{'crstype'} eq 'Community') {
                   15980:                     $ccrole = 'co';
                   15981:                 }
                   15982:                 my %roleshash =
                   15983:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   15984:                                                   $args->{'ccdomain'},
                   15985:                                                   'userroles',['active'],[$ccrole],
                   15986:                                                   [$args->{'clonedomain'}]);
                   15987:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   15988:                     $can_clone = 1;
                   15989:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   15990:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   15991:                     $can_clone = 1;
1.1075.2.95  raeburn  15992:                 }
                   15993:             }
                   15994:             unless ($can_clone) {
                   15995:                 if ($args->{'crstype'} eq 'Community') {
1.1075.2.161.  .1(raebu 15996:21):                     push(@clonemsg,({
                   15997:21):                                       mt => 'No new community created.',
                   15998:21):                                       args => [],
                   15999:21):                                     },
                   16000:21):                                     {
                   16001:21):                                       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]).',
                   16002:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16003:21):                                     }));
1.1075.2.95  raeburn  16004:                 } else {
1.1075.2.161.  .1(raebu 16005:21):                     push(@clonemsg,({
                   16006:21):                                       mt => 'No new course created.',
                   16007:21):                                       args => [],
                   16008:21):                                     },
                   16009:21):                                     {
                   16010:21):                                       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]).',
                   16011:21):                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   16012:21):                                     }));
1.578     raeburn  16013: 	        }
1.566     albertel 16014: 	    }
1.578     raeburn  16015:         }
1.566     albertel 16016:     }
1.1075.2.161.  .1(raebu 16017:21):     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16018: }
                   16019: 
1.444     albertel 16020: sub construct_course {
1.1075.2.119  raeburn  16021:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1075.2.161.  .1(raebu 16022:21):         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   16023:21):     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  16024:     my $linefeed =  '<br />'."\n";
                   16025:     if ($context eq 'auto') {
                   16026:         $linefeed = "\n";
                   16027:     }
1.566     albertel 16028: 
                   16029: #
                   16030: # Are we cloning?
                   16031: #
1.1075.2.161.  .1(raebu 16032:21):     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 16033:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1075.2.161.  .1(raebu 16034:21): 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 16035:         if (!$can_clone) {
1.1075.2.161.  .1(raebu 16036:21): 	    return (0,$outcome,$clonemsgref);
1.566     albertel 16037: 	}
                   16038:     }
                   16039: 
1.444     albertel 16040: #
                   16041: # Open course
                   16042: #
                   16043:     my $crstype = lc($args->{'crstype'});
                   16044:     my %cenv=();
                   16045:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   16046:                                              $args->{'cdescr'},
                   16047:                                              $args->{'curl'},
                   16048:                                              $args->{'course_home'},
                   16049:                                              $args->{'nonstandard'},
                   16050:                                              $args->{'crscode'},
                   16051:                                              $args->{'ccuname'}.':'.
                   16052:                                              $args->{'ccdomain'},
1.882     raeburn  16053:                                              $args->{'crstype'},
1.1075.2.161.  .1(raebu 16054:21):                                              $cnum,$context,$category,
                   16055:21):                                              $callercontext);
1.444     albertel 16056: 
                   16057:     # Note: The testing routines depend on this being output; see 
                   16058:     # Utils::Course. This needs to at least be output as a comment
                   16059:     # if anyone ever decides to not show this, and Utils::Course::new
                   16060:     # will need to be suitably modified.
1.1075.2.161.  .1(raebu 16061:21):     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16062:21):         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16063:21):     } else {
                   16064:21):         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
                   16065:21):     }
1.943     raeburn  16066:     if ($$courseid =~ /^error:/) {
1.1075.2.161.  .1(raebu 16067:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16068:     }
                   16069: 
1.444     albertel 16070: #
                   16071: # Check if created correctly
                   16072: #
1.479     albertel 16073:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 16074:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  16075:     if ($crsuhome eq 'no_host') {
1.1075.2.161.  .1(raebu 16076:21):         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   16077:21):             $outcome .= &mt_user($user_lh,
                   16078:21):                             'Course creation failed, unrecognized course home server.');
                   16079:21):         } else {
                   16080:21):             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   16081:21):         }
                   16082:21):         $outcome .= $linefeed;
                   16083:21):         return (0,$outcome,$clonemsgref);
1.943     raeburn  16084:     }
1.541     raeburn  16085:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 16086: 
1.444     albertel 16087: #
1.566     albertel 16088: # Do the cloning
1.1075.2.161.  .1(raebu 16089:21): #
                   16090:21):     my @clonemsg;
1.566     albertel 16091:     if ($can_clone && $cloneid) {
1.1075.2.161.  .1(raebu 16092:21):         push(@clonemsg,
                   16093:21):                       {
                   16094:21):                           mt => 'Created [_1] by cloning from [_2]',
                   16095:21):                           args => [$crstype,$clonetitle],
                   16096:21):                       });
1.566     albertel 16097: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 16098: # Copy all files
1.1075.2.161.  .1(raebu 16099:21):         my @info =
                   16100:21):             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   16101:21):                                                      $args->{'dateshift'},$args->{'crscode'},
                   16102:21):                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   16103:21):                                                      $args->{'tinyurls'});
                   16104:21):         if (@info) {
                   16105:21):             push(@clonemsg,@info);
                   16106:21):         }
1.444     albertel 16107: # Restore URL
1.566     albertel 16108: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 16109: # Restore title
1.566     albertel 16110: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  16111: # Restore creation date, creator and creation context.
                   16112:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   16113:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   16114:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 16115: # Mark as cloned
1.566     albertel 16116: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      16117: # Need to clone grading mode
                   16118:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   16119:         $cenv{'grading'}=$newenv{'grading'};
                   16120: # Do not clone these environment entries
                   16121:         &Apache::lonnet::del('environment',
                   16122:                   ['default_enrollment_start_date',
                   16123:                    'default_enrollment_end_date',
                   16124:                    'question.email',
                   16125:                    'policy.email',
                   16126:                    'comment.email',
                   16127:                    'pch.users.denied',
1.725     raeburn  16128:                    'plc.users.denied',
                   16129:                    'hidefromcat',
1.1075.2.36  raeburn  16130:                    'checkforpriv',
1.1075.2.158  raeburn  16131:                    'categories'],
1.638     www      16132:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  16133:         if ($args->{'textbook'}) {
                   16134:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   16135:         }
1.444     albertel 16136:     }
1.566     albertel 16137: 
1.444     albertel 16138: #
                   16139: # Set environment (will override cloned, if existing)
                   16140: #
                   16141:     my @sections = ();
                   16142:     my @xlists = ();
                   16143:     if ($args->{'crstype'}) {
                   16144:         $cenv{'type'}=$args->{'crstype'};
                   16145:     }
                   16146:     if ($args->{'crsid'}) {
                   16147:         $cenv{'courseid'}=$args->{'crsid'};
                   16148:     }
                   16149:     if ($args->{'crscode'}) {
                   16150:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   16151:     }
                   16152:     if ($args->{'crsquota'} ne '') {
                   16153:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   16154:     } else {
                   16155:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   16156:     }
                   16157:     if ($args->{'ccuname'}) {
                   16158:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   16159:                                         ':'.$args->{'ccdomain'};
                   16160:     } else {
                   16161:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   16162:     }
1.1075.2.31  raeburn  16163:     if ($args->{'defaultcredits'}) {
                   16164:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   16165:     }
1.444     albertel 16166:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   16167:     if ($args->{'crssections'}) {
                   16168:         $cenv{'internal.sectionnums'} = '';
                   16169:         if ($args->{'crssections'} =~ m/,/) {
                   16170:             @sections = split/,/,$args->{'crssections'};
                   16171:         } else {
                   16172:             $sections[0] = $args->{'crssections'};
                   16173:         }
                   16174:         if (@sections > 0) {
                   16175:             foreach my $item (@sections) {
                   16176:                 my ($sec,$gp) = split/:/,$item;
                   16177:                 my $class = $args->{'crscode'}.$sec;
                   16178:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   16179:                 $cenv{'internal.sectionnums'} .= $item.',';
                   16180:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16181:                     push(@badclasses,$class);
1.444     albertel 16182:                 }
                   16183:             }
                   16184:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   16185:         }
                   16186:     }
                   16187: # do not hide course coordinator from staff listing, 
                   16188: # even if privileged
                   16189:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  16190: # add course coordinator's domain to domains to check for privileged users
                   16191: # if different to course domain
                   16192:     if ($$crsudom ne $args->{'ccdomain'}) {
                   16193:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   16194:     }
1.444     albertel 16195: # add crosslistings
                   16196:     if ($args->{'crsxlist'}) {
                   16197:         $cenv{'internal.crosslistings'}='';
                   16198:         if ($args->{'crsxlist'} =~ m/,/) {
                   16199:             @xlists = split/,/,$args->{'crsxlist'};
                   16200:         } else {
                   16201:             $xlists[0] = $args->{'crsxlist'};
                   16202:         }
                   16203:         if (@xlists > 0) {
                   16204:             foreach my $item (@xlists) {
                   16205:                 my ($xl,$gp) = split/:/,$item;
                   16206:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   16207:                 $cenv{'internal.crosslistings'} .= $item.',';
                   16208:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  16209:                     push(@badclasses,$xl);
1.444     albertel 16210:                 }
                   16211:             }
                   16212:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   16213:         }
                   16214:     }
                   16215:     if ($args->{'autoadds'}) {
                   16216:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   16217:     }
                   16218:     if ($args->{'autodrops'}) {
                   16219:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   16220:     }
                   16221: # check for notification of enrollment changes
                   16222:     my @notified = ();
                   16223:     if ($args->{'notify_owner'}) {
                   16224:         if ($args->{'ccuname'} ne '') {
                   16225:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   16226:         }
                   16227:     }
                   16228:     if ($args->{'notify_dc'}) {
                   16229:         if ($uname ne '') { 
1.630     raeburn  16230:             push(@notified,$uname.':'.$udom);
1.444     albertel 16231:         }
                   16232:     }
                   16233:     if (@notified > 0) {
                   16234:         my $notifylist;
                   16235:         if (@notified > 1) {
                   16236:             $notifylist = join(',',@notified);
                   16237:         } else {
                   16238:             $notifylist = $notified[0];
                   16239:         }
                   16240:         $cenv{'internal.notifylist'} = $notifylist;
                   16241:     }
                   16242:     if (@badclasses > 0) {
                   16243:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  16244:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   16245:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   16246:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 16247:         );
1.1075.2.119  raeburn  16248:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   16249:                            &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  16250:         if ($context eq 'auto') {
                   16251:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  16252:         } else {
1.566     albertel 16253:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  16254:         }
                   16255:         foreach my $item (@badclasses) {
1.541     raeburn  16256:             if ($context eq 'auto') {
1.1075.2.119  raeburn  16257:                 $outcome .= " - $item\n";
1.541     raeburn  16258:             } else {
1.1075.2.119  raeburn  16259:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  16260:             }
1.1075.2.119  raeburn  16261:         }
                   16262:         if ($context eq 'auto') {
                   16263:             $outcome .= $linefeed;
                   16264:         } else {
                   16265:             $outcome .= "</ul><br /><br /></div>\n";
                   16266:         }
1.444     albertel 16267:     }
                   16268:     if ($args->{'no_end_date'}) {
                   16269:         $args->{'endaccess'} = 0;
                   16270:     }
                   16271:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   16272:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   16273:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   16274:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   16275:     if ($args->{'showphotos'}) {
                   16276:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   16277:     }
                   16278:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   16279:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   16280:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   16281:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  16282:             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'); 
                   16283:             if ($context eq 'auto') {
                   16284:                 $outcome .= $krb_msg;
                   16285:             } else {
1.566     albertel 16286:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  16287:             }
                   16288:             $outcome .= $linefeed;
1.444     albertel 16289:         }
                   16290:     }
                   16291:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   16292:        if ($args->{'setpolicy'}) {
                   16293:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16294:        }
                   16295:        if ($args->{'setcontent'}) {
                   16296:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16297:        }
1.1075.2.110  raeburn  16298:        if ($args->{'setcomment'}) {
                   16299:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   16300:        }
1.444     albertel 16301:     }
                   16302:     if ($args->{'reshome'}) {
                   16303: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   16304: 	$cenv{'reshome'}=~s/\/+$/\//;
                   16305:     }
                   16306: #
                   16307: # course has keyed access
                   16308: #
                   16309:     if ($args->{'setkeys'}) {
                   16310:        $cenv{'keyaccess'}='yes';
                   16311:     }
                   16312: # if specified, key authority is not course, but user
                   16313: # only active if keyaccess is yes
                   16314:     if ($args->{'keyauth'}) {
1.487     albertel 16315: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   16316: 	$user = &LONCAPA::clean_username($user);
                   16317: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     16318: 	if ($user ne '' && $domain ne '') {
1.487     albertel 16319: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 16320: 	}
                   16321:     }
                   16322: 
1.1075.2.59  raeburn  16323: #
                   16324: #  generate and store uniquecode (available to course requester), if course should have one.
                   16325: #
                   16326:     if ($args->{'uniquecode'}) {
                   16327:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   16328:         if ($code) {
                   16329:             $cenv{'internal.uniquecode'} = $code;
                   16330:             my %crsinfo =
                   16331:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   16332:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   16333:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   16334:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   16335:             }
                   16336:             if (ref($coderef)) {
                   16337:                 $$coderef = $code;
                   16338:             }
                   16339:         }
                   16340:     }
                   16341: 
1.444     albertel 16342:     if ($args->{'disresdis'}) {
                   16343:         $cenv{'pch.roles.denied'}='st';
                   16344:     }
                   16345:     if ($args->{'disablechat'}) {
                   16346:         $cenv{'plc.roles.denied'}='st';
                   16347:     }
                   16348: 
                   16349:     # Record we've not yet viewed the Course Initialization Helper for this 
                   16350:     # course
                   16351:     $cenv{'course.helper.not.run'} = 1;
                   16352:     #
                   16353:     # Use new Randomseed
                   16354:     #
                   16355:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   16356:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   16357:     #
                   16358:     # The encryption code and receipt prefix for this course
                   16359:     #
                   16360:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   16361:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   16362:     #
                   16363:     # By default, use standard grading
                   16364:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   16365: 
1.541     raeburn  16366:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   16367:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16368: #
                   16369: # Open all assignments
                   16370: #
                   16371:     if ($args->{'openall'}) {
1.1075.2.146  raeburn  16372:        my $opendate = time;
                   16373:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   16374:            $opendate = $args->{'openallfrom'};
                   16375:        }
1.444     albertel 16376:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1075.2.146  raeburn  16377:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 16378:                            $storeunder.'.type' => 'date_start');
1.1075.2.146  raeburn  16379:        $outcome .= &mt('All assignments open starting [_1]',
                   16380:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   16381:                    &Apache::lonnet::cput
                   16382:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 16383:    }
                   16384: #
                   16385: # Set first page
                   16386: #
                   16387:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   16388: 	    || ($cloneid)) {
                   16389: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 16390: 
                   16391: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   16392:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   16393: 
1.444     albertel 16394:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   16395:         my $title; my $url;
                   16396:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   16397: 	    $title=&mt('Syllabus');
1.444     albertel 16398:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   16399:         } else {
1.963     raeburn  16400:             $title=&mt('Table of Contents');
1.444     albertel 16401:             $url='/adm/navmaps';
                   16402:         }
1.445     albertel 16403: 
                   16404:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   16405: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   16406: 
                   16407: 	if ($errtext) { $fatal=2; }
1.541     raeburn  16408:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 16409:     }
1.566     albertel 16410: 
1.1075.2.161.  .1(raebu 16411:21):     return (1,$outcome,\@clonemsg);
1.444     albertel 16412: }
                   16413: 
1.1075.2.59  raeburn  16414: sub make_unique_code {
                   16415:     my ($cdom,$cnum) = @_;
                   16416:     # get lock on uniquecodes db
                   16417:     my $lockhash = {
                   16418:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   16419:                                                   ':'.$env{'user.domain'},
                   16420:                    };
                   16421:     my $tries = 0;
                   16422:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16423:     my ($code,$error);
                   16424: 
                   16425:     while (($gotlock ne 'ok') && ($tries<3)) {
                   16426:         $tries ++;
                   16427:         sleep 1;
                   16428:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   16429:     }
                   16430:     if ($gotlock eq 'ok') {
                   16431:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   16432:         my $gotcode;
                   16433:         my $attempts = 0;
                   16434:         while ((!$gotcode) && ($attempts < 100)) {
                   16435:             $code = &generate_code();
                   16436:             if (!exists($currcodes{$code})) {
                   16437:                 $gotcode = 1;
                   16438:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   16439:                     $error = 'nostore';
                   16440:                 }
                   16441:             }
                   16442:             $attempts ++;
                   16443:         }
                   16444:         my @del_lock = ($cnum."\0".'uniquecodes');
                   16445:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   16446:     } else {
                   16447:         $error = 'nolock';
                   16448:     }
                   16449:     return ($code,$error);
                   16450: }
                   16451: 
                   16452: sub generate_code {
                   16453:     my $code;
                   16454:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   16455:     for (my $i=0; $i<6; $i++) {
                   16456:         my $lettnum = int (rand 2);
                   16457:         my $item = '';
                   16458:         if ($lettnum) {
                   16459:             $item = $letts[int( rand(18) )];
                   16460:         } else {
                   16461:             $item = 1+int( rand(8) );
                   16462:         }
                   16463:         $code .= $item;
                   16464:     }
                   16465:     return $code;
                   16466: }
                   16467: 
1.444     albertel 16468: ############################################################
                   16469: ############################################################
                   16470: 
1.953     droeschl 16471: #SD
                   16472: # only Community and Course, or anything else?
1.378     raeburn  16473: sub course_type {
                   16474:     my ($cid) = @_;
                   16475:     if (!defined($cid)) {
                   16476:         $cid = $env{'request.course.id'};
                   16477:     }
1.404     albertel 16478:     if (defined($env{'course.'.$cid.'.type'})) {
                   16479:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  16480:     } else {
                   16481:         return 'Course';
1.377     raeburn  16482:     }
                   16483: }
1.156     albertel 16484: 
1.406     raeburn  16485: sub group_term {
                   16486:     my $crstype = &course_type();
                   16487:     my %names = (
                   16488:                   'Course' => 'group',
1.865     raeburn  16489:                   'Community' => 'group',
1.406     raeburn  16490:                 );
                   16491:     return $names{$crstype};
                   16492: }
                   16493: 
1.902     raeburn  16494: sub course_types {
1.1075.2.59  raeburn  16495:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  16496:     my %typename = (
                   16497:                          official   => 'Official course',
                   16498:                          unofficial => 'Unofficial course',
                   16499:                          community  => 'Community',
1.1075.2.59  raeburn  16500:                          textbook   => 'Textbook course',
1.902     raeburn  16501:                    );
                   16502:     return (\@types,\%typename);
                   16503: }
                   16504: 
1.156     albertel 16505: sub icon {
                   16506:     my ($file)=@_;
1.505     albertel 16507:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 16508:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 16509:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 16510:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   16511: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   16512: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16513: 	            $curfext.".gif") {
                   16514: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   16515: 		$curfext.".gif";
                   16516: 	}
                   16517:     }
1.249     albertel 16518:     return &lonhttpdurl($iconname);
1.154     albertel 16519: } 
1.84      albertel 16520: 
1.575     albertel 16521: sub lonhttpdurl {
1.692     www      16522: #
                   16523: # Had been used for "small fry" static images on separate port 8080.
                   16524: # Modify here if lightweight http functionality desired again.
                   16525: # Currently eliminated due to increasing firewall issues.
                   16526: #
1.575     albertel 16527:     my ($url)=@_;
1.692     www      16528:     return $url;
1.215     albertel 16529: }
                   16530: 
1.213     albertel 16531: sub connection_aborted {
                   16532:     my ($r)=@_;
                   16533:     $r->print(" ");$r->rflush();
                   16534:     my $c = $r->connection;
                   16535:     return $c->aborted();
                   16536: }
                   16537: 
1.221     foxr     16538: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     16539: #    strings as 'strings'.
                   16540: sub escape_single {
1.221     foxr     16541:     my ($input) = @_;
1.223     albertel 16542:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     16543:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   16544:     return $input;
                   16545: }
1.223     albertel 16546: 
1.222     foxr     16547: #  Same as escape_single, but escape's "'s  This 
                   16548: #  can be used for  "strings"
                   16549: sub escape_double {
                   16550:     my ($input) = @_;
                   16551:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   16552:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   16553:     return $input;
                   16554: }
1.223     albertel 16555:  
1.222     foxr     16556: #   Escapes the last element of a full URL.
                   16557: sub escape_url {
                   16558:     my ($url)   = @_;
1.238     raeburn  16559:     my @urlslices = split(/\//, $url,-1);
1.369     www      16560:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  16561:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     16562: }
1.462     albertel 16563: 
1.820     raeburn  16564: sub compare_arrays {
                   16565:     my ($arrayref1,$arrayref2) = @_;
                   16566:     my (@difference,%count);
                   16567:     @difference = ();
                   16568:     %count = ();
                   16569:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   16570:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   16571:         foreach my $element (keys(%count)) {
                   16572:             if ($count{$element} == 1) {
                   16573:                 push(@difference,$element);
                   16574:             }
                   16575:         }
                   16576:     }
                   16577:     return @difference;
                   16578: }
                   16579: 
1.1075.2.152  raeburn  16580: sub lon_status_items {
                   16581:     my %defaults = (
                   16582:                      E         => 100,
                   16583:                      W         => 4,
                   16584:                      N         => 1,
                   16585:                      U         => 5,
                   16586:                      threshold => 200,
                   16587:                      sysmail   => 2500,
                   16588:                    );
                   16589:     my %names = (
                   16590:                    E => 'Errors',
                   16591:                    W => 'Warnings',
                   16592:                    N => 'Notices',
                   16593:                    U => 'Unsent',
                   16594:                 );
                   16595:     return (\%defaults,\%names);
                   16596: }
                   16597: 
1.817     bisitz   16598: # -------------------------------------------------------- Initialize user login
1.462     albertel 16599: sub init_user_environment {
1.463     albertel 16600:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 16601:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   16602: 
                   16603:     my $public=($username eq 'public' && $domain eq 'public');
                   16604: 
                   16605: # See if old ID present, if so, remove
                   16606: 
1.1062    raeburn  16607:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 16608:     my $now=time;
                   16609: 
                   16610:     if ($public) {
                   16611: 	my $max_public=100;
                   16612: 	my $oldest;
                   16613: 	my $oldest_time=0;
                   16614: 	for(my $next=1;$next<=$max_public;$next++) {
                   16615: 	    if (-e $lonids."/publicuser_$next.id") {
                   16616: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   16617: 		if ($mtime<$oldest_time || !$oldest_time) {
                   16618: 		    $oldest_time=$mtime;
                   16619: 		    $oldest=$next;
                   16620: 		}
                   16621: 	    } else {
                   16622: 		$cookie="publicuser_$next";
                   16623: 		last;
                   16624: 	    }
                   16625: 	}
                   16626: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   16627:     } else {
1.463     albertel 16628: 	# if this isn't a robot, kill any existing non-robot sessions
                   16629: 	if (!$args->{'robot'}) {
                   16630: 	    opendir(DIR,$lonids);
                   16631: 	    while ($filename=readdir(DIR)) {
                   16632: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1075.2.136  raeburn  16633:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   16634:                             &GDBM_READER(),0640)) {
                   16635:                         my $linkedfile;
                   16636:                         if (exists($oldenv{'user.linkedenv'})) {
                   16637:                             $linkedfile = $oldenv{'user.linkedenv'};
                   16638:                         }
                   16639:                         untie(%oldenv);
                   16640:                         if (unlink("$lonids/$filename")) {
                   16641:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   16642:                                 if (-l "$lonids/$linkedfile.id") {
                   16643:                                     unlink("$lonids/$linkedfile.id");
                   16644:                                 }
                   16645:                             }
                   16646:                         }
                   16647:                     } else {
                   16648:                         unlink($lonids.'/'.$filename);
                   16649:                     }
1.463     albertel 16650: 		}
1.462     albertel 16651: 	    }
1.463     albertel 16652: 	    closedir(DIR);
1.1075.2.84  raeburn  16653: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   16654:             my $namespace = 'nohist_courseeditor';
                   16655:             my $lockingkey = 'paste'."\0".'locked_num';
                   16656:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   16657:                                                 $domain,$username);
                   16658:             if (exists($lockhash{$lockingkey})) {
                   16659:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   16660:                 unless ($delresult eq 'ok') {
                   16661:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   16662:                 }
                   16663:             }
1.462     albertel 16664: 	}
                   16665: # Give them a new cookie
1.463     albertel 16666: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      16667: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 16668: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 16669:     
                   16670: # Initialize roles
                   16671: 
1.1062    raeburn  16672: 	($userroles,$firstaccenv,$timerintenv) = 
                   16673:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 16674:     }
                   16675: # ------------------------------------ Check browser type and MathML capability
                   16676: 
1.1075.2.77  raeburn  16677:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   16678:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 16679: 
                   16680: # ------------------------------------------------------------- Get environment
                   16681: 
                   16682:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   16683:     my ($tmp) = keys(%userenv);
                   16684:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   16685:     } else {
                   16686: 	undef(%userenv);
                   16687:     }
                   16688:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   16689: 	$form->{'interface'}=$userenv{'interface'};
                   16690:     }
                   16691:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   16692: 
                   16693: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   16694:     foreach my $option ('interface','localpath','localres') {
                   16695:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 16696:     }
                   16697: # --------------------------------------------------------- Write first profile
                   16698: 
                   16699:     {
1.1075.2.150  raeburn  16700:         my $ip = &Apache::lonnet::get_requestor_ip();
1.462     albertel 16701: 	my %initial_env = 
                   16702: 	    ("user.name"          => $username,
                   16703: 	     "user.domain"        => $domain,
                   16704: 	     "user.home"          => $authhost,
                   16705: 	     "browser.type"       => $clientbrowser,
                   16706: 	     "browser.version"    => $clientversion,
                   16707: 	     "browser.mathml"     => $clientmathml,
                   16708: 	     "browser.unicode"    => $clientunicode,
                   16709: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  16710:              "browser.mobile"     => $clientmobile,
                   16711:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  16712:              "browser.osversion"  => $clientosversion,
1.462     albertel 16713: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   16714: 	     "request.course.fn"  => '',
                   16715: 	     "request.course.uri" => '',
                   16716: 	     "request.course.sec" => '',
                   16717: 	     "request.role"       => 'cm',
                   16718: 	     "request.role.adv"   => $env{'user.adv'},
1.1075.2.150  raeburn  16719: 	     "request.host"       => $ip,);
1.462     albertel 16720: 
                   16721:         if ($form->{'localpath'}) {
                   16722: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   16723: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   16724:         }
                   16725: 	
                   16726: 	if ($form->{'interface'}) {
                   16727: 	    $form->{'interface'}=~s/\W//gs;
                   16728: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   16729: 	    $env{'browser.interface'}=$form->{'interface'};
                   16730: 	}
                   16731: 
1.1075.2.54  raeburn  16732:         if ($form->{'iptoken'}) {
                   16733:             my $lonhost = $r->dir_config('lonHostID');
                   16734:             $initial_env{"user.noloadbalance"} = $lonhost;
                   16735:             $env{'user.noloadbalance'} = $lonhost;
                   16736:         }
                   16737: 
1.1075.2.120  raeburn  16738:         if ($form->{'noloadbalance'}) {
                   16739:             my @hosts = &Apache::lonnet::current_machine_ids();
                   16740:             my $hosthere = $form->{'noloadbalance'};
                   16741:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   16742:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   16743:                 $env{'user.noloadbalance'} = $hosthere;
                   16744:             }
                   16745:         }
                   16746: 
1.1016    raeburn  16747:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  16748:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   16749:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  16750: 
1.1075.2.161.  .10(raeb 16751:-22):             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
1.1075.2.125  raeburn  16752:                 $userenv{'availabletools.'.$tool} = 
                   16753:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   16754:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   16755:             }
1.724     raeburn  16756: 
1.1075.2.125  raeburn  16757:             foreach my $crstype ('official','unofficial','community','textbook') {
                   16758:                 $userenv{'canrequest.'.$crstype} =
                   16759:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   16760:                                                       'reload','requestcourses',
                   16761:                                                       \%userenv,\%domdef,\%is_adv);
                   16762:             }
1.765     raeburn  16763: 
1.1075.2.125  raeburn  16764:             $userenv{'canrequest.author'} =
                   16765:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   16766:                                                   'reload','requestauthor',
                   16767:                                                   \%userenv,\%domdef,\%is_adv);
                   16768:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   16769:                                                  $domain,$username);
                   16770:             my $reqstatus = $reqauthor{'author_status'};
                   16771:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   16772:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   16773:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   16774:                                                       $reqauthor{'author'}{'timestamp'};
                   16775:                 }
1.1075.2.14  raeburn  16776:             }
                   16777:         }
                   16778: 
1.462     albertel 16779: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  16780: 
1.462     albertel 16781: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   16782: 		 &GDBM_WRCREAT(),0640)) {
                   16783: 	    &_add_to_env(\%disk_env,\%initial_env);
                   16784: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   16785: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  16786:             if (ref($firstaccenv) eq 'HASH') {
                   16787:                 &_add_to_env(\%disk_env,$firstaccenv);
                   16788:             }
                   16789:             if (ref($timerintenv) eq 'HASH') {
                   16790:                 &_add_to_env(\%disk_env,$timerintenv);
                   16791:             }
1.463     albertel 16792: 	    if (ref($args->{'extra_env'})) {
                   16793: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   16794: 	    }
1.462     albertel 16795: 	    untie(%disk_env);
                   16796: 	} else {
1.705     tempelho 16797: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   16798: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 16799: 	    return 'error: '.$!;
                   16800: 	}
                   16801:     }
                   16802:     $env{'request.role'}='cm';
                   16803:     $env{'request.role.adv'}=$env{'user.adv'};
                   16804:     $env{'browser.type'}=$clientbrowser;
                   16805: 
                   16806:     return $cookie;
                   16807: 
                   16808: }
                   16809: 
                   16810: sub _add_to_env {
                   16811:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  16812:     if (ref($env_data) eq 'HASH') {
                   16813:         while (my ($key,$value) = each(%$env_data)) {
                   16814: 	    $idf->{$prefix.$key} = $value;
                   16815: 	    $env{$prefix.$key}   = $value;
                   16816:         }
1.462     albertel 16817:     }
                   16818: }
                   16819: 
1.685     tempelho 16820: # --- Get the symbolic name of a problem and the url
                   16821: sub get_symb {
                   16822:     my ($request,$silent) = @_;
1.726     raeburn  16823:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 16824:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   16825:     if ($symb eq '') {
                   16826:         if (!$silent) {
1.1071    raeburn  16827:             if (ref($request)) { 
                   16828:                 $request->print("Unable to handle ambiguous references:$url:.");
                   16829:             }
1.685     tempelho 16830:             return ();
                   16831:         }
                   16832:     }
                   16833:     &Apache::lonenc::check_decrypt(\$symb);
                   16834:     return ($symb);
                   16835: }
                   16836: 
                   16837: # --------------------------------------------------------------Get annotation
                   16838: 
                   16839: sub get_annotation {
                   16840:     my ($symb,$enc) = @_;
                   16841: 
                   16842:     my $key = $symb;
                   16843:     if (!$enc) {
                   16844:         $key =
                   16845:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   16846:     }
                   16847:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   16848:     return $annotation{$key};
                   16849: }
                   16850: 
                   16851: sub clean_symb {
1.731     raeburn  16852:     my ($symb,$delete_enc) = @_;
1.685     tempelho 16853: 
                   16854:     &Apache::lonenc::check_decrypt(\$symb);
                   16855:     my $enc = $env{'request.enc'};
1.731     raeburn  16856:     if ($delete_enc) {
1.730     raeburn  16857:         delete($env{'request.enc'});
                   16858:     }
1.685     tempelho 16859: 
                   16860:     return ($symb,$enc);
                   16861: }
1.462     albertel 16862: 
1.1075.2.69  raeburn  16863: ############################################################
                   16864: ############################################################
                   16865: 
                   16866: =pod
                   16867: 
                   16868: =head1 Routines for building display used to search for courses
                   16869: 
                   16870: 
                   16871: =over 4
                   16872: 
                   16873: =item * &build_filters()
                   16874: 
                   16875: Create markup for a table used to set filters to use when selecting
                   16876: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   16877: and quotacheck.pl
                   16878: 
                   16879: 
                   16880: Inputs:
                   16881: 
                   16882: filterlist - anonymous array of fields to include as potential filters
                   16883: 
                   16884: crstype - course type
                   16885: 
                   16886: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   16887:               to pop-open a course selector (will contain "extra element").
                   16888: 
                   16889: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   16890: 
                   16891: filter - anonymous hash of criteria and their values
                   16892: 
                   16893: action - form action
                   16894: 
                   16895: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   16896: 
                   16897: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   16898: 
                   16899: cloneruname - username of owner of new course who wants to clone
                   16900: 
                   16901: clonerudom - domain of owner of new course who wants to clone
                   16902: 
                   16903: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   16904: 
                   16905: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   16906: 
                   16907: codedom - domain
                   16908: 
                   16909: formname - value of form element named "form".
                   16910: 
                   16911: fixeddom - domain, if fixed.
                   16912: 
                   16913: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   16914: 
                   16915: cnameelement - name of form element in form on opener page which will receive title of selected course
                   16916: 
                   16917: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   16918: 
                   16919: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   16920: 
                   16921: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   16922: 
                   16923: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   16924: 
                   16925: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   16926: 
                   16927: 
                   16928: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   16929: 
                   16930: 
                   16931: Side Effects: None
                   16932: 
                   16933: =cut
                   16934: 
                   16935: # ---------------------------------------------- search for courses based on last activity etc.
                   16936: 
                   16937: sub build_filters {
                   16938:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   16939:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   16940:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   16941:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   16942:         $clonetext,$clonewarning) = @_;
                   16943:     my ($list,$jscript);
                   16944:     my $onchange = 'javascript:updateFilters(this)';
                   16945:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   16946:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   16947:         $typeselectform,$instcodetitle);
                   16948:     if ($formname eq '') {
                   16949:         $formname = $caller;
                   16950:     }
                   16951:     foreach my $item (@{$filterlist}) {
                   16952:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   16953:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   16954:             if ($item eq 'domainfilter') {
                   16955:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   16956:             } elsif ($item eq 'coursefilter') {
                   16957:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   16958:             } elsif ($item eq 'ownerfilter') {
                   16959:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16960:             } elsif ($item eq 'ownerdomfilter') {
                   16961:                 $filter->{'ownerdomfilter'} =
                   16962:                     &LONCAPA::clean_domain($filter->{$item});
                   16963:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   16964:                                                        'ownerdomfilter',1);
                   16965:             } elsif ($item eq 'personfilter') {
                   16966:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   16967:             } elsif ($item eq 'persondomfilter') {
                   16968:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   16969:                                                         'persondomfilter',1);
                   16970:             } else {
                   16971:                 $filter->{$item} =~ s/\W//g;
                   16972:             }
                   16973:             if (!$filter->{$item}) {
                   16974:                 $filter->{$item} = '';
                   16975:             }
                   16976:         }
                   16977:         if ($item eq 'domainfilter') {
                   16978:             my $allow_blank = 1;
                   16979:             if ($formname eq 'portform') {
                   16980:                 $allow_blank=0;
                   16981:             } elsif ($formname eq 'studentform') {
                   16982:                 $allow_blank=0;
                   16983:             }
                   16984:             if ($fixeddom) {
                   16985:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   16986:                                     ' value="'.$codedom.'" />'.
                   16987:                                     &Apache::lonnet::domain($codedom,'description');
                   16988:             } else {
                   16989:                 $domainselectform = &select_dom_form($filter->{$item},
                   16990:                                                      'domainfilter',
                   16991:                                                       $allow_blank,'',$onchange);
                   16992:             }
                   16993:         } else {
                   16994:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   16995:         }
                   16996:     }
                   16997: 
                   16998:     # last course activity filter and selection
                   16999:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   17000: 
                   17001:     # course created filter and selection
                   17002:     if (exists($filter->{'createdfilter'})) {
                   17003:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   17004:     }
                   17005: 
                   17006:     my %lt = &Apache::lonlocal::texthash(
                   17007:                 'cac' => "$crstype Activity",
                   17008:                 'ccr' => "$crstype Created",
                   17009:                 'cde' => "$crstype Title",
                   17010:                 'cdo' => "$crstype Domain",
                   17011:                 'ins' => 'Institutional Code',
                   17012:                 'inc' => 'Institutional Categorization',
                   17013:                 'cow' => "$crstype Owner/Co-owner",
                   17014:                 'cop' => "$crstype Personnel Includes",
                   17015:                 'cog' => 'Type',
                   17016:              );
                   17017: 
                   17018:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17019:         my $typeval = 'Course';
                   17020:         if ($crstype eq 'Community') {
                   17021:             $typeval = 'Community';
                   17022:         }
                   17023:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   17024:     } else {
                   17025:         $typeselectform =  '<select name="type" size="1"';
                   17026:         if ($onchange) {
                   17027:             $typeselectform .= ' onchange="'.$onchange.'"';
                   17028:         }
                   17029:         $typeselectform .= '>'."\n";
                   17030:         foreach my $posstype ('Course','Community') {
                   17031:             $typeselectform.='<option value="'.$posstype.'"'.
                   17032:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   17033:         }
                   17034:         $typeselectform.="</select>";
                   17035:     }
                   17036: 
                   17037:     my ($cloneableonlyform,$cloneabletitle);
                   17038:     if (exists($filter->{'cloneableonly'})) {
                   17039:         my $cloneableon = '';
                   17040:         my $cloneableoff = ' checked="checked"';
                   17041:         if ($filter->{'cloneableonly'}) {
                   17042:             $cloneableon = $cloneableoff;
                   17043:             $cloneableoff = '';
                   17044:         }
                   17045:         $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>';
                   17046:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  17047:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  17048:         } else {
                   17049:             $cloneabletitle = &mt('Cloneable by you');
                   17050:         }
                   17051:     }
                   17052:     my $officialjs;
                   17053:     if ($crstype eq 'Course') {
                   17054:         if (exists($filter->{'instcodefilter'})) {
                   17055: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   17056: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   17057:             if ($codedom) {
                   17058:                 $officialjs = 1;
                   17059:                 ($instcodeform,$jscript,$$numtitlesref) =
                   17060:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   17061:                                                                   $officialjs,$codetitlesref);
                   17062:                 if ($jscript) {
                   17063:                     $jscript = '<script type="text/javascript">'."\n".
                   17064:                                '// <![CDATA['."\n".
                   17065:                                $jscript."\n".
                   17066:                                '// ]]>'."\n".
                   17067:                                '</script>'."\n";
                   17068:                 }
                   17069:             }
                   17070:             if ($instcodeform eq '') {
                   17071:                 $instcodeform =
                   17072:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   17073:                     $list->{'instcodefilter'}.'" />';
                   17074:                 $instcodetitle = $lt{'ins'};
                   17075:             } else {
                   17076:                 $instcodetitle = $lt{'inc'};
                   17077:             }
                   17078:             if ($fixeddom) {
                   17079:                 $instcodetitle .= '<br />('.$codedom.')';
                   17080:             }
                   17081:         }
                   17082:     }
                   17083:     my $output = qq|
                   17084: <form method="post" name="filterpicker" action="$action">
                   17085: <input type="hidden" name="form" value="$formname" />
                   17086: |;
                   17087:     if ($formname eq 'modifycourse') {
                   17088:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   17089:                    '<input type="hidden" name="prevphase" value="'.
                   17090:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  17091:     } elsif ($formname eq 'quotacheck') {
                   17092:         $output .= qq|
                   17093: <input type="hidden" name="sortby" value="" />
                   17094: <input type="hidden" name="sortorder" value="" />
                   17095: |;
                   17096:     } else {
1.1075.2.69  raeburn  17097:         my $name_input;
                   17098:         if ($cnameelement ne '') {
                   17099:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   17100:                           $cnameelement.'" />';
                   17101:         }
                   17102:         $output .= qq|
                   17103: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   17104: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   17105: $name_input
                   17106: $roleelement
                   17107: $multelement
                   17108: $typeelement
                   17109: |;
                   17110:         if ($formname eq 'portform') {
                   17111:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   17112:         }
                   17113:     }
                   17114:     if ($fixeddom) {
                   17115:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   17116:     }
                   17117:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   17118:     if ($sincefilterform) {
                   17119:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   17120:                   .$sincefilterform
                   17121:                   .&Apache::lonhtmlcommon::row_closure();
                   17122:     }
                   17123:     if ($createdfilterform) {
                   17124:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   17125:                   .$createdfilterform
                   17126:                   .&Apache::lonhtmlcommon::row_closure();
                   17127:     }
                   17128:     if ($domainselectform) {
                   17129:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   17130:                   .$domainselectform
                   17131:                   .&Apache::lonhtmlcommon::row_closure();
                   17132:     }
                   17133:     if ($typeselectform) {
                   17134:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   17135:             $output .= $typeselectform;
                   17136:         } else {
                   17137:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   17138:                       .$typeselectform
                   17139:                       .&Apache::lonhtmlcommon::row_closure();
                   17140:         }
                   17141:     }
                   17142:     if ($instcodeform) {
                   17143:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   17144:                   .$instcodeform
                   17145:                   .&Apache::lonhtmlcommon::row_closure();
                   17146:     }
                   17147:     if (exists($filter->{'ownerfilter'})) {
                   17148:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   17149:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17150:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   17151:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17152:                    $ownerdomselectform.'</td></tr></table>'.
                   17153:                    &Apache::lonhtmlcommon::row_closure();
                   17154:     }
                   17155:     if (exists($filter->{'personfilter'})) {
                   17156:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   17157:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   17158:                    '<input type="text" name="personfilter" size="20" value="'.
                   17159:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   17160:                    $persondomselectform.'</td></tr></table>'.
                   17161:                    &Apache::lonhtmlcommon::row_closure();
                   17162:     }
                   17163:     if (exists($filter->{'coursefilter'})) {
                   17164:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   17165:                   .'<input type="text" name="coursefilter" size="25" value="'
                   17166:                   .$list->{'coursefilter'}.'" />'
                   17167:                   .&Apache::lonhtmlcommon::row_closure();
                   17168:     }
                   17169:     if ($cloneableonlyform) {
                   17170:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   17171:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   17172:     }
                   17173:     if (exists($filter->{'descriptfilter'})) {
                   17174:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   17175:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   17176:                   .$list->{'descriptfilter'}.'" />'
                   17177:                   .&Apache::lonhtmlcommon::row_closure(1);
                   17178:     }
                   17179:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   17180:                '<input type="hidden" name="updater" value="" />'."\n".
                   17181:                '<input type="submit" name="gosearch" value="'.
                   17182:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   17183:     return $jscript.$clonewarning.$output;
                   17184: }
                   17185: 
                   17186: =pod
                   17187: 
                   17188: =item * &timebased_select_form()
                   17189: 
                   17190: Create markup for a dropdown list used to select a time-based
                   17191: filter e.g., Course Activity, Course Created, when searching for courses
                   17192: or communities
                   17193: 
                   17194: Inputs:
                   17195: 
                   17196: item - name of form element (sincefilter or createdfilter)
                   17197: 
                   17198: filter - anonymous hash of criteria and their values
                   17199: 
                   17200: Returns: HTML for a select box contained a blank, then six time selections,
                   17201:          with value set in incoming form variables currently selected.
                   17202: 
                   17203: Side Effects: None
                   17204: 
                   17205: =cut
                   17206: 
                   17207: sub timebased_select_form {
                   17208:     my ($item,$filter) = @_;
                   17209:     if (ref($filter) eq 'HASH') {
                   17210:         $filter->{$item} =~ s/[^\d-]//g;
                   17211:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   17212:         return &select_form(
                   17213:                             $filter->{$item},
                   17214:                             $item,
                   17215:                             {      '-1' => '',
                   17216:                                 '86400' => &mt('today'),
                   17217:                                '604800' => &mt('last week'),
                   17218:                               '2592000' => &mt('last month'),
                   17219:                               '7776000' => &mt('last three months'),
                   17220:                              '15552000' => &mt('last six months'),
                   17221:                              '31104000' => &mt('last year'),
                   17222:                     'select_form_order' =>
                   17223:                            ['-1','86400','604800','2592000','7776000',
                   17224:                             '15552000','31104000']});
                   17225:     }
                   17226: }
                   17227: 
                   17228: =pod
                   17229: 
                   17230: =item * &js_changer()
                   17231: 
                   17232: Create script tag containing Javascript used to submit course search form
                   17233: when course type or domain is changed, and also to hide 'Searching ...' on
                   17234: page load completion for page showing search result.
                   17235: 
                   17236: Inputs: None
                   17237: 
                   17238: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   17239: 
                   17240: Side Effects: None
                   17241: 
                   17242: =cut
                   17243: 
                   17244: sub js_changer {
                   17245:     return <<ENDJS;
                   17246: <script type="text/javascript">
                   17247: // <![CDATA[
                   17248: function updateFilters(caller) {
                   17249:     if (typeof(caller) != "undefined") {
                   17250:         document.filterpicker.updater.value = caller.name;
                   17251:     }
                   17252:     document.filterpicker.submit();
                   17253: }
                   17254: 
                   17255: function hideSearching() {
                   17256:     if (document.getElementById('searching')) {
                   17257:         document.getElementById('searching').style.display = 'none';
                   17258:     }
                   17259:     return;
                   17260: }
                   17261: 
                   17262: // ]]>
                   17263: </script>
                   17264: 
                   17265: ENDJS
                   17266: }
                   17267: 
                   17268: =pod
                   17269: 
                   17270: =item * &search_courses()
                   17271: 
                   17272: Process selected filters form course search form and pass to lonnet::courseiddump
                   17273: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   17274: 
                   17275: Inputs:
                   17276: 
                   17277: dom - domain being searched
                   17278: 
                   17279: type - course type ('Course' or 'Community' or '.' if any).
                   17280: 
                   17281: filter - anonymous hash of criteria and their values
                   17282: 
                   17283: numtitles - for institutional codes - number of categories
                   17284: 
                   17285: cloneruname - optional username of new course owner
                   17286: 
                   17287: clonerudom - optional domain of new course owner
                   17288: 
1.1075.2.95  raeburn  17289: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  17290:             (used when DC is using course creation form)
                   17291: 
                   17292: codetitles - reference to array of titles of components in institutional codes (official courses).
                   17293: 
1.1075.2.95  raeburn  17294: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   17295:            (and so can clone automatically)
                   17296: 
                   17297: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   17298: 
                   17299: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   17300:               courses to clone
1.1075.2.69  raeburn  17301: 
                   17302: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   17303: 
                   17304: 
                   17305: Side Effects: None
                   17306: 
                   17307: =cut
                   17308: 
                   17309: 
                   17310: sub search_courses {
1.1075.2.95  raeburn  17311:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   17312:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  17313:     my (%courses,%showcourses,$cloner);
                   17314:     if (($filter->{'ownerfilter'} ne '') ||
                   17315:         ($filter->{'ownerdomfilter'} ne '')) {
                   17316:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   17317:                                        $filter->{'ownerdomfilter'};
                   17318:     }
                   17319:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   17320:         if (!$filter->{$item}) {
                   17321:             $filter->{$item}='.';
                   17322:         }
                   17323:     }
                   17324:     my $now = time;
                   17325:     my $timefilter =
                   17326:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   17327:     my ($createdbefore,$createdafter);
                   17328:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   17329:         $createdbefore = $now;
                   17330:         $createdafter = $now-$filter->{'createdfilter'};
                   17331:     }
                   17332:     my ($instcodefilter,$regexpok);
                   17333:     if ($numtitles) {
                   17334:         if ($env{'form.official'} eq 'on') {
                   17335:             $instcodefilter =
                   17336:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17337:             $regexpok = 1;
                   17338:         } elsif ($env{'form.official'} eq 'off') {
                   17339:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   17340:             unless ($instcodefilter eq '') {
                   17341:                 $regexpok = -1;
                   17342:             }
                   17343:         }
                   17344:     } else {
                   17345:         $instcodefilter = $filter->{'instcodefilter'};
                   17346:     }
                   17347:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   17348:     if ($type eq '') { $type = '.'; }
                   17349: 
                   17350:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   17351:         $cloner = $cloneruname.':'.$clonerudom;
                   17352:     }
                   17353:     %courses = &Apache::lonnet::courseiddump($dom,
                   17354:                                              $filter->{'descriptfilter'},
                   17355:                                              $timefilter,
                   17356:                                              $instcodefilter,
                   17357:                                              $filter->{'combownerfilter'},
                   17358:                                              $filter->{'coursefilter'},
                   17359:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  17360:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  17361:                                              $filter->{'cloneableonly'},
                   17362:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  17363:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  17364:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   17365:         my $ccrole;
                   17366:         if ($type eq 'Community') {
                   17367:             $ccrole = 'co';
                   17368:         } else {
                   17369:             $ccrole = 'cc';
                   17370:         }
                   17371:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   17372:                                                      $filter->{'persondomfilter'},
                   17373:                                                      'userroles',undef,
                   17374:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   17375:                                                      $dom);
                   17376:         foreach my $role (keys(%rolehash)) {
                   17377:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   17378:             my $cid = $cdom.'_'.$cnum;
                   17379:             if (exists($courses{$cid})) {
                   17380:                 if (ref($courses{$cid}) eq 'HASH') {
                   17381:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   17382:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  17383:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  17384:                         }
                   17385:                     } else {
                   17386:                         $courses{$cid}{roles} = [$courserole];
                   17387:                     }
                   17388:                     $showcourses{$cid} = $courses{$cid};
                   17389:                 }
                   17390:             }
                   17391:         }
                   17392:         %courses = %showcourses;
                   17393:     }
                   17394:     return %courses;
                   17395: }
                   17396: 
                   17397: =pod
                   17398: 
                   17399: =back
                   17400: 
1.1075.2.88  raeburn  17401: =head1 Routines for version requirements for current course.
                   17402: 
                   17403: =over 4
                   17404: 
                   17405: =item * &check_release_required()
                   17406: 
                   17407: Compares required LON-CAPA version with version on server, and
                   17408: if required version is newer looks for a server with the required version.
                   17409: 
                   17410: Looks first at servers in user's owen domain; if none suitable, looks at
                   17411: servers in course's domain are permitted to host sessions for user's domain.
                   17412: 
                   17413: Inputs:
                   17414: 
                   17415: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17416: 
                   17417: $courseid - Course ID of current course
                   17418: 
                   17419: $rolecode - User's current role in course (for switchserver query string).
                   17420: 
                   17421: $required - LON-CAPA version needed by course (format: Major.Minor).
                   17422: 
                   17423: 
                   17424: Returns:
                   17425: 
                   17426: $switchserver - query string tp append to /adm/switchserver call (if
                   17427:                 current server's LON-CAPA version is too old.
                   17428: 
                   17429: $warning - Message is displayed if no suitable server could be found.
                   17430: 
                   17431: =cut
                   17432: 
                   17433: sub check_release_required {
                   17434:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   17435:     my ($switchserver,$warning);
                   17436:     if ($required ne '') {
                   17437:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   17438:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17439:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   17440:             my $otherserver;
                   17441:             if (($major eq '' && $minor eq '') ||
                   17442:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   17443:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   17444:                 my $switchlcrev =
                   17445:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   17446:                                                            $userdomserver);
                   17447:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   17448:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   17449:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   17450:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   17451:                     if ($cdom ne $env{'user.domain'}) {
                   17452:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   17453:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   17454:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   17455:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   17456:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   17457:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   17458:                         my $canhost =
                   17459:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   17460:                                                               $coursedomserver,
                   17461:                                                               $remoterev,
                   17462:                                                               $udomdefaults{'remotesessions'},
                   17463:                                                               $defdomdefaults{'hostedsessions'});
                   17464: 
                   17465:                         if ($canhost) {
                   17466:                             $otherserver = $coursedomserver;
                   17467:                         } else {
                   17468:                             $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.");
                   17469:                         }
                   17470:                     } else {
                   17471:                         $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).");
                   17472:                     }
                   17473:                 } else {
                   17474:                     $otherserver = $userdomserver;
                   17475:                 }
                   17476:             }
                   17477:             if ($otherserver ne '') {
                   17478:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   17479:             }
                   17480:         }
                   17481:     }
                   17482:     return ($switchserver,$warning);
                   17483: }
                   17484: 
                   17485: =pod
                   17486: 
                   17487: =item * &check_release_result()
                   17488: 
                   17489: Inputs:
                   17490: 
                   17491: $switchwarning - Warning message if no suitable server found to host session.
                   17492: 
                   17493: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17494:                 and current role.
                   17495: 
                   17496: Returns: HTML to display with information about requirement to switch server.
                   17497:          Either displaying warning with link to Roles/Courses screen or
                   17498:          display link to switchserver.
                   17499: 
1.1075.2.69  raeburn  17500: =cut
                   17501: 
1.1075.2.88  raeburn  17502: sub check_release_result {
                   17503:     my ($switchwarning,$switchserver) = @_;
                   17504:     my $output = &start_page('Selected course unavailable on this server').
                   17505:                  '<p class="LC_warning">';
                   17506:     if ($switchwarning) {
                   17507:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   17508:         if (&show_course()) {
                   17509:             $output .= &mt('Display courses');
                   17510:         } else {
                   17511:             $output .= &mt('Display roles');
                   17512:         }
                   17513:         $output .= '</a>';
                   17514:     } elsif ($switchserver) {
                   17515:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   17516:                    '<br />'.
                   17517:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   17518:                    &mt('Switch Server').
                   17519:                    '</a>';
                   17520:     }
                   17521:     $output .= '</p>'.&end_page();
                   17522:     return $output;
                   17523: }
                   17524: 
                   17525: =pod
                   17526: 
                   17527: =item * &needs_coursereinit()
                   17528: 
                   17529: Determine if course contents stored for user's session needs to be
                   17530: refreshed, because content has changed since "Big Hash" last tied.
                   17531: 
                   17532: Check for change is made if time last checked is more than 10 minutes ago
                   17533: (by default).
                   17534: 
                   17535: Inputs:
                   17536: 
                   17537: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   17538: 
                   17539: $interval (optional) - Time which may elapse (in s) between last check for content
                   17540:                        change in current course. (default: 600 s).
                   17541: 
                   17542: Returns: an array; first element is:
                   17543: 
                   17544: =over 4
                   17545: 
                   17546: 'switch' - if content updates mean user's session
                   17547:            needs to be switched to a server running a newer LON-CAPA version
                   17548: 
                   17549: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   17550:            on current server hosting user's session
                   17551: 
                   17552: ''       - if no action required.
                   17553: 
                   17554: =back
                   17555: 
                   17556: If first item element is 'switch':
                   17557: 
                   17558: second item is $switchwarning - Warning message if no suitable server found to host session.
                   17559: 
                   17560: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   17561:                               and current role.
                   17562: 
                   17563: otherwise: no other elements returned.
                   17564: 
                   17565: =back
                   17566: 
                   17567: =cut
                   17568: 
                   17569: sub needs_coursereinit {
                   17570:     my ($loncaparev,$interval) = @_;
                   17571:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   17572:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   17573:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   17574:     my $now = time;
                   17575:     if ($interval eq '') {
                   17576:         $interval = 600;
                   17577:     }
                   17578:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   17579:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1075.2.161.  .4(raebu 17580:22):         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
          .1(raebu 17581:21):         if ($blocked) {
                   17582:21):             return ();
                   17583:21):         }
          .13(raeb 17584:-23):         my $update;
                   17585:-23):         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17586:-23):         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   17587:-23):         if ($lastmainchange > $env{'request.course.tied'}) {
                   17588:-23):             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   17589:-23):             if ($needswitch) {
                   17590:-23):                 return ('switch',$switchwarning,$switchserver);
                   17591:-23):             }
                   17592:-23):             $update = 'main';
                   17593:-23):         }
                   17594:-23):         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   17595:-23):             if ($update) {
                   17596:-23):                 $update = 'both';
                   17597:-23):             } else {
                   17598:-23):                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   17599:-23):                 if ($needswitch) {
                   17600:-23):                     return ('switch',$switchwarning,$switchserver);
                   17601:-23):                 } else {
                   17602:-23):                     $update = 'supp';
1.1075.2.88  raeburn  17603:                 }
                   17604:             }
1.1075.2.161.  .13(raeb 17605:-23):             return ($update);
                   17606:-23):         }
                   17607:-23):     }
                   17608:-23):     return ();
                   17609:-23): }
                   17610:-23): 
                   17611:-23): sub switch_for_update {
                   17612:-23):     my ($loncaparev,$cdom,$cnum) = @_;
                   17613:-23):     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17614:-23):     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   17615:-23):         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   17616:-23):         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   17617:-23):             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   17618:-23):                                     $curr_reqd_hash{'internal.releaserequired'}});
                   17619:-23):             my ($switchserver,$switchwarning) =
                   17620:-23):                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   17621:-23):                                         $curr_reqd_hash{'internal.releaserequired'});
                   17622:-23):             if ($switchwarning ne '' || $switchserver ne '') {
                   17623:-23):                 return ('switch',$switchwarning,$switchserver);
                   17624:-23):             }
1.1075.2.88  raeburn  17625:         }
                   17626:     }
                   17627:     return ();
                   17628: }
1.1075.2.69  raeburn  17629: 
1.1075.2.11  raeburn  17630: sub update_content_constraints {
                   17631:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17632:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   17633:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   17634:     my %checkresponsetypes;
                   17635:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   17636:         my ($item,$name,$value) = split(/:/,$key);
                   17637:         if ($item eq 'resourcetag') {
                   17638:             if ($name eq 'responsetype') {
                   17639:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   17640:             }
                   17641:         }
                   17642:     }
                   17643:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17644:     if (defined($navmap)) {
                   17645:         my %allresponses;
                   17646:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   17647:             my %responses = $res->responseTypes();
                   17648:             foreach my $key (keys(%responses)) {
                   17649:                 next unless(exists($checkresponsetypes{$key}));
                   17650:                 $allresponses{$key} += $responses{$key};
                   17651:             }
                   17652:         }
                   17653:         foreach my $key (keys(%allresponses)) {
                   17654:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   17655:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   17656:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   17657:             }
                   17658:         }
                   17659:         undef($navmap);
                   17660:     }
                   17661:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   17662:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   17663:     }
                   17664:     return;
                   17665: }
                   17666: 
1.1075.2.27  raeburn  17667: sub allmaps_incourse {
                   17668:     my ($cdom,$cnum,$chome,$cid) = @_;
                   17669:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   17670:         $cid = $env{'request.course.id'};
                   17671:         $cdom = $env{'course.'.$cid.'.domain'};
                   17672:         $cnum = $env{'course.'.$cid.'.num'};
                   17673:         $chome = $env{'course.'.$cid.'.home'};
                   17674:     }
                   17675:     my %allmaps = ();
                   17676:     my $lastchange =
                   17677:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   17678:     if ($lastchange > $env{'request.course.tied'}) {
                   17679:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   17680:         unless ($ferr) {
                   17681:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   17682:         }
                   17683:     }
                   17684:     my $navmap = Apache::lonnavmaps::navmap->new();
                   17685:     if (defined($navmap)) {
                   17686:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   17687:             $allmaps{$res->src()} = 1;
                   17688:         }
                   17689:     }
                   17690:     return \%allmaps;
                   17691: }
                   17692: 
1.1075.2.11  raeburn  17693: sub parse_supplemental_title {
                   17694:     my ($title) = @_;
                   17695: 
                   17696:     my ($foldertitle,$renametitle);
                   17697:     if ($title =~ /&amp;&amp;&amp;/) {
                   17698:         $title = &HTML::Entites::decode($title);
                   17699:     }
                   17700:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   17701:         $renametitle=$4;
                   17702:         my ($time,$uname,$udom) = ($1,$2,$3);
                   17703:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   17704:         my $name =  &plainname($uname,$udom);
                   17705:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   17706:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   17707:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   17708:             $name.': <br />'.$foldertitle;
                   17709:     }
                   17710:     if (wantarray) {
                   17711:         return ($title,$foldertitle,$renametitle);
                   17712:     }
                   17713:     return $title;
                   17714: }
                   17715: 
1.1075.2.161.  .13(raeb 17716:-23): sub get_supplemental {
                   17717:-23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   17718:-23):     my $hashid=$cnum.':'.$cdom;
                   17719:-23):     my ($supplemental,$cached,$set_httprefs);
                   17720:-23):     unless ($ignorecache) {
                   17721:-23):         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   17722:-23):     }
                   17723:-23):     unless (defined($cached)) {
                   17724:-23):         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   17725:-23):         unless ($chome eq 'no_host') {
                   17726:-23):             my @order = @LONCAPA::map::order;
                   17727:-23):             my @resources = @LONCAPA::map::resources;
                   17728:-23):             my @resparms = @LONCAPA::map::resparms;
                   17729:-23):             my @zombies = @LONCAPA::map::zombies;
                   17730:-23):             my ($errors,%ids,%hidden);
                   17731:-23):             $errors =
                   17732:-23):                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   17733:-23):                                       $errors,$possdel,\%ids,\%hidden);
                   17734:-23):             @LONCAPA::map::order = @order;
                   17735:-23):             @LONCAPA::map::resources = @resources;
                   17736:-23):             @LONCAPA::map::resparms = @resparms;
                   17737:-23):             @LONCAPA::map::zombies = @zombies;
                   17738:-23):             $set_httprefs = 1;
                   17739:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   17740:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   17741:-23):             }
                   17742:-23):             $supplemental = {
                   17743:-23):                                ids => \%ids,
                   17744:-23):                                hidden => \%hidden,
                   17745:-23):                             };
                   17746:-23):             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   17747:-23):         }
                   17748:-23):     }
                   17749:-23):     return ($supplemental,$set_httprefs);
                   17750:-23): }
                   17751:-23): 
1.1075.2.43  raeburn  17752: sub recurse_supplemental {
1.1075.2.161.  .13(raeb 17753:-23):     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   17754:-23):     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   17755:-23):         my $mapnum;
                   17756:-23):         if ($suppmap eq 'supplemental.sequence') {
                   17757:-23):             $mapnum = 0;
                   17758:-23):         } else {
                   17759:-23):             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   17760:-23):         }
1.1075.2.43  raeburn  17761:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   17762:         if ($fatal) {
                   17763:             $errors ++;
                   17764:         } else {
1.1075.2.161.  .13(raeb 17765:-23):             my @order = @LONCAPA::map::order;
                   17766:-23):             if (@order > 0) {
                   17767:-23):                 my @resources = @LONCAPA::map::resources;
                   17768:-23):                 my @resparms = @LONCAPA::map::resparms;
                   17769:-23):                 foreach my $idx (@order) {
                   17770:-23):                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1075.2.43  raeburn  17771:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.161.  .13(raeb 17772:-23):                         my $id = $mapnum.':'.$idx;
                   17773:-23):                         push(@{$suppids->{$src}},$id);
                   17774:-23):                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   17775:-23):                             $hiddensupp->{$id} = 1;
                   17776:-23):                         }
1.1075.2.46  raeburn  17777:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1075.2.161.  .13(raeb 17778:-23):                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   17779:-23):                                                             $hiddensupp,$hiddensupp->{$id});
1.1075.2.43  raeburn  17780:                         } else {
1.1075.2.161.  .13(raeb 17781:-23):                             my $allowed;
                   17782:-23):                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   17783:-23):                                 $allowed = 1;
                   17784:-23):                             } elsif ($possdel) {
                   17785:-23):                                 foreach my $item (@{$suppids->{$src}}) {
                   17786:-23):                                     next if ($item eq $id);
                   17787:-23):                                     unless ($hiddensupp->{$item}) {
                   17788:-23):                                        $allowed = 1;
                   17789:-23):                                        last;
                   17790:-23):                                     }
                   17791:-23):                                 }
                   17792:-23):                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   17793:-23):                                     &Apache::lonnet::delenv('httpref.'.$src);
                   17794:-23):                                 }
                   17795:-23):                             }
                   17796:-23):                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   17797:-23):                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   17798:-23):                             }
                   17799:-23):                         }
                   17800:-23):                     }
                   17801:-23):                 }
                   17802:-23):             }
                   17803:-23):         }
                   17804:-23):     }
                   17805:-23):     return $errors;
                   17806:-23): }
                   17807:-23): 
                   17808:-23): sub set_supp_httprefs {
                   17809:-23):     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   17810:-23):     if (ref($supplemental) eq 'HASH') {
                   17811:-23):         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   17812:-23):             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   17813:-23):                 next if ($src =~ /\.sequence$/);
                   17814:-23):                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   17815:-23):                     my $allowed;
                   17816:-23):                     if ($env{'request.role.adv'}) {
                   17817:-23):                         $allowed = 1;
                   17818:-23):                     } else {
                   17819:-23):                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   17820:-23):                             unless ($supplemental->{'hidden'}->{$id}) {
                   17821:-23):                                 $allowed = 1;
                   17822:-23):                                 last;
                   17823:-23):                             }
                   17824:-23):                         }
                   17825:-23):                     }
                   17826:-23):                     if (exists($env{'httpref.'.$src})) {
                   17827:-23):                         if ($possdel) {
                   17828:-23):                             unless ($allowed) {
                   17829:-23):                                 &Apache::lonnet::delenv('httpref.'.$src);
                   17830:-23):                             }
1.1075.2.43  raeburn  17831:                         }
1.1075.2.161.  .13(raeb 17832:-23):                     } elsif ($allowed) {
                   17833:-23):                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1075.2.43  raeburn  17834:                     }
                   17835:                 }
                   17836:             }
1.1075.2.161.  .13(raeb 17837:-23):             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   17838:-23):                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   17839:-23):             }
1.1075.2.43  raeburn  17840:         }
                   17841:     }
1.1075.2.161.  .13(raeb 17842:-23): }
                   17843:-23): 
                   17844:-23): sub get_supp_parameter {
                   17845:-23):     my ($resparm,$name)=@_;
                   17846:-23):     return if ($resparm eq '');
                   17847:-23):     my $value=undef;
                   17848:-23):     my $ptype=undef;
                   17849:-23):     foreach (split('&&&',$resparm)) {
                   17850:-23):         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   17851:-23):         if ($thisname eq $name) {
                   17852:-23):             $value=$thisvalue;
                   17853:-23):             $ptype=$thistype;
                   17854:-23):         }
                   17855:-23):     }
                   17856:-23):     return $value;
1.1075.2.43  raeburn  17857: }
                   17858: 
1.1075.2.18  raeburn  17859: sub symb_to_docspath {
1.1075.2.119  raeburn  17860:     my ($symb,$navmapref) = @_;
                   17861:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  17862:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   17863:     if ($resurl=~/\.(sequence|page)$/) {
                   17864:         $mapurl=$resurl;
                   17865:     } elsif ($resurl eq 'adm/navmaps') {
                   17866:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   17867:     }
                   17868:     my $mapresobj;
1.1075.2.119  raeburn  17869:     unless (ref($$navmapref)) {
                   17870:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   17871:     }
                   17872:     if (ref($$navmapref)) {
                   17873:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  17874:     }
                   17875:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   17876:     my $type=$2;
                   17877:     my $path;
                   17878:     if (ref($mapresobj)) {
                   17879:         my $pcslist = $mapresobj->map_hierarchy();
                   17880:         if ($pcslist ne '') {
                   17881:             foreach my $pc (split(/,/,$pcslist)) {
                   17882:                 next if ($pc <= 1);
1.1075.2.119  raeburn  17883:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  17884:                 if (ref($res)) {
                   17885:                     my $thisurl = $res->src();
                   17886:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   17887:                     my $thistitle = $res->title();
                   17888:                     $path .= '&'.
                   17889:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  17890:                              &escape($thistitle).
1.1075.2.18  raeburn  17891:                              ':'.$res->randompick().
                   17892:                              ':'.$res->randomout().
                   17893:                              ':'.$res->encrypted().
                   17894:                              ':'.$res->randomorder().
                   17895:                              ':'.$res->is_page();
                   17896:                 }
                   17897:             }
                   17898:         }
                   17899:         $path =~ s/^\&//;
                   17900:         my $maptitle = $mapresobj->title();
                   17901:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17902:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17903:         }
                   17904:         $path .= (($path ne '')? '&' : '').
                   17905:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17906:                  &escape($maptitle).
1.1075.2.18  raeburn  17907:                  ':'.$mapresobj->randompick().
                   17908:                  ':'.$mapresobj->randomout().
                   17909:                  ':'.$mapresobj->encrypted().
                   17910:                  ':'.$mapresobj->randomorder().
                   17911:                  ':'.$mapresobj->is_page();
                   17912:     } else {
                   17913:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   17914:         my $ispage = (($type eq 'page')? 1 : '');
                   17915:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  17916:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  17917:         }
                   17918:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  17919:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  17920:     }
                   17921:     unless ($mapurl eq 'default') {
                   17922:         $path = 'default&'.
1.1075.2.46  raeburn  17923:                 &escape('Main Content').
1.1075.2.18  raeburn  17924:                 ':::::&'.$path;
                   17925:     }
                   17926:     return $path;
                   17927: }
                   17928: 
1.1075.2.161.  .13(raeb 17929:-23): sub validate_folderpath {
                   17930:-23):     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   17931:-23):     if ($env{'form.folderpath'} ne '') {
                   17932:-23):         my @items = split(/\&/,$env{'form.folderpath'});
                   17933:-23):         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
                   17934:-23):         for (my $i=0; $i<@items; $i++) {
                   17935:-23):             my $odd = $i%2;
                   17936:-23):             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   17937:-23):                 $badpath = 1;
                   17938:-23):             } elsif ($odd && $supplementalflag) {
                   17939:-23):                 my $idx = $i-1;
                   17940:-23):                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   17941:-23):                     my $esc_name = $1;
                   17942:-23):                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   17943:-23):                         $supppath .= '&'.$esc_name;
                   17944:-23):                         $changed = 1;
                   17945:-23):                     } else {
                   17946:-23):                         $supppath .= '&'.$items[$i];
                   17947:-23):                     }
                   17948:-23):                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   17949:-23):                     $changed = 1;
                   17950:-23):                     my $is_hidden;
                   17951:-23):                     unless ($got_supp) {
                   17952:-23):                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
                   17953:-23):                         if (ref($supplemental) eq 'HASH') {
                   17954:-23):                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   17955:-23):                                 %supphidden = %{$supplemental->{'hidden'}};
                   17956:-23):                             }
                   17957:-23):                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   17958:-23):                                 %suppids = %{$supplemental->{'ids'}};
                   17959:-23):                             }
                   17960:-23):                         }
                   17961:-23):                         $got_supp = 1;
                   17962:-23):                     }
                   17963:-23):                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   17964:-23):                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   17965:-23):                         if ($supphidden{$mapid}) {
                   17966:-23):                             $is_hidden = 1;
                   17967:-23):                         }
                   17968:-23):                     }
                   17969:-23):                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   17970:-23):                 } else {
                   17971:-23):                     $supppath .= '&'.$items[$i];
                   17972:-23):                 }
                   17973:-23):             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   17974:-23):                 $badpath = 1;
                   17975:-23):             } elsif ($supplementalflag) {
                   17976:-23):                 $supppath .= '&'.$items[$i];
                   17977:-23):             }
                   17978:-23):             last if ($badpath);
                   17979:-23):         }
                   17980:-23):         if ($badpath) {
                   17981:-23):             delete($env{'form.folderpath'});
                   17982:-23):         } elsif ($changed && $supplementalflag) {
                   17983:-23):             $supppath =~ s/^\&//;
                   17984:-23):             $env{'form.folderpath'} = $supppath;
                   17985:-23):         }
                   17986:-23):     }
                   17987:-23):     return;
                   17988:-23): }
                   17989:-23): 
1.1075.2.14  raeburn  17990: sub captcha_display {
1.1075.2.137  raeburn  17991:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  17992:     my ($output,$error);
1.1075.2.107  raeburn  17993:     my ($captcha,$pubkey,$privkey,$version) =
1.1075.2.137  raeburn  17994:         &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  17995:     if ($captcha eq 'original') {
                   17996:         $output = &create_captcha();
                   17997:         unless ($output) {
                   17998:             $error = 'captcha';
                   17999:         }
                   18000:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18001:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  18002:         unless ($output) {
                   18003:             $error = 'recaptcha';
                   18004:         }
                   18005:     }
1.1075.2.107  raeburn  18006:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  18007: }
                   18008: 
                   18009: sub captcha_response {
1.1075.2.137  raeburn  18010:     my ($context,$lonhost,$defdom) = @_;
1.1075.2.14  raeburn  18011:     my ($captcha_chk,$captcha_error);
1.1075.2.137  raeburn  18012:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1075.2.14  raeburn  18013:     if ($captcha eq 'original') {
                   18014:         ($captcha_chk,$captcha_error) = &check_captcha();
                   18015:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  18016:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  18017:     } else {
                   18018:         $captcha_chk = 1;
                   18019:     }
                   18020:     return ($captcha_chk,$captcha_error);
                   18021: }
                   18022: 
                   18023: sub get_captcha_config {
1.1075.2.137  raeburn  18024:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1075.2.107  raeburn  18025:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  18026:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   18027:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   18028:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18029:     if ($context eq 'usercreation') {
                   18030:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   18031:         if (ref($domconfig{$context}) eq 'HASH') {
                   18032:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   18033:             if (ref($hashtocheck) eq 'HASH') {
                   18034:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   18035:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   18036:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   18037:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   18038:                     }
                   18039:                     if ($privkey && $pubkey) {
                   18040:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  18041:                         $version = $hashtocheck->{'recaptchaversion'};
                   18042:                         if ($version ne '2') {
                   18043:                             $version = 1;
                   18044:                         }
1.1075.2.14  raeburn  18045:                     } else {
                   18046:                         $captcha = 'original';
                   18047:                     }
                   18048:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   18049:                     $captcha = 'original';
                   18050:                 }
                   18051:             }
                   18052:         } else {
                   18053:             $captcha = 'captcha';
                   18054:         }
                   18055:     } elsif ($context eq 'login') {
                   18056:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   18057:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   18058:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   18059:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   18060:             if ($privkey && $pubkey) {
                   18061:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  18062:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   18063:                 if ($version ne '2') {
                   18064:                     $version = 1;
                   18065:                 }
1.1075.2.14  raeburn  18066:             } else {
                   18067:                 $captcha = 'original';
                   18068:             }
                   18069:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   18070:             $captcha = 'original';
                   18071:         }
1.1075.2.137  raeburn  18072:     } elsif ($context eq 'passwords') {
                   18073:         if ($dom_in_effect) {
                   18074:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   18075:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   18076:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   18077:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   18078:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   18079:                 }
                   18080:                 if ($privkey && $pubkey) {
                   18081:                     $captcha = 'recaptcha';
                   18082:                     $version = $passwdconf{'recaptchaversion'};
                   18083:                     if ($version ne '2') {
                   18084:                         $version = 1;
                   18085:                     }
                   18086:                 } else {
                   18087:                     $captcha = 'original';
                   18088:                 }
                   18089:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   18090:                 $captcha = 'original';
                   18091:             }
                   18092:         }
1.1075.2.14  raeburn  18093:     }
1.1075.2.107  raeburn  18094:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  18095: }
                   18096: 
                   18097: sub create_captcha {
                   18098:     my %captcha_params = &captcha_settings();
                   18099:     my ($output,$maxtries,$tries) = ('',10,0);
                   18100:     while ($tries < $maxtries) {
                   18101:         $tries ++;
                   18102:         my $captcha = Authen::Captcha->new (
                   18103:                                            output_folder => $captcha_params{'output_dir'},
                   18104:                                            data_folder   => $captcha_params{'db_dir'},
                   18105:                                           );
                   18106:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   18107: 
                   18108:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   18109:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1075.2.158  raeburn  18110:                       '<span class="LC_nobreak">'.
1.1075.2.14  raeburn  18111:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  18112:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
1.1075.2.158  raeburn  18113:                       '</span><br />'.
1.1075.2.66  raeburn  18114:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  18115:             last;
                   18116:         }
                   18117:     }
1.1075.2.158  raeburn  18118:     if ($output eq '') {
                   18119:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   18120:     }
1.1075.2.14  raeburn  18121:     return $output;
                   18122: }
                   18123: 
                   18124: sub captcha_settings {
                   18125:     my %captcha_params = (
                   18126:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   18127:                            www_output_dir => "/captchaspool",
                   18128:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   18129:                            numchars       => '5',
                   18130:                          );
                   18131:     return %captcha_params;
                   18132: }
                   18133: 
                   18134: sub check_captcha {
                   18135:     my ($captcha_chk,$captcha_error);
                   18136:     my $code = $env{'form.code'};
                   18137:     my $md5sum = $env{'form.crypt'};
                   18138:     my %captcha_params = &captcha_settings();
                   18139:     my $captcha = Authen::Captcha->new(
                   18140:                       output_folder => $captcha_params{'output_dir'},
                   18141:                       data_folder   => $captcha_params{'db_dir'},
                   18142:                   );
1.1075.2.26  raeburn  18143:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  18144:     my %captcha_hash = (
                   18145:                         0       => 'Code not checked (file error)',
                   18146:                        -1      => 'Failed: code expired',
                   18147:                        -2      => 'Failed: invalid code (not in database)',
                   18148:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   18149:     );
                   18150:     if ($captcha_chk != 1) {
                   18151:         $captcha_error = $captcha_hash{$captcha_chk}
                   18152:     }
                   18153:     return ($captcha_chk,$captcha_error);
                   18154: }
                   18155: 
                   18156: sub create_recaptcha {
1.1075.2.107  raeburn  18157:     my ($pubkey,$version) = @_;
                   18158:     if ($version >= 2) {
1.1075.2.158  raeburn  18159:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   18160:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1075.2.107  raeburn  18161:     } else {
                   18162:         my $use_ssl;
                   18163:         if ($ENV{'SERVER_PORT'} == 443) {
                   18164:             $use_ssl = 1;
                   18165:         }
                   18166:         my $captcha = Captcha::reCAPTCHA->new;
                   18167:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   18168:                $captcha->get_html($pubkey,undef,$use_ssl).
                   18169:                &mt('If the text is hard to read, [_1] will replace them.',
                   18170:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   18171:                '<br /><br />';
                   18172:      }
1.1075.2.14  raeburn  18173: }
                   18174: 
                   18175: sub check_recaptcha {
1.1075.2.107  raeburn  18176:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  18177:     my $captcha_chk;
1.1075.2.150  raeburn  18178:     my $ip = &Apache::lonnet::get_requestor_ip(); 
1.1075.2.107  raeburn  18179:     if ($version >= 2) {
                   18180:         my $ua = LWP::UserAgent->new;
                   18181:         $ua->timeout(10);
                   18182:         my %info = (
                   18183:                      secret   => $privkey,
                   18184:                      response => $env{'form.g-recaptcha-response'},
1.1075.2.150  raeburn  18185:                      remoteip => $ip,
1.1075.2.107  raeburn  18186:                    );
                   18187:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   18188:         if ($response->is_success)  {
                   18189:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   18190:             if (ref($data) eq 'HASH') {
                   18191:                 if ($data->{'success'}) {
                   18192:                     $captcha_chk = 1;
                   18193:                 }
                   18194:             }
                   18195:         }
                   18196:     } else {
                   18197:         my $captcha = Captcha::reCAPTCHA->new;
                   18198:         my $captcha_result =
                   18199:             $captcha->check_answer(
                   18200:                                     $privkey,
1.1075.2.150  raeburn  18201:                                     $ip,
1.1075.2.107  raeburn  18202:                                     $env{'form.recaptcha_challenge_field'},
                   18203:                                     $env{'form.recaptcha_response_field'},
                   18204:                                   );
                   18205:         if ($captcha_result->{is_valid}) {
                   18206:             $captcha_chk = 1;
                   18207:         }
1.1075.2.14  raeburn  18208:     }
                   18209:     return $captcha_chk;
                   18210: }
                   18211: 
1.1075.2.64  raeburn  18212: sub emailusername_info {
1.1075.2.103  raeburn  18213:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  18214:     my %titles = &Apache::lonlocal::texthash (
                   18215:                      lastname      => 'Last Name',
                   18216:                      firstname     => 'First Name',
                   18217:                      institution   => 'School/college/university',
                   18218:                      location      => "School's city, state/province, country",
                   18219:                      web           => "School's web address",
                   18220:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  18221:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  18222:                  );
                   18223:     return (\@fields,\%titles);
                   18224: }
                   18225: 
1.1075.2.56  raeburn  18226: sub cleanup_html {
                   18227:     my ($incoming) = @_;
                   18228:     my $outgoing;
                   18229:     if ($incoming ne '') {
                   18230:         $outgoing = $incoming;
                   18231:         $outgoing =~ s/;/&#059;/g;
                   18232:         $outgoing =~ s/\#/&#035;/g;
                   18233:         $outgoing =~ s/\&/&#038;/g;
                   18234:         $outgoing =~ s/</&#060;/g;
                   18235:         $outgoing =~ s/>/&#062;/g;
                   18236:         $outgoing =~ s/\(/&#040/g;
                   18237:         $outgoing =~ s/\)/&#041;/g;
                   18238:         $outgoing =~ s/"/&#034;/g;
                   18239:         $outgoing =~ s/'/&#039;/g;
                   18240:         $outgoing =~ s/\$/&#036;/g;
                   18241:         $outgoing =~ s{/}{&#047;}g;
                   18242:         $outgoing =~ s/=/&#061;/g;
                   18243:         $outgoing =~ s/\\/&#092;/g
                   18244:     }
                   18245:     return $outgoing;
                   18246: }
                   18247: 
1.1075.2.74  raeburn  18248: # Checks for critical messages and returns a redirect url if one exists.
                   18249: # $interval indicates how often to check for messages.
1.1075.2.161.  .1(raebu 18250:21): # $context is the calling context -- roles, grades, contents, menu or flip.
1.1075.2.74  raeburn  18251: sub critical_redirect {
1.1075.2.161.  .1(raebu 18252:21):     my ($interval,$context) = @_;
1.1075.2.158  raeburn  18253:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   18254:         return ();
                   18255:     }
1.1075.2.74  raeburn  18256:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1075.2.161.  .1(raebu 18257:21):         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   18258:21):             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18259:21):             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
          .4(raebu 18260:22):             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
          .1(raebu 18261:21):             if ($blocked) {
                   18262:21):                 my $checkrole = "cm./$cdom/$cnum";
                   18263:21):                 if ($env{'request.course.sec'} ne '') {
                   18264:21):                     $checkrole .= "/$env{'request.course.sec'}";
                   18265:21):                 }
                   18266:21):                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   18267:21):                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   18268:21):                     return;
                   18269:21):                 }
                   18270:21):             }
                   18271:21):         }
1.1075.2.74  raeburn  18272:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   18273:                                         $env{'user.name'});
                   18274:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   18275:         my $redirecturl;
                   18276:         if ($what[0]) {
1.1075.2.158  raeburn  18277:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1075.2.74  raeburn  18278:                 $redirecturl='/adm/email?critical=display';
                   18279:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   18280:                 return (1, $url);
                   18281:             }
                   18282:         }
                   18283:     }
                   18284:     return ();
                   18285: }
                   18286: 
1.1075.2.64  raeburn  18287: # Use:
                   18288: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   18289: #
                   18290: ##################################################
                   18291: #          password associated functions         #
                   18292: ##################################################
                   18293: sub des_keys {
                   18294:     # Make a new key for DES encryption.
                   18295:     # Each key has two parts which are returned separately.
                   18296:     # Please note:  Each key must be passed through the &hex function
                   18297:     # before it is output to the web browser.  The hex versions cannot
                   18298:     # be used to decrypt.
                   18299:     my @hexstr=('0','1','2','3','4','5','6','7',
                   18300:                 '8','9','a','b','c','d','e','f');
                   18301:     my $lkey='';
                   18302:     for (0..7) {
                   18303:         $lkey.=$hexstr[rand(15)];
                   18304:     }
                   18305:     my $ukey='';
                   18306:     for (0..7) {
                   18307:         $ukey.=$hexstr[rand(15)];
                   18308:     }
                   18309:     return ($lkey,$ukey);
                   18310: }
                   18311: 
                   18312: sub des_decrypt {
                   18313:     my ($key,$cyphertext) = @_;
                   18314:     my $keybin=pack("H16",$key);
                   18315:     my $cypher;
                   18316:     if ($Crypt::DES::VERSION>=2.03) {
                   18317:         $cypher=new Crypt::DES $keybin;
                   18318:     } else {
                   18319:         $cypher=new DES $keybin;
                   18320:     }
1.1075.2.106  raeburn  18321:     my $plaintext='';
                   18322:     my $cypherlength = length($cyphertext);
                   18323:     my $numchunks = int($cypherlength/32);
                   18324:     for (my $j=0; $j<$numchunks; $j++) {
                   18325:         my $start = $j*32;
                   18326:         my $cypherblock = substr($cyphertext,$start,32);
                   18327:         my $chunk =
                   18328:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   18329:         $chunk .=
                   18330:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   18331:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   18332:         $plaintext .= $chunk;
                   18333:     }
1.1075.2.64  raeburn  18334:     return $plaintext;
                   18335: }
                   18336: 
1.1075.2.161.  .1(raebu 18337:21): sub get_requested_shorturls {
                   18338:21):     my ($cdom,$cnum,$navmap) = @_;
                   18339:21):     return unless (ref($navmap));
                   18340:21):     my ($numnew,$errors);
                   18341:21):     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   18342:21):     if (@toshorten) {
                   18343:21):         my (%maps,%resources,%titles);
                   18344:21):         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   18345:21):                                                                'shorturls',$cdom,$cnum);
                   18346:21):         if (keys(%resources)) {
                   18347:21):             my %tocreate;
                   18348:21):             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   18349:21):                 my $symb = $resources{$item};
                   18350:21):                 if ($symb) {
                   18351:21):                     $tocreate{$cnum.'&'.$symb} = 1;
                   18352:21):                 }
                   18353:21):             }
                   18354:21):             if (keys(%tocreate)) {
                   18355:21):                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   18356:21):                                                       \%tocreate);
                   18357:21):             }
                   18358:21):         }
                   18359:21):     }
                   18360:21):     return ($numnew,$errors);
                   18361:21): }
                   18362:21): 
                   18363:21): sub make_short_symbs {
                   18364:21):     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   18365:21):     my ($numnew,@errors);
                   18366:21):     if (ref($tocreateref) eq 'HASH') {
                   18367:21):         my %tocreate = %{$tocreateref};
                   18368:21):         if (keys(%tocreate)) {
                   18369:21):             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   18370:21):             my $su = Short::URL->new(no_vowels => 1);
                   18371:21):             my $init = '';
                   18372:21):             my (%newunique,%addcourse,%courseonly,%failed);
                   18373:21):             # get lock on tiny db
                   18374:21):             my $now = time;
                   18375:21):             if ($lockuser eq '') {
                   18376:21):                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   18377:21):             }
                   18378:21):             my $lockhash = {
                   18379:21):                                 "lock\0$now" => $lockuser,
                   18380:21):                             };
                   18381:21):             my $tries = 0;
                   18382:21):             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18383:21):             my ($code,$error);
                   18384:21):             while (($gotlock ne 'ok') && ($tries<3)) {
                   18385:21):                 $tries ++;
                   18386:21):                 sleep 1;
                   18387:21):                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   18388:21):             }
                   18389:21):             if ($gotlock eq 'ok') {
                   18390:21):                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   18391:21):                                        \%addcourse,\%courseonly,\%failed);
                   18392:21):                 if (keys(%failed)) {
                   18393:21):                     my $numfailed = scalar(keys(%failed));
                   18394:21):                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   18395:21):                 }
                   18396:21):                 if (keys(%newunique)) {
                   18397:21):                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   18398:21):                     if ($putres eq 'ok') {
                   18399:21):                         $numnew = scalar(keys(%newunique));
                   18400:21):                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   18401:21):                         unless ($newputres eq 'ok') {
                   18402:21):                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   18403:21):                         }
                   18404:21):                     } else {
                   18405:21):                         push(@errors,&mt('error: could not store unique six character URLs'));
                   18406:21):                     }
                   18407:21):                 }
                   18408:21):                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   18409:21):                 unless ($dellockres eq 'ok') {
                   18410:21):                     push(@errors,&mt('error: could not release lockfile'));
                   18411:21):                 }
                   18412:21):             } else {
                   18413:21):                 push(@errors,&mt('error: could not obtain lockfile'));
                   18414:21):             }
                   18415:21):             if (keys(%courseonly)) {
                   18416:21):                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   18417:21):                 if ($result ne 'ok') {
                   18418:21):                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   18419:21):                 }
                   18420:21):             }
                   18421:21):         }
                   18422:21):     }
                   18423:21):     return ($numnew,\@errors);
                   18424:21): }
                   18425:21): 
                   18426:21): sub shorten_symbs {
                   18427:21):     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   18428:21):     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   18429:21):                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   18430:21):                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   18431:21):     my (%possibles,%collisions);
                   18432:21):     foreach my $key (keys(%{$tocreate})) {
                   18433:21):         my $num = String::CRC32::crc32($key);
                   18434:21):         my $tiny = $su->encode($num,$init);
                   18435:21):         if ($tiny) {
                   18436:21):             $possibles{$tiny} = $key;
                   18437:21):         }
                   18438:21):     }
                   18439:21):     if (!$init) {
                   18440:21):         $init = 1;
                   18441:21):     } else {
                   18442:21):         $init ++;
                   18443:21):     }
                   18444:21):     if (keys(%possibles)) {
                   18445:21):         my @posstiny = keys(%possibles);
                   18446:21):         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   18447:21):         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   18448:21):         if (keys(%currtiny)) {
                   18449:21):             foreach my $key (keys(%currtiny)) {
                   18450:21):                 next if ($currtiny{$key} eq '');
                   18451:21):                 if ($currtiny{$key} eq $possibles{$key}) {
                   18452:21):                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   18453:21):                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18454:21):                         $courseonly->{$tsymb} = $key;
                   18455:21):                     }
                   18456:21):                 } else {
                   18457:21):                     $collisions{$possibles{$key}} = 1;
                   18458:21):                 }
                   18459:21):                 delete($possibles{$key});
                   18460:21):             }
                   18461:21):         }
                   18462:21):         foreach my $key (keys(%possibles)) {
                   18463:21):             $newunique->{$key} = $possibles{$key};
                   18464:21):             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   18465:21):             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   18466:21):                 $addcourse->{$tsymb} = $key;
                   18467:21):             }
                   18468:21):         }
                   18469:21):     }
                   18470:21):     if (keys(%collisions)) {
                   18471:21):         if ($init <5) {
                   18472:21):             if (!$init) {
                   18473:21):                 $init = 1;
                   18474:21):             } else {
                   18475:21):                 $init ++;
                   18476:21):             }
                   18477:21):             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   18478:21):                                    $newunique,$addcourse,$courseonly,$failed);
                   18479:21):         } else {
                   18480:21):             foreach my $key (keys(%collisions)) {
                   18481:21):                 $failed->{$key} = 1;
                   18482:21):                 $failed->{$key} = 1;
                   18483:21):             }
                   18484:21):         }
                   18485:21):     }
                   18486:21):     return $init;
                   18487:21): }
                   18488:21): 
1.1075.2.135  raeburn  18489: sub is_nonframeable {
                   18490:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   18491:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
                   18492:     return if (($remprotocol eq '') || ($remhost eq ''));
                   18493: 
                   18494:     $remprotocol = lc($remprotocol);
                   18495:     $remhost = lc($remhost);
                   18496:     my $remport = 80;
                   18497:     if ($remprotocol eq 'https') {
                   18498:         $remport = 443;
                   18499:     }
                   18500:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
                   18501:     if ($cached) {
                   18502:         unless ($nocache) {
                   18503:             if ($result) {
                   18504:                 return 1;
                   18505:             } else {
                   18506:                 return 0;
                   18507:             }
                   18508:         }
                   18509:     }
                   18510:     my $uselink;
                   18511:     my $request = new HTTP::Request('HEAD',$url);
1.1075.2.142  raeburn  18512:     my $ua = LWP::UserAgent->new;
                   18513:     $ua->timeout(5);
                   18514:     my $response=$ua->request($request);
1.1075.2.135  raeburn  18515:     if ($response->is_success()) {
                   18516:         my $secpolicy = lc($response->header('content-security-policy'));
                   18517:         my $xframeop = lc($response->header('x-frame-options'));
                   18518:         $secpolicy =~ s/^\s+|\s+$//g;
                   18519:         $xframeop =~ s/^\s+|\s+$//g;
                   18520:         if (($secpolicy ne '') || ($xframeop ne '')) {
                   18521:             my $remotehost = $remprotocol.'://'.$remhost;
                   18522:             my ($origin,$protocol,$port);
                   18523:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   18524:                 $port = $ENV{'SERVER_PORT'};
                   18525:             } else {
                   18526:                 $port = 80;
                   18527:             }
                   18528:             if ($absolute eq '') {
                   18529:                 $protocol = 'http:';
                   18530:                 if ($port == 443) {
                   18531:                     $protocol = 'https:';
                   18532:                 }
                   18533:                 $origin = $protocol.'//'.lc($hostname);
                   18534:             } else {
                   18535:                 $origin = lc($absolute);
                   18536:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   18537:             }
                   18538:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   18539:                 my $framepolicy = $1;
                   18540:                 $framepolicy =~ s/^\s+|\s+$//g;
                   18541:                 my @policies = split(/\s+/,$framepolicy);
                   18542:                 if (@policies) {
                   18543:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   18544:                         $uselink = 1;
                   18545:                     } else {
                   18546:                         $uselink = 1;
                   18547:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   18548:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   18549:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   18550:                             undef($uselink);
                   18551:                         }
                   18552:                         if ($uselink) {
                   18553:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   18554:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   18555:                                     undef($uselink);
                   18556:                                 }
                   18557:                             }
                   18558:                         }
                   18559:                         if ($uselink) {
                   18560:                             my @possok;
                   18561:                             if ($ip ne '') {
                   18562:                                 push(@possok,$ip);
                   18563:                             }
                   18564:                             my $hoststr = '';
                   18565:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   18566:                                 if ($hoststr eq '') {
                   18567:                                     $hoststr = $part;
                   18568:                                 } else {
                   18569:                                     $hoststr = "$part.$hoststr";
                   18570:                                 }
                   18571:                                 if ($hoststr eq $hostname) {
                   18572:                                     push(@possok,$hostname);
                   18573:                                 } else {
                   18574:                                     push(@possok,"*.$hoststr");
                   18575:                                 }
                   18576:                             }
                   18577:                             if (@possok) {
                   18578:                                 foreach my $poss (@possok) {
                   18579:                                     last if (!$uselink);
                   18580:                                     foreach my $policy (@policies) {
                   18581:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   18582:                                             undef($uselink);
                   18583:                                             last;
                   18584:                                         }
                   18585:                                     }
                   18586:                                 }
                   18587:                             }
                   18588:                         }
                   18589:                     }
                   18590:                 }
                   18591:             } elsif ($xframeop ne '') {
                   18592:                 $uselink = 1;
                   18593:                 my @policies = split(/\s*,\s*/,$xframeop);
                   18594:                 if (@policies) {
                   18595:                     unless (grep(/^deny$/,@policies)) {
                   18596:                         if ($origin ne '') {
                   18597:                             if (grep(/^sameorigin$/,@policies)) {
                   18598:                                 if ($remotehost eq $origin) {
                   18599:                                     undef($uselink);
                   18600:                                 }
                   18601:                             }
                   18602:                             if ($uselink) {
                   18603:                                 foreach my $policy (@policies) {
                   18604:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   18605:                                         my $allowfrom = $1;
                   18606:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   18607:                                             undef($uselink);
                   18608:                                             last;
                   18609:                                         }
                   18610:                                     }
                   18611:                                 }
                   18612:                             }
                   18613:                         }
                   18614:                     }
                   18615:                 }
                   18616:             }
                   18617:         }
                   18618:     }
                   18619:     if ($nocache) {
                   18620:         if ($cached) {
                   18621:             my $devalidate;
                   18622:             if ($uselink && !$result) {
                   18623:                 $devalidate = 1;
                   18624:             } elsif (!$uselink && $result) {
                   18625:                 $devalidate = 1;
                   18626:             }
                   18627:             if ($devalidate) {
                   18628:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   18629:             }
                   18630:         }
                   18631:     } else {
                   18632:         if ($uselink) {
                   18633:             $result = 1;
                   18634:         } else {
                   18635:             $result = 0;
                   18636:         }
                   18637:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   18638:     }
                   18639:     return $uselink;
                   18640: }
                   18641: 
1.1075.2.161.  .1(raebu 18642:21): sub page_menu {
                   18643:21):     my ($menucolls,$menunum) = @_;
                   18644:21):     my %menu;
                   18645:21):     foreach my $item (split(/;/,$menucolls)) {
                   18646:21):         my ($num,$value) = split(/\%/,$item);
                   18647:21):         if ($num eq $menunum) {
                   18648:21):             my @entries = split(/\&/,$value);
                   18649:21):             foreach my $entry (@entries) {
                   18650:21):                 my ($name,$fields) = split(/=/,$entry);
                   18651:21):                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
                   18652:21):                     $menu{$name} = $fields;
                   18653:21):                 } else {
                   18654:21):                     my @shown;
                   18655:21):                     if ($fields =~ /,/) {
                   18656:21):                         @shown = split(/,/,$fields);
                   18657:21):                     } else {
                   18658:21):                         @shown = ($fields);
                   18659:21):                     }
                   18660:21):                     if (@shown) {
                   18661:21):                         foreach my $field (@shown) {
                   18662:21):                             next if ($field eq '');
                   18663:21):                             $menu{$field} = 1;
                   18664:21):                         }
                   18665:21):                     }
                   18666:21):                 }
                   18667:21):             }
                   18668:21):         }
                   18669:21):     }
                   18670:21):     return %menu;
                   18671:21): }
                   18672:21): 
1.112     bowersj2 18673: 1;
                   18674: __END__;
1.41      ng       18675: 

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