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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1449  ! raeburn     4: # $Id: loncommon.pm,v 1.1448 2025/01/29 09:11:10 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.1383    raeburn    64: use Apache::lonnavmaps();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.1409    raeburn    74: use LONCAPA::ltiutils;
1.1280    raeburn    75: use LONCAPA::LWPReq;
1.1395    raeburn    76: use LONCAPA::map();
1.1328    raeburn    77: use HTTP::Request;
1.657     raeburn    78: use DateTime::TimeZone;
1.1241    raeburn    79: use DateTime::Locale;
1.1220    raeburn    80: use Encode();
1.1091    foxr       81: use Text::Aspell;
1.1094    raeburn    82: use Authen::Captcha;
                     83: use Captcha::reCAPTCHA;
1.1234    raeburn    84: use JSON::DWIW;
1.1174    raeburn    85: use Crypt::DES;
                     86: use DynaLoader; # for Crypt::DES version
1.1223    musolffc   87: use MIME::Lite;
                     88: use MIME::Types;
1.1292    raeburn    89: use File::Copy();
1.1300    raeburn    90: use File::Path();
1.1309    raeburn    91: use String::CRC32();
                     92: use Short::URL();
1.117     www        93: 
1.517     raeburn    94: # ---------------------------------------------- Designs
                     95: use vars qw(%defaultdesign);
                     96: 
1.22      www        97: my $readit;
                     98: 
1.517     raeburn    99: 
1.157     matthew   100: ##
                    101: ## Global Variables
                    102: ##
1.46      matthew   103: 
1.643     foxr      104: 
                    105: # ----------------------------------------------- SSI with retries:
                    106: #
                    107: 
                    108: =pod
                    109: 
1.648     raeburn   110: =head1 Server Side include with retries:
1.643     foxr      111: 
                    112: =over 4
                    113: 
1.648     raeburn   114: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      115: 
                    116: Performs an ssi with some number of retries.  Retries continue either
                    117: until the result is ok or until the retry count supplied by the
                    118: caller is exhausted.  
                    119: 
                    120: Inputs:
1.648     raeburn   121: 
                    122: =over 4
                    123: 
1.643     foxr      124: resource   - Identifies the resource to insert.
1.648     raeburn   125: 
1.643     foxr      126: retries    - Count of the number of retries allowed.
1.648     raeburn   127: 
1.643     foxr      128: form       - Hash that identifies the rendering options.
                    129: 
1.648     raeburn   130: =back
                    131: 
                    132: Returns:
                    133: 
                    134: =over 4
                    135: 
1.643     foxr      136: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   137: 
1.643     foxr      138: response   - The response from the last attempt (which may or may not have been successful.
                    139: 
1.648     raeburn   140: =back
                    141: 
                    142: =back
                    143: 
1.643     foxr      144: =cut
                    145: 
                    146: sub ssi_with_retries {
                    147:     my ($resource, $retries, %form) = @_;
                    148: 
                    149: 
                    150:     my $ok = 0;			# True if we got a good response.
                    151:     my $content;
                    152:     my $response;
                    153: 
                    154:     # Try to get the ssi done. within the retries count:
                    155: 
                    156:     do {
                    157: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    158: 	$ok      = $response->is_success;
1.650     www       159:         if (!$ok) {
                    160:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    161:         }
1.643     foxr      162: 	$retries--;
                    163:     } while (!$ok && ($retries > 0));
                    164: 
                    165:     if (!$ok) {
                    166: 	$content = '';		# On error return an empty content.
                    167:     }
                    168:     return ($content, $response);
                    169: 
                    170: }
                    171: 
                    172: 
                    173: 
1.20      www       174: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  175: my %language;
1.124     www       176: my %supported_language;
1.1088    foxr      177: my %supported_codes;
1.1048    foxr      178: my %latex_language;		# For choosing hyphenation in <transl..>
                    179: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  180: my %cprtag;
1.192     taceyjo1  181: my %scprtag;
1.351     www       182: my %fe; my %fd; my %fm;
1.41      ng        183: my %category_extensions;
1.12      harris41  184: 
1.46      matthew   185: # ---------------------------------------------- Thesaurus variables
1.144     matthew   186: #
                    187: # %Keywords:
                    188: #      A hash used by &keyword to determine if a word is considered a keyword.
                    189: # $thesaurus_db_file 
                    190: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   191: 
                    192: my %Keywords;
                    193: my $thesaurus_db_file;
                    194: 
1.144     matthew   195: #
                    196: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    197: # thesaurus.tab, and filecategories.tab.
                    198: #
1.18      www       199: BEGIN {
1.46      matthew   200:     # Variable initialization
                    201:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    202:     #
1.22      www       203:     unless ($readit) {
1.12      harris41  204: # ------------------------------------------------------------------- languages
                    205:     {
1.158     raeburn   206:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    207:                                    '/language.tab';
1.1317    raeburn   208:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  209:             while (my $line = <$fh>) {
                    210:                 next if ($line=~/^\#/);
                    211:                 chomp($line);
1.1088    foxr      212:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   213:                 $language{$key}=$val.' - '.$enc;
                    214:                 if ($sup) {
                    215:                     $supported_language{$key}=$sup;
1.1088    foxr      216: 		    $supported_codes{$key}   = $code;
1.158     raeburn   217:                 }
1.1048    foxr      218: 		if ($latex) {
                    219: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      220: 		    $latex_language{$code} = $latex;
1.1048    foxr      221: 		}
1.158     raeburn   222:             }
                    223:             close($fh);
                    224:         }
1.12      harris41  225:     }
                    226: # ------------------------------------------------------------------ copyrights
                    227:     {
1.158     raeburn   228:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    229:                                   '/copyright.tab';
1.1317    raeburn   230:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  231:             while (my $line = <$fh>) {
                    232:                 next if ($line=~/^\#/);
                    233:                 chomp($line);
                    234:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   235:                 $cprtag{$key}=$val;
                    236:             }
                    237:             close($fh);
                    238:         }
1.12      harris41  239:     }
1.351     www       240: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  241:     {
                    242:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    243:                                   '/source_copyright.tab';
1.1317    raeburn   244:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  245:             while (my $line = <$fh>) {
                    246:                 next if ($line =~ /^\#/);
                    247:                 chomp($line);
                    248:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  249:                 $scprtag{$key}=$val;
                    250:             }
                    251:             close($fh);
                    252:         }
                    253:     }
1.63      www       254: 
1.517     raeburn   255: # -------------------------------------------------------------- default domain designs
1.63      www       256:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   257:     my $designfile = $designdir.'/default.tab';
1.1317    raeburn   258:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   259:         while (my $line = <$fh>) {
                    260:             next if ($line =~ /^\#/);
                    261:             chomp($line);
                    262:             my ($key,$val)=(split(/\=/,$line));
                    263:             if ($val) { $defaultdesign{$key}=$val; }
                    264:         }
                    265:         close($fh);
1.63      www       266:     }
                    267: 
1.15      harris41  268: # ------------------------------------------------------------- file categories
                    269:     {
1.158     raeburn   270:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    271:                                   '/filecategories.tab';
1.1317    raeburn   272:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  273: 	    while (my $line = <$fh>) {
                    274: 		next if ($line =~ /^\#/);
                    275: 		chomp($line);
                    276:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1263    raeburn   277:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   278:             }
                    279:             close($fh);
                    280:         }
                    281: 
1.15      harris41  282:     }
1.12      harris41  283: # ------------------------------------------------------------------ file types
                    284:     {
1.158     raeburn   285:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    286:                '/filetypes.tab';
1.1317    raeburn   287:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  288:             while (my $line = <$fh>) {
                    289: 		next if ($line =~ /^\#/);
                    290: 		chomp($line);
                    291:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   292:                 if ($descr ne '') {
                    293:                     $fe{$ending}=lc($emb);
                    294:                     $fd{$ending}=$descr;
1.351     www       295:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   296:                 }
                    297:             }
                    298:             close($fh);
                    299:         }
1.12      harris41  300:     }
1.22      www       301:     &Apache::lonnet::logthis(
1.705     tempelho  302:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       303:     $readit=1;
1.46      matthew   304:     }  # end of unless($readit) 
1.32      matthew   305:     
                    306: }
1.112     bowersj2  307: 
1.42      matthew   308: ###############################################################
                    309: ##           HTML and Javascript Helper Functions            ##
                    310: ###############################################################
                    311: 
                    312: =pod 
                    313: 
1.112     bowersj2  314: =head1 HTML and Javascript Functions
1.42      matthew   315: 
1.112     bowersj2  316: =over 4
                    317: 
1.648     raeburn   318: =item * &browser_and_searcher_javascript()
1.112     bowersj2  319: 
                    320: X<browsing, javascript>X<searching, javascript>Returns a string
                    321: containing javascript with two functions, C<openbrowser> and
                    322: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    323: tags.
1.42      matthew   324: 
1.648     raeburn   325: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   326: 
                    327: inputs: formname, elementname, only, omit
                    328: 
                    329: formname and elementname indicate the name of the html form and name of
                    330: the element that the results of the browsing selection are to be placed in. 
                    331: 
                    332: Specifying 'only' will restrict the browser to displaying only files
1.185     www       333: with the given extension.  Can be a comma separated list.
1.42      matthew   334: 
                    335: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       336: with the given extension.  Can be a comma separated list.
1.42      matthew   337: 
1.648     raeburn   338: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   339: 
                    340: Inputs: formname, elementname
                    341: 
                    342: formname and elementname specify the name of the html form and the name
                    343: of the element the selection from the search results will be placed in.
1.542     raeburn   344: 
1.42      matthew   345: =cut
                    346: 
                    347: sub browser_and_searcher_javascript {
1.199     albertel  348:     my ($mode)=@_;
                    349:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  350:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   351:     return <<END;
1.219     albertel  352: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   353:     var editbrowser = null;
1.135     albertel  354:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       355:         var url = '$resurl/?';
1.42      matthew   356:         if (editbrowser == null) {
                    357:             url += 'launch=1&';
                    358:         }
                    359:         url += 'catalogmode=interactive&';
1.199     albertel  360:         url += 'mode=$mode&';
1.611     albertel  361:         url += 'inhibitmenu=yes&';
1.42      matthew   362:         url += 'form=' + formname + '&';
                    363:         if (only != null) {
                    364:             url += 'only=' + only + '&';
1.217     albertel  365:         } else {
                    366:             url += 'only=&';
                    367: 	}
1.42      matthew   368:         if (omit != null) {
                    369:             url += 'omit=' + omit + '&';
1.217     albertel  370:         } else {
                    371:             url += 'omit=&';
                    372: 	}
1.135     albertel  373:         if (titleelement != null) {
                    374:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  375:         } else {
                    376: 	    url += 'titleelement=&';
                    377: 	}
1.42      matthew   378:         url += 'element=' + elementname + '';
                    379:         var title = 'Browser';
1.435     albertel  380:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   381:         options += ',width=700,height=600';
                    382:         editbrowser = open(url,title,options,'1');
                    383:         editbrowser.focus();
                    384:     }
                    385:     var editsearcher;
1.135     albertel  386:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   387:         var url = '/adm/searchcat?';
                    388:         if (editsearcher == null) {
                    389:             url += 'launch=1&';
                    390:         }
                    391:         url += 'catalogmode=interactive&';
1.199     albertel  392:         url += 'mode=$mode&';
1.42      matthew   393:         url += 'form=' + formname + '&';
1.135     albertel  394:         if (titleelement != null) {
                    395:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  396:         } else {
                    397: 	    url += 'titleelement=&';
                    398: 	}
1.42      matthew   399:         url += 'element=' + elementname + '';
                    400:         var title = 'Search';
1.435     albertel  401:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   402:         options += ',width=700,height=600';
                    403:         editsearcher = open(url,title,options,'1');
                    404:         editsearcher.focus();
                    405:     }
1.219     albertel  406: // END LON-CAPA Internal -->
1.42      matthew   407: END
1.170     www       408: }
                    409: 
                    410: sub lastresurl {
1.258     albertel  411:     if ($env{'environment.lastresurl'}) {
                    412: 	return $env{'environment.lastresurl'}
1.170     www       413:     } else {
                    414: 	return '/res';
                    415:     }
                    416: }
                    417: 
                    418: sub storeresurl {
                    419:     my $resurl=&Apache::lonnet::clutter(shift);
                    420:     unless ($resurl=~/^\/res/) { return 0; }
                    421:     $resurl=~s/\/$//;
                    422:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   423:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       424:     return 1;
1.42      matthew   425: }
                    426: 
1.74      www       427: sub studentbrowser_javascript {
1.111     www       428:    unless (
1.258     albertel  429:             (($env{'request.course.id'}) && 
1.302     albertel  430:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    431: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    432: 					  '/'.$env{'request.course.sec'})
                    433: 	      ))
1.258     albertel  434:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       435:           ) { return ''; }  
1.74      www       436:    return (<<'ENDSTDBRW');
1.776     bisitz    437: <script type="text/javascript" language="Javascript">
1.824     bisitz    438: // <![CDATA[
1.74      www       439:     var stdeditbrowser;
1.1413    raeburn   440:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadv,uident) {
1.74      www       441:         var url = '/adm/pickstudent?';
                    442:         var filter;
1.558     albertel  443: 	if (!ignorefilter) {
                    444: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    445: 	}
1.74      www       446:         if (filter != null) {
                    447:            if (filter != '') {
                    448:                url += 'filter='+filter+'&';
                    449: 	   }
                    450:         }
                    451:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       452:                                     '&udomelement='+udom+
                    453:                                     '&clicker='+clicker;
1.111     www       454: 	if (roleflag) { url+="&roles=1"; }
1.1337    raeburn   455:         if (courseadv == 'condition') {
                    456:             if (document.getElementById('courseadv')) {
                    457:                 courseadv = document.getElementById('courseadv').value;
                    458:             }
                    459:         }
                    460:         if ((courseadv == 'only') || (courseadv == 'none')) { url+="&courseadv="+courseadv; }
1.1413    raeburn   461:         if (uident !== '') { url+="&identelement="+uident; } 
1.102     www       462:         var title = 'Student_Browser';
1.74      www       463:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    464:         options += ',width=700,height=600';
                    465:         stdeditbrowser = open(url,title,options,'1');
                    466:         stdeditbrowser.focus();
                    467:     }
1.824     bisitz    468: // ]]>
1.74      www       469: </script>
                    470: ENDSTDBRW
                    471: }
1.42      matthew   472: 
1.1003    www       473: sub resourcebrowser_javascript {
                    474:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       475:    return (<<'ENDRESBRW');
1.1003    www       476: <script type="text/javascript" language="Javascript">
                    477: // <![CDATA[
                    478:     var reseditbrowser;
1.1004    www       479:     function openresbrowser(formname,reslink) {
1.1005    www       480:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       481:         var title = 'Resource_Browser';
                    482:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       483:         options += ',width=700,height=500';
1.1004    www       484:         reseditbrowser = open(url,title,options,'1');
                    485:         reseditbrowser.focus();
1.1003    www       486:     }
                    487: // ]]>
                    488: </script>
1.1004    www       489: ENDRESBRW
1.1003    www       490: }
                    491: 
1.74      www       492: sub selectstudent_link {
1.1413    raeburn   493:    my ($form,$unameele,$udomele,$courseadv,$clickerid,$identelem)=@_;
1.999     www       494:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    495:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    496:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  497:    if ($env{'request.course.id'}) {  
1.302     albertel  498:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    499: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    500: 					'/'.$env{'request.course.sec'})) {
1.111     www       501: 	   return '';
                    502:        }
1.999     www       503:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.1337    raeburn   504:        if ($courseadv eq 'only') {
                    505:            $callargs .= ",'',1,'$courseadv'";
                    506:        } elsif ($courseadv eq 'none') {
                    507:            $callargs .= ",'','','$courseadv'";
                    508:        } elsif ($courseadv eq 'condition') {
                    509:            $callargs .= ",'','','$courseadv'";
1.1413    raeburn   510:        } elsif ($identelem ne '') {
                    511:            $callargs .= ",'','',''";
                    512:        }
                    513:        if ($identelem ne '') {
                    514:            $callargs .= ",'".&Apache::lonhtmlcommon::entity_encode($identelem)."'";
1.793     raeburn   515:        }
                    516:        return '<span class="LC_nobreak">'.
                    517:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    518:               &mt('Select User').'</a></span>';
1.74      www       519:    }
1.258     albertel  520:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       521:        $callargs .= ",'',1"; 
1.793     raeburn   522:        return '<span class="LC_nobreak">'.
                    523:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    524:               &mt('Select User').'</a></span>';
1.111     www       525:    }
                    526:    return '';
1.91      www       527: }
                    528: 
1.1004    www       529: sub selectresource_link {
                    530:    my ($form,$reslink,$arg)=@_;
                    531:    
                    532:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    533:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    534:    unless ($env{'request.course.id'}) { return $arg; }
                    535:    return '<span class="LC_nobreak">'.
                    536:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    537:               $arg.'</a></span>';
                    538: }
                    539: 
                    540: 
                    541: 
1.653     raeburn   542: sub authorbrowser_javascript {
                    543:     return <<"ENDAUTHORBRW";
1.776     bisitz    544: <script type="text/javascript" language="JavaScript">
1.824     bisitz    545: // <![CDATA[
1.653     raeburn   546: var stdeditbrowser;
                    547: 
                    548: function openauthorbrowser(formname,udom) {
                    549:     var url = '/adm/pickauthor?';
                    550:     url += 'form='+formname+'&roledom='+udom;
                    551:     var title = 'Author_Browser';
                    552:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    553:     options += ',width=700,height=600';
                    554:     stdeditbrowser = open(url,title,options,'1');
                    555:     stdeditbrowser.focus();
                    556: }
                    557: 
1.824     bisitz    558: // ]]>
1.653     raeburn   559: </script>
                    560: ENDAUTHORBRW
                    561: }
                    562: 
1.91      www       563: sub coursebrowser_javascript {
1.1116    raeburn   564:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1221    raeburn   565:         $credits_element,$instcode) = @_;
1.932     raeburn   566:     my $wintitle = 'Course_Browser';
1.931     raeburn   567:     if ($crstype eq 'Community') {
1.932     raeburn   568:         $wintitle = 'Community_Browser';
1.909     raeburn   569:     }
1.876     raeburn   570:     my $id_functions = &javascript_index_functions();
                    571:     my $output = '
1.776     bisitz    572: <script type="text/javascript" language="JavaScript">
1.824     bisitz    573: // <![CDATA[
1.468     raeburn   574:     var stdeditbrowser;'."\n";
1.876     raeburn   575: 
                    576:     $output .= <<"ENDSTDBRW";
1.909     raeburn   577:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       578:         var url = '/adm/pickcourse?';
1.895     raeburn   579:         var formid = getFormIdByName(formname);
1.876     raeburn   580:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  581:         if (domainfilter != null) {
                    582:            if (domainfilter != '') {
                    583:                url += 'domainfilter='+domainfilter+'&';
                    584: 	   }
                    585:         }
1.91      www       586:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  587: 	                            '&cdomelement='+udom+
                    588:                                     '&cnameelement='+desc;
1.468     raeburn   589:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   590:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   591:                 url += '&roleelement='+extra_element;
                    592:                 if (domainfilter == null || domainfilter == '') {
                    593:                     url += '&domainfilter='+extra_element;
                    594:                 }
1.234     raeburn   595:             }
1.468     raeburn   596:             else {
                    597:                 if (formname == 'portform') {
                    598:                     url += '&setroles='+extra_element;
1.800     raeburn   599:                 } else {
                    600:                     if (formname == 'rules') {
                    601:                         url += '&fixeddom='+extra_element; 
                    602:                     }
1.468     raeburn   603:                 }
                    604:             }     
1.230     raeburn   605:         }
1.909     raeburn   606:         if (type != null && type != '') {
                    607:             url += '&type='+type;
                    608:         }
                    609:         if (type_elem != null && type_elem != '') {
                    610:             url += '&typeelement='+type_elem;
                    611:         }
1.872     raeburn   612:         if (formname == 'ccrs') {
                    613:             var ownername = document.forms[formid].ccuname.value;
                    614:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1238    raeburn   615:             url += '&cloner='+ownername+':'+ownerdom;
                    616:             if (type == 'Course') {
                    617:                 url += '&crscode='+document.forms[formid].crscode.value;
                    618:             }
1.1221    raeburn   619:         }
                    620:         if (formname == 'requestcrs') {
                    621:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   622:         }
1.293     raeburn   623:         if (multflag !=null && multflag != '') {
                    624:             url += '&multiple='+multflag;
                    625:         }
1.909     raeburn   626:         var title = '$wintitle';
1.91      www       627:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    628:         options += ',width=700,height=600';
                    629:         stdeditbrowser = open(url,title,options,'1');
                    630:         stdeditbrowser.focus();
                    631:     }
1.876     raeburn   632: $id_functions
                    633: ENDSTDBRW
1.1116    raeburn   634:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    635:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    636:                                       $credits_element);
1.876     raeburn   637:     }
                    638:     $output .= '
                    639: // ]]>
                    640: </script>';
                    641:     return $output;
                    642: }
                    643: 
                    644: sub javascript_index_functions {
                    645:     return <<"ENDJS";
                    646: 
                    647: function getFormIdByName(formname) {
                    648:     for (var i=0;i<document.forms.length;i++) {
                    649:         if (document.forms[i].name == formname) {
                    650:             return i;
                    651:         }
                    652:     }
                    653:     return -1;
                    654: }
                    655: 
                    656: function getIndexByName(formid,item) {
                    657:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    658:         if (document.forms[formid].elements[i].name == item) {
                    659:             return i;
                    660:         }
                    661:     }
                    662:     return -1;
                    663: }
1.468     raeburn   664: 
1.876     raeburn   665: function getDomainFromSelectbox(formname,udom) {
                    666:     var userdom;
                    667:     var formid = getFormIdByName(formname);
                    668:     if (formid > -1) {
                    669:         var domid = getIndexByName(formid,udom);
                    670:         if (domid > -1) {
                    671:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    672:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    673:             }
                    674:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    675:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   676:             }
                    677:         }
                    678:     }
1.876     raeburn   679:     return userdom;
                    680: }
                    681: 
                    682: ENDJS
1.468     raeburn   683: 
1.876     raeburn   684: }
                    685: 
1.1017    raeburn   686: sub javascript_array_indexof {
1.1018    raeburn   687:     return <<ENDJS;
1.1017    raeburn   688: <script type="text/javascript" language="JavaScript">
                    689: // <![CDATA[
                    690: 
                    691: if (!Array.prototype.indexOf) {
                    692:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    693:         "use strict";
                    694:         if (this === void 0 || this === null) {
                    695:             throw new TypeError();
                    696:         }
                    697:         var t = Object(this);
                    698:         var len = t.length >>> 0;
                    699:         if (len === 0) {
                    700:             return -1;
                    701:         }
                    702:         var n = 0;
                    703:         if (arguments.length > 0) {
                    704:             n = Number(arguments[1]);
1.1088    foxr      705:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   706:                 n = 0;
                    707:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    708:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    709:             }
                    710:         }
                    711:         if (n >= len) {
                    712:             return -1;
                    713:         }
                    714:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    715:         for (; k < len; k++) {
                    716:             if (k in t && t[k] === searchElement) {
                    717:                 return k;
                    718:             }
                    719:         }
                    720:         return -1;
                    721:     }
                    722: }
                    723: 
                    724: // ]]>
                    725: </script>
                    726: 
                    727: ENDJS
                    728: 
                    729: }
                    730: 
1.876     raeburn   731: sub userbrowser_javascript {
                    732:     my $id_functions = &javascript_index_functions();
                    733:     return <<"ENDUSERBRW";
                    734: 
1.888     raeburn   735: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   736:     var url = '/adm/pickuser?';
                    737:     var userdom = getDomainFromSelectbox(formname,udom);
                    738:     if (userdom != null) {
                    739:        if (userdom != '') {
                    740:            url += 'srchdom='+userdom+'&';
                    741:        }
                    742:     }
                    743:     url += 'form=' + formname + '&unameelement='+uname+
                    744:                                 '&udomelement='+udom+
                    745:                                 '&ulastelement='+ulast+
                    746:                                 '&ufirstelement='+ufirst+
                    747:                                 '&uemailelement='+uemail+
1.881     raeburn   748:                                 '&hideudomelement='+hideudom+
                    749:                                 '&coursedom='+crsdom;
1.888     raeburn   750:     if ((caller != null) && (caller != undefined)) {
                    751:         url += '&caller='+caller;
                    752:     }
1.876     raeburn   753:     var title = 'User_Browser';
                    754:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    755:     options += ',width=700,height=600';
                    756:     var stdeditbrowser = open(url,title,options,'1');
                    757:     stdeditbrowser.focus();
                    758: }
                    759: 
1.888     raeburn   760: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   761:     var formid = getFormIdByName(formname);
                    762:     if (formid > -1) {
1.888     raeburn   763:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   764:         var domid = getIndexByName(formid,udom);
                    765:         var hidedomid = getIndexByName(formid,origdom);
                    766:         if (hidedomid > -1) {
                    767:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   768:             var unameval = document.forms[formid].elements[unameid].value;
                    769:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    770:                 if (domid > -1) {
                    771:                     var slct = document.forms[formid].elements[domid];
                    772:                     if (slct.type == 'select-one') {
                    773:                         var i;
                    774:                         for (i=0;i<slct.length;i++) {
                    775:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    776:                         }
                    777:                     }
                    778:                     if (slct.type == 'hidden') {
                    779:                         slct.value = fixeddom;
1.876     raeburn   780:                     }
                    781:                 }
1.468     raeburn   782:             }
                    783:         }
                    784:     }
1.876     raeburn   785:     return;
                    786: }
                    787: 
                    788: $id_functions
                    789: ENDUSERBRW
1.468     raeburn   790: }
                    791: 
                    792: sub setsec_javascript {
1.1116    raeburn   793:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   794:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    795:         $communityrolestr);
                    796:     if ($role_element ne '') {
                    797:         my @allroles = ('st','ta','ep','in','ad');
                    798:         foreach my $crstype ('Course','Community') {
                    799:             if ($crstype eq 'Community') {
                    800:                 foreach my $role (@allroles) {
                    801:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    802:                 }
                    803:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    804:             } else {
                    805:                 foreach my $role (@allroles) {
                    806:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    807:                 }
                    808:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    809:             }
                    810:         }
                    811:         $rolestr = '"'.join('","',@allroles).'"';
                    812:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    813:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    814:     }
1.468     raeburn   815:     my $setsections = qq|
                    816: function setSect(sectionlist) {
1.629     raeburn   817:     var sectionsArray = new Array();
                    818:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    819:         sectionsArray = sectionlist.split(",");
                    820:     }
1.468     raeburn   821:     var numSections = sectionsArray.length;
                    822:     document.$formname.$sec_element.length = 0;
                    823:     if (numSections == 0) {
                    824:         document.$formname.$sec_element.multiple=false;
                    825:         document.$formname.$sec_element.size=1;
                    826:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    827:     } else {
                    828:         if (numSections == 1) {
                    829:             document.$formname.$sec_element.multiple=false;
                    830:             document.$formname.$sec_element.size=1;
                    831:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    832:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    833:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    834:         } else {
                    835:             for (var i=0; i<numSections; i++) {
                    836:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    837:             }
                    838:             document.$formname.$sec_element.multiple=true
                    839:             if (numSections < 3) {
                    840:                 document.$formname.$sec_element.size=numSections;
                    841:             } else {
                    842:                 document.$formname.$sec_element.size=3;
                    843:             }
                    844:             document.$formname.$sec_element.options[0].selected = false
                    845:         }
                    846:     }
1.91      www       847: }
1.905     raeburn   848: 
                    849: function setRole(crstype) {
1.468     raeburn   850: |;
1.905     raeburn   851:     if ($role_element eq '') {
                    852:         $setsections .= '    return;
                    853: }
                    854: ';
                    855:     } else {
                    856:         $setsections .= qq|
                    857:     var elementLength = document.$formname.$role_element.length;
                    858:     var allroles = Array($rolestr);
                    859:     var courserolenames = Array($courserolestr);
                    860:     var communityrolenames = Array($communityrolestr);
                    861:     if (elementLength != undefined) {
                    862:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    863:             if (crstype == 'Course') {
                    864:                 return;
                    865:             } else {
                    866:                 allroles[5] = 'co';
                    867:                 for (var i=0; i<6; i++) {
                    868:                     document.$formname.$role_element.options[i].value = allroles[i];
                    869:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    870:                 }
                    871:             }
                    872:         } else {
                    873:             if (crstype == 'Community') {
                    874:                 return;
                    875:             } else {
                    876:                 allroles[5] = 'cc';
                    877:                 for (var i=0; i<6; i++) {
                    878:                     document.$formname.$role_element.options[i].value = allroles[i];
                    879:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    880:                 }
                    881:             }
                    882:         }
                    883:     }
                    884:     return;
                    885: }
                    886: |;
                    887:     }
1.1116    raeburn   888:     if ($credits_element) {
                    889:         $setsections .= qq|
                    890: function setCredits(defaultcredits) {
                    891:     document.$formname.$credits_element.value = defaultcredits;
                    892:     return;
                    893: }
                    894: |;
                    895:     }
1.468     raeburn   896:     return $setsections;
                    897: }
                    898: 
1.91      www       899: sub selectcourse_link {
1.909     raeburn   900:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    901:        $typeelement) = @_;
                    902:    my $type = $selecttype;
1.871     raeburn   903:    my $linktext = &mt('Select Course');
                    904:    if ($selecttype eq 'Community') {
1.909     raeburn   905:        $linktext = &mt('Select Community');
1.1239    raeburn   906:    } elsif ($selecttype eq 'Placement') {
                    907:        $linktext = &mt('Select Placement Test'); 
1.906     raeburn   908:    } elsif ($selecttype eq 'Course/Community') {
                    909:        $linktext = &mt('Select Course/Community');
1.909     raeburn   910:        $type = '';
1.1019    raeburn   911:    } elsif ($selecttype eq 'Select') {
                    912:        $linktext = &mt('Select');
                    913:        $type = '';
1.871     raeburn   914:    }
1.787     bisitz    915:    return '<span class="LC_nobreak">'
                    916:          ."<a href='"
                    917:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    918:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   919:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   920:          ."'>".$linktext.'</a>'
1.787     bisitz    921:          .'</span>';
1.74      www       922: }
1.42      matthew   923: 
1.653     raeburn   924: sub selectauthor_link {
                    925:    my ($form,$udom)=@_;
                    926:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    927:           &mt('Select Author').'</a>';
                    928: }
                    929: 
1.876     raeburn   930: sub selectuser_link {
1.881     raeburn   931:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   932:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   933:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   934:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   935:            ');">'.$linktext.'</a>';
1.876     raeburn   936: }
                    937: 
1.273     raeburn   938: sub check_uncheck_jscript {
                    939:     my $jscript = <<"ENDSCRT";
                    940: function checkAll(field) {
                    941:     if (field.length > 0) {
                    942:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   943:             if (!field[i].disabled) { 
                    944:                 field[i].checked = true;
                    945:             }
1.273     raeburn   946:         }
                    947:     } else {
1.1093    raeburn   948:         if (!field.disabled) { 
                    949:             field.checked = true;
                    950:         }
1.273     raeburn   951:     }
                    952: }
                    953:  
                    954: function uncheckAll(field) {
                    955:     if (field.length > 0) {
                    956:         for (i = 0; i < field.length; i++) {
                    957:             field[i].checked = false ;
1.543     albertel  958:         }
                    959:     } else {
1.273     raeburn   960:         field.checked = false ;
                    961:     }
                    962: }
                    963: ENDSCRT
                    964:     return $jscript;
                    965: }
                    966: 
1.656     www       967: sub select_timezone {
1.1387    raeburn   968:    my ($name,$selected,$onchange,$includeempty,$id,$disabled)=@_;
                    969:    my $output='<select name="'.$name.'" '.$id.$onchange.$disabled.'>'."\n";
1.659     raeburn   970:    if ($includeempty) {
                    971:        $output .= '<option value=""';
                    972:        if (($selected eq '') || ($selected eq 'local')) {
                    973:            $output .= ' selected="selected" ';
                    974:        }
                    975:        $output .= '> </option>';
                    976:    }
1.657     raeburn   977:    my @timezones = DateTime::TimeZone->all_names;
                    978:    foreach my $tzone (@timezones) {
                    979:        $output.= '<option value="'.$tzone.'"';
                    980:        if ($tzone eq $selected) {
                    981:            $output.=' selected="selected"';
                    982:        }
                    983:        $output.=">$tzone</option>\n";
1.656     www       984:    }
                    985:    $output.="</select>";
                    986:    return $output;
                    987: }
1.273     raeburn   988: 
1.687     raeburn   989: sub select_datelocale {
1.1256    raeburn   990:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    991:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   992:     if ($includeempty) {
                    993:         $output .= '<option value=""';
                    994:         if ($selected eq '') {
                    995:             $output .= ' selected="selected" ';
                    996:         }
                    997:         $output .= '> </option>';
                    998:     }
1.1241    raeburn   999:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn  1000:     my (@possibles,%locale_names);
1.1241    raeburn  1001:     my @locales = DateTime::Locale->ids();
                   1002:     foreach my $id (@locales) {
                   1003:         if ($id ne '') {
                   1004:             my ($en_terr,$native_terr);
                   1005:             my $loc = DateTime::Locale->load($id);
                   1006:             if (ref($loc)) {
                   1007:                 $en_terr = $loc->name();
                   1008:                 $native_terr = $loc->native_name();
1.687     raeburn  1009:                 if (grep(/^en$/,@languages) || !@languages) {
                   1010:                     if ($en_terr ne '') {
                   1011:                         $locale_names{$id} = '('.$en_terr.')';
                   1012:                     } elsif ($native_terr ne '') {
                   1013:                         $locale_names{$id} = $native_terr;
                   1014:                     }
                   1015:                 } else {
                   1016:                     if ($native_terr ne '') {
                   1017:                         $locale_names{$id} = $native_terr.' ';
                   1018:                     } elsif ($en_terr ne '') {
                   1019:                         $locale_names{$id} = '('.$en_terr.')';
                   1020:                     }
                   1021:                 }
1.1220    raeburn  1022:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1241    raeburn  1023:                 push(@possibles,$id);
                   1024:             } 
1.687     raeburn  1025:         }
                   1026:     }
                   1027:     foreach my $item (sort(@possibles)) {
                   1028:         $output.= '<option value="'.$item.'"';
                   1029:         if ($item eq $selected) {
                   1030:             $output.=' selected="selected"';
                   1031:         }
                   1032:         $output.=">$item";
                   1033:         if ($locale_names{$item} ne '') {
1.1220    raeburn  1034:             $output.='  '.$locale_names{$item};
1.687     raeburn  1035:         }
                   1036:         $output.="</option>\n";
                   1037:     }
                   1038:     $output.="</select>";
                   1039:     return $output;
                   1040: }
                   1041: 
1.792     raeburn  1042: sub select_language {
1.1256    raeburn  1043:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1044:     my %langchoices;
                   1045:     if ($includeempty) {
1.1117    raeburn  1046:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1047:     }
                   1048:     foreach my $id (&languageids()) {
                   1049:         my $code = &supportedlanguagecode($id);
                   1050:         if ($code) {
                   1051:             $langchoices{$code} = &plainlanguagedescription($id);
                   1052:         }
                   1053:     }
1.1117    raeburn  1054:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1256    raeburn  1055:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1056: }
                   1057: 
1.42      matthew  1058: =pod
1.36      matthew  1059: 
1.1088    foxr     1060: 
                   1061: =item * &list_languages()
                   1062: 
                   1063: Returns an array reference that is suitable for use in language prompters.
                   1064: Each array element is itself a two element array.  The first element
                   1065: is the language code.  The second element a descsriptiuon of the 
                   1066: language itself.  This is suitable for use in e.g.
                   1067: &Apache::edit::select_arg (once dereferenced that is).
                   1068: 
                   1069: =cut 
                   1070: 
                   1071: sub list_languages {
                   1072:     my @lang_choices;
                   1073: 
                   1074:     foreach my $id (&languageids()) {
                   1075: 	my $code = &supportedlanguagecode($id);
                   1076: 	if ($code) {
                   1077: 	    my $selector    = $supported_codes{$id};
                   1078: 	    my $description = &plainlanguagedescription($id);
1.1263    raeburn  1079: 	    push(@lang_choices, [$selector, $description]);
1.1088    foxr     1080: 	}
                   1081:     }
                   1082:     return \@lang_choices;
                   1083: }
                   1084: 
                   1085: =pod
                   1086: 
1.648     raeburn  1087: =item * &linked_select_forms(...)
1.36      matthew  1088: 
                   1089: linked_select_forms returns a string containing a <script></script> block
                   1090: and html for two <select> menus.  The select menus will be linked in that
                   1091: changing the value of the first menu will result in new values being placed
                   1092: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1093: order unless a defined order is provided.
1.36      matthew  1094: 
                   1095: linked_select_forms takes the following ordered inputs:
                   1096: 
                   1097: =over 4
                   1098: 
1.112     bowersj2 1099: =item * $formname, the name of the <form> tag
1.36      matthew  1100: 
1.112     bowersj2 1101: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1102: 
1.112     bowersj2 1103: =item * $firstdefault, the default value for the first menu
1.36      matthew  1104: 
1.112     bowersj2 1105: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1106: 
1.112     bowersj2 1107: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1108: 
1.112     bowersj2 1109: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1110: 
1.609     raeburn  1111: =item * $menuorder, the order of values in the first menu
                   1112: 
1.1115    raeburn  1113: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1114:         event for the first <select> tag
                   1115: 
                   1116: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1117:         event for the second <select> tag
                   1118: 
1.1245    raeburn  1119: =item * $suffix, to differentiate separate uses of select2data javascript
                   1120:         objects in a page.
                   1121: 
1.41      ng       1122: =back 
                   1123: 
1.36      matthew  1124: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1125: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1126: values for the first select menu.  The text that coincides with the 
1.41      ng       1127: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1128: and text for the second menu are given in the hash pointed to by 
                   1129: $menu{$choice1}->{'select2'}.  
                   1130: 
1.112     bowersj2 1131:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1132:                        default => "B3",
                   1133:                        select2 => { 
                   1134:                            B1 => "Choice B1",
                   1135:                            B2 => "Choice B2",
                   1136:                            B3 => "Choice B3",
                   1137:                            B4 => "Choice B4"
1.609     raeburn  1138:                            },
                   1139:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1140:                    },
                   1141:                A2 => { text =>"Choice A2" ,
                   1142:                        default => "C2",
                   1143:                        select2 => { 
                   1144:                            C1 => "Choice C1",
                   1145:                            C2 => "Choice C2",
                   1146:                            C3 => "Choice C3"
1.609     raeburn  1147:                            },
                   1148:                        order => ['C2','C1','C3'],
1.112     bowersj2 1149:                    },
                   1150:                A3 => { text =>"Choice A3" ,
                   1151:                        default => "D6",
                   1152:                        select2 => { 
                   1153:                            D1 => "Choice D1",
                   1154:                            D2 => "Choice D2",
                   1155:                            D3 => "Choice D3",
                   1156:                            D4 => "Choice D4",
                   1157:                            D5 => "Choice D5",
                   1158:                            D6 => "Choice D6",
                   1159:                            D7 => "Choice D7"
1.609     raeburn  1160:                            },
                   1161:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1162:                    }
                   1163:                );
1.36      matthew  1164: 
                   1165: =cut
                   1166: 
                   1167: sub linked_select_forms {
                   1168:     my ($formname,
                   1169:         $middletext,
                   1170:         $firstdefault,
                   1171:         $firstselectname,
                   1172:         $secondselectname, 
1.609     raeburn  1173:         $hashref,
                   1174:         $menuorder,
1.1115    raeburn  1175:         $onchangefirst,
1.1245    raeburn  1176:         $onchangesecond,
                   1177:         $suffix
1.36      matthew  1178:         ) = @_;
                   1179:     my $second = "document.$formname.$secondselectname";
                   1180:     my $first = "document.$formname.$firstselectname";
                   1181:     # output the javascript to do the changing
                   1182:     my $result = '';
1.776     bisitz   1183:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1184:     $result.="// <![CDATA[\n";
1.1245    raeburn  1185:     $result.="var select2data${suffix} = new Object();\n";
1.36      matthew  1186:     $" = '","';
                   1187:     my $debug = '';
                   1188:     foreach my $s1 (sort(keys(%$hashref))) {
1.1245    raeburn  1189:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
                   1190:         $result.="select2data${suffix}['d_$s1'].def = new String('".
1.36      matthew  1191:             $hashref->{$s1}->{'default'}."');\n";
1.1245    raeburn  1192:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
1.36      matthew  1193:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1194:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1195:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1196:         }
1.36      matthew  1197:         $result.="\"@s2values\");\n";
1.1245    raeburn  1198:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
1.36      matthew  1199:         my @s2texts;
                   1200:         foreach my $value (@s2values) {
1.1263    raeburn  1201:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1202:         }
                   1203:         $result.="\"@s2texts\");\n";
                   1204:     }
                   1205:     $"=' ';
                   1206:     $result.= <<"END";
                   1207: 
1.1245    raeburn  1208: function select1${suffix}_changed() {
1.36      matthew  1209:     // Determine new choice
1.1245    raeburn  1210:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1.36      matthew  1211:     // update select2
1.1245    raeburn  1212:     var values     = select2data${suffix}[newvalue].values;
                   1213:     var texts      = select2data${suffix}[newvalue].texts;
                   1214:     var select2def = select2data${suffix}[newvalue].def;
1.36      matthew  1215:     var i;
                   1216:     // out with the old
1.1245    raeburn  1217:     $second.options.length = 0;
                   1218:     // in with the new
1.36      matthew  1219:     for (i=0;i<values.length; i++) {
                   1220:         $second.options[i] = new Option(values[i]);
1.143     matthew  1221:         $second.options[i].value = values[i];
1.36      matthew  1222:         $second.options[i].text = texts[i];
                   1223:         if (values[i] == select2def) {
                   1224:             $second.options[i].selected = true;
                   1225:         }
                   1226:     }
                   1227: }
1.824     bisitz   1228: // ]]>
1.36      matthew  1229: </script>
                   1230: END
                   1231:     # output the initial values for the selection lists
1.1245    raeburn  1232:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1.609     raeburn  1233:     my @order = sort(keys(%{$hashref}));
                   1234:     if (ref($menuorder) eq 'ARRAY') {
                   1235:         @order = @{$menuorder};
                   1236:     }
                   1237:     foreach my $value (@order) {
1.36      matthew  1238:         $result.="    <option value=\"$value\" ";
1.253     albertel 1239:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1240:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1241:     }
                   1242:     $result .= "</select>\n";
1.1400    raeburn  1243:     my %select2;
                   1244:     if (ref($hashref->{$firstdefault}) eq 'HASH') {
                   1245:         if (ref($hashref->{$firstdefault}->{'select2'}) eq 'HASH') {
                   1246:             %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1247:         }
                   1248:     }
1.36      matthew  1249:     $result .= $middletext;
1.1115    raeburn  1250:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1251:     if ($onchangesecond) {
                   1252:         $result .= ' onchange="'.$onchangesecond.'"';
                   1253:     }
                   1254:     $result .= ">\n";
1.36      matthew  1255:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1256:     
                   1257:     my @secondorder = sort(keys(%select2));
                   1258:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1259:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1260:     }
                   1261:     foreach my $value (@secondorder) {
1.36      matthew  1262:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1263:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1264:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1265:     }
                   1266:     $result .= "</select>\n";
                   1267:     #    return $debug;
                   1268:     return $result;
                   1269: }   #  end of sub linked_select_forms {
                   1270: 
1.45      matthew  1271: =pod
1.44      bowersj2 1272: 
1.1381    raeburn  1273: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid,$links_target)
1.44      bowersj2 1274: 
1.112     bowersj2 1275: Returns a string corresponding to an HTML link to the given help
                   1276: $topic, where $topic corresponds to the name of a .tex file in
                   1277: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1278: spaces. 
                   1279: 
                   1280: $text will optionally be linked to the same topic, allowing you to
                   1281: link text in addition to the graphic. If you do not want to link
                   1282: text, but wish to specify one of the later parameters, pass an
                   1283: empty string. 
                   1284: 
                   1285: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1286: the link will not open a new window. If false, the link will open
                   1287: a new window using Javascript. (Default is false.) 
                   1288: 
                   1289: $width and $height are optional numerical parameters that will
                   1290: override the width and height of the popped up window, which may
1.973     raeburn  1291: be useful for certain help topics with big pictures included.
                   1292: 
                   1293: $imgid is the id of the img tag used for the help icon. This may be
                   1294: used in a javascript call to switch the image src.  See 
                   1295: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1296: 
1.1381    raeburn  1297: $links_target will optionally be set to a target (_top, _parent or _self).
                   1298: 
1.44      bowersj2 1299: =cut
                   1300: 
                   1301: sub help_open_topic {
1.1381    raeburn  1302:     my ($topic, $text, $stayOnPage, $width, $height, $imgid, $links_target) = @_;
1.48      bowersj2 1303:     $text = "" if (not defined $text);
1.44      bowersj2 1304:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1305:     $width = 500 if (not defined $width);
1.44      bowersj2 1306:     $height = 400 if (not defined $height);
                   1307:     my $filename = $topic;
                   1308:     $filename =~ s/ /_/g;
                   1309: 
1.48      bowersj2 1310:     my $template = "";
                   1311:     my $link;
1.572     banghart 1312:     
1.159     www      1313:     $topic=~s/\W/\_/g;
1.44      bowersj2 1314: 
1.572     banghart 1315:     if (!$stayOnPage) {
1.1033    www      1316: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1317:     } elsif ($stayOnPage eq 'popup') {
                   1318:         $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 1319:     } else {
1.48      bowersj2 1320: 	$link = "/adm/help/${filename}.hlp";
                   1321:     }
                   1322: 
                   1323:     # Add the text
1.1314    raeburn  1324:     my $target = ' target="_top"';
1.1381    raeburn  1325:     if ($links_target) {
                   1326:         $target = ' target="'.$links_target.'"';
                   1327:     } elsif ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1328:              (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1329:         $target = '';
1.1378    raeburn  1330:     }
1.1380    raeburn  1331:     if ($text ne "") {
1.763     bisitz   1332: 	$template.='<span class="LC_help_open_topic">'
1.1314    raeburn  1333:                   .'<a'.$target.' href="'.$link.'">'
1.763     bisitz   1334:                   .$text.'</a>';
1.48      bowersj2 1335:     }
                   1336: 
1.763     bisitz   1337:     # (Always) Add the graphic
1.179     matthew  1338:     my $title = &mt('Online Help');
1.667     raeburn  1339:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1340:     if ($imgid ne '') {
                   1341:         $imgid = ' id="'.$imgid.'"';
                   1342:     }
1.1314    raeburn  1343:     $template.=' <a'.$target.' href="'.$link.'" title="'.$title.'">'
1.763     bisitz   1344:               .'<img src="'.$helpicon.'" border="0"'
                   1345:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1346:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1347:               .' /></a>';
                   1348:     if ($text ne "") {	
                   1349:         $template.='</span>';
                   1350:     }
1.44      bowersj2 1351:     return $template;
                   1352: 
1.106     bowersj2 1353: }
                   1354: 
                   1355: # This is a quicky function for Latex cheatsheet editing, since it 
                   1356: # appears in at least four places
                   1357: sub helpLatexCheatsheet {
1.1037    www      1358:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1359:     my $out;
1.106     bowersj2 1360:     my $addOther = '';
1.732     raeburn  1361:     if ($topic) {
1.1037    www      1362: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1363:     }
                   1364:     $out = '<span>' # Start cheatsheet
                   1365: 	  .$addOther
                   1366:           .'<span>'
1.1037    www      1367: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1368: 	  .'</span> <span>'
1.1037    www      1369: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1370: 	  .'</span>';
1.732     raeburn  1371:     unless ($not_author) {
1.1186    kruse    1372:         $out .= '<span>'
                   1373:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1374:                .'</span> <span>'
1.1424    raeburn  1375:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.763     bisitz   1376: 	       .'</span>';
1.732     raeburn  1377:     }
1.763     bisitz   1378:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1379:     return $out;
1.172     www      1380: }
                   1381: 
1.430     albertel 1382: sub general_help {
                   1383:     my $helptopic='Student_Intro';
                   1384:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1385: 	$helptopic='Authoring_Intro';
1.907     raeburn  1386:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1387: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1388:     } elsif ($env{'request.role'}=~/^dc/) {
                   1389:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1390:     }
                   1391:     return $helptopic;
                   1392: }
                   1393: 
                   1394: sub update_help_link {
                   1395:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1396:     my $origurl = $ENV{'REQUEST_URI'};
                   1397:     $origurl=~s|^/~|/priv/|;
                   1398:     my $timestamp = time;
                   1399:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1400:         $$datum = &escape($$datum);
                   1401:     }
                   1402: 
                   1403:     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";
                   1404:     my $output .= <<"ENDOUTPUT";
                   1405: <script type="text/javascript">
1.824     bisitz   1406: // <![CDATA[
1.430     albertel 1407: banner_link = '$banner_link';
1.824     bisitz   1408: // ]]>
1.430     albertel 1409: </script>
                   1410: ENDOUTPUT
                   1411:     return $output;
                   1412: }
                   1413: 
                   1414: # now just updates the help link and generates a blue icon
1.193     raeburn  1415: sub help_open_menu {
1.1381    raeburn  1416:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text,$links_target) 
1.552     banghart 1417: 	= @_;    
1.949     droeschl 1418:     $stayOnPage = 1;
1.430     albertel 1419:     my $output;
                   1420:     if ($component_help) {
                   1421: 	if (!$text) {
                   1422: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
1.1381    raeburn  1423: 				       $width,$height,'',$links_target);
1.430     albertel 1424: 	} else {
                   1425: 	    my $help_text;
                   1426: 	    $help_text=&unescape($topic);
                   1427: 	    $output='<table><tr><td>'.
                   1428: 		&help_open_topic($component_help,$help_text,$stayOnPage,
1.1381    raeburn  1429: 				 $width,$height,'',$links_target).'</td></tr></table>';
1.430     albertel 1430: 	}
                   1431:     }
                   1432:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1433:     return $output.$banner_link;
                   1434: }
                   1435: 
                   1436: sub top_nav_help {
1.1369    raeburn  1437:     my ($text,$linkattr) = @_;
1.436     albertel 1438:     $text = &mt($text);
1.949     droeschl 1439:     my $stay_on_page = 1;
                   1440: 
1.1168    raeburn  1441:     my ($link,$banner_link);
                   1442:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1443:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1444: 	                         : "javascript:helpMenu('open')";
                   1445:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1446:     }
1.201     raeburn  1447:     my $title = &mt('Get help');
1.1168    raeburn  1448:     if ($link) {
                   1449:         return <<"END";
1.436     albertel 1450: $banner_link
1.1369    raeburn  1451: <a href="$link" title="$title" $linkattr>$text</a>
1.436     albertel 1452: END
1.1168    raeburn  1453:     } else {
                   1454:         return '&nbsp;'.$text.'&nbsp;';
                   1455:     }
1.436     albertel 1456: }
                   1457: 
                   1458: sub help_menu_js {
1.1154    raeburn  1459:     my ($httphost) = @_;
1.949     droeschl 1460:     my $stayOnPage = 1;
1.436     albertel 1461:     my $width = 620;
                   1462:     my $height = 600;
1.430     albertel 1463:     my $helptopic=&general_help();
1.1154    raeburn  1464:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1465:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1466:     my $start_page =
                   1467:         &Apache::loncommon::start_page('Help Menu', undef,
                   1468: 				       {'frameset'    => 1,
                   1469: 					'js_ready'    => 1,
1.1154    raeburn  1470:                                         'use_absolute' => $httphost,
1.331     albertel 1471: 					'add_entries' => {
1.1168    raeburn  1472: 					    'border' => '0', 
1.579     raeburn  1473: 					    'rows'   => "110,*",},});
1.331     albertel 1474:     my $end_page =
                   1475:         &Apache::loncommon::end_page({'frameset' => 1,
                   1476: 				      'js_ready' => 1,});
                   1477: 
1.436     albertel 1478:     my $template .= <<"ENDTEMPLATE";
                   1479: <script type="text/javascript">
1.877     bisitz   1480: // <![CDATA[
1.253     albertel 1481: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1482: var banner_link = '';
1.243     raeburn  1483: function helpMenu(target) {
                   1484:     var caller = this;
                   1485:     if (target == 'open') {
                   1486:         var newWindow = null;
                   1487:         try {
1.262     albertel 1488:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1489:         }
                   1490:         catch(error) {
                   1491:             writeHelp(caller);
                   1492:             return;
                   1493:         }
                   1494:         if (newWindow) {
                   1495:             caller = newWindow;
                   1496:         }
1.193     raeburn  1497:     }
1.243     raeburn  1498:     writeHelp(caller);
                   1499:     return;
                   1500: }
                   1501: function writeHelp(caller) {
1.1168    raeburn  1502:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1503:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1504:     caller.document.close();
                   1505:     caller.focus();
1.193     raeburn  1506: }
1.877     bisitz   1507: // END LON-CAPA Internal -->
1.253     albertel 1508: // ]]>
1.436     albertel 1509: </script>
1.193     raeburn  1510: ENDTEMPLATE
                   1511:     return $template;
                   1512: }
                   1513: 
1.172     www      1514: sub help_open_bug {
                   1515:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1516:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1517:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1518:     $text = "" if (not defined $text);
                   1519: 	$stayOnPage=1;
1.184     albertel 1520:     $width = 600 if (not defined $width);
                   1521:     $height = 600 if (not defined $height);
1.172     www      1522: 
                   1523:     $topic=~s/\W+/\+/g;
                   1524:     my $link='';
                   1525:     my $template='';
1.379     albertel 1526:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1527: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1528:     if (!$stayOnPage)
                   1529:     {
                   1530: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1531:     }
                   1532:     else
                   1533:     {
                   1534: 	$link = $url;
                   1535:     }
1.1314    raeburn  1536: 
1.1382    raeburn  1537:     my $target = '_top';
                   1538:     if ((($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) ||
                   1539:         (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'} eq '_self'))) {
                   1540:         $target = '_blank';
1.1378    raeburn  1541:     }
1.1382    raeburn  1542: 
1.172     www      1543:     # Add the text
                   1544:     if ($text ne "")
                   1545:     {
                   1546: 	$template .= 
                   1547:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.1382    raeburn  1548:   "<td bgcolor='#FF5555'><a target=\"$target\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1549:     }
                   1550: 
                   1551:     # Add the graphic
1.179     matthew  1552:     my $title = &mt('Report a Bug');
1.215     albertel 1553:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1554:     $template .= <<"ENDTEMPLATE";
1.1382    raeburn  1555:  <a target="$target" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1556: ENDTEMPLATE
                   1557:     if ($text ne '') { $template.='</td></tr></table>' };
                   1558:     return $template;
                   1559: 
                   1560: }
                   1561: 
                   1562: sub help_open_faq {
                   1563:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1564:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1565:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1566:     $text = "" if (not defined $text);
                   1567: 	$stayOnPage=1;
                   1568:     $width = 350 if (not defined $width);
                   1569:     $height = 400 if (not defined $height);
                   1570: 
                   1571:     $topic=~s/\W+/\+/g;
                   1572:     my $link='';
                   1573:     my $template='';
                   1574:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1575:     if (!$stayOnPage)
                   1576:     {
                   1577: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1578:     }
                   1579:     else
                   1580:     {
                   1581: 	$link = $url;
                   1582:     }
                   1583: 
                   1584:     # Add the text
                   1585:     if ($text ne "")
                   1586:     {
                   1587: 	$template .= 
1.173     www      1588:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1589:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1590:     }
                   1591: 
                   1592:     # Add the graphic
1.179     matthew  1593:     my $title = &mt('View the FAQ');
1.215     albertel 1594:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1595:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1596:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1597: ENDTEMPLATE
                   1598:     if ($text ne '') { $template.='</td></tr></table>' };
                   1599:     return $template;
                   1600: 
1.44      bowersj2 1601: }
1.37      matthew  1602: 
1.180     matthew  1603: ###############################################################
                   1604: ###############################################################
                   1605: 
1.45      matthew  1606: =pod
                   1607: 
1.648     raeburn  1608: =item * &change_content_javascript():
1.256     matthew  1609: 
                   1610: This and the next function allow you to create small sections of an
                   1611: otherwise static HTML page that you can update on the fly with
                   1612: Javascript, even in Netscape 4.
                   1613: 
                   1614: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1615: must be written to the HTML page once. It will prove the Javascript
                   1616: function "change(name, content)". Calling the change function with the
                   1617: name of the section 
                   1618: you want to update, matching the name passed to C<changable_area>, and
                   1619: the new content you want to put in there, will put the content into
                   1620: that area.
                   1621: 
                   1622: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1623: to contain room for the original contents. You need to "make space"
                   1624: for whatever changes you wish to make, and be B<sure> to check your
                   1625: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1626: it's adequate for updating a one-line status display, but little more.
                   1627: This script will set the space to 100% width, so you only need to
                   1628: worry about height in Netscape 4.
                   1629: 
                   1630: Modern browsers are much less limiting, and if you can commit to the
                   1631: user not using Netscape 4, this feature may be used freely with
                   1632: pretty much any HTML.
                   1633: 
                   1634: =cut
                   1635: 
                   1636: sub change_content_javascript {
                   1637:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1638:     if ($env{'browser.type'} eq 'netscape' &&
                   1639: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1640: 	return (<<NETSCAPE4);
                   1641: 	function change(name, content) {
                   1642: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1643: 	    doc.open();
                   1644: 	    doc.write(content);
                   1645: 	    doc.close();
                   1646: 	}
                   1647: NETSCAPE4
                   1648:     } else {
                   1649: 	# Otherwise, we need to use semi-standards-compliant code
                   1650: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1651: 	# is really scary, and every useful browser supports it
                   1652: 	return (<<DOMBASED);
                   1653: 	function change(name, content) {
                   1654: 	    element = document.getElementById(name);
                   1655: 	    element.innerHTML = content;
                   1656: 	}
                   1657: DOMBASED
                   1658:     }
                   1659: }
                   1660: 
                   1661: =pod
                   1662: 
1.648     raeburn  1663: =item * &changable_area($name,$origContent):
1.256     matthew  1664: 
                   1665: This provides a "changable area" that can be modified on the fly via
                   1666: the Javascript code provided in C<change_content_javascript>. $name is
                   1667: the name you will use to reference the area later; do not repeat the
                   1668: same name on a given HTML page more then once. $origContent is what
                   1669: the area will originally contain, which can be left blank.
                   1670: 
                   1671: =cut
                   1672: 
                   1673: sub changable_area {
                   1674:     my ($name, $origContent) = @_;
                   1675: 
1.258     albertel 1676:     if ($env{'browser.type'} eq 'netscape' &&
                   1677: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1678: 	# If this is netscape 4, we need to use the Layer tag
                   1679: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1680:     } else {
                   1681: 	return "<span id='$name'>$origContent</span>";
                   1682:     }
                   1683: }
                   1684: 
                   1685: =pod
                   1686: 
1.648     raeburn  1687: =item * &viewport_geometry_js 
1.590     raeburn  1688: 
                   1689: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1690: 
                   1691: =cut
                   1692: 
                   1693: 
                   1694: sub viewport_geometry_js { 
                   1695:     return <<"GEOMETRY";
                   1696: var Geometry = {};
                   1697: function init_geometry() {
                   1698:     if (Geometry.init) { return };
                   1699:     Geometry.init=1;
                   1700:     if (window.innerHeight) {
                   1701:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1702:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1703:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1704:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1705:     }
                   1706:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1707:         Geometry.getViewportHeight =
                   1708:             function() { return document.documentElement.clientHeight; };
                   1709:         Geometry.getViewportWidth =
                   1710:             function() { return document.documentElement.clientWidth; };
                   1711: 
                   1712:         Geometry.getHorizontalScroll =
                   1713:             function() { return document.documentElement.scrollLeft; };
                   1714:         Geometry.getVerticalScroll =
                   1715:             function() { return document.documentElement.scrollTop; };
                   1716:     }
                   1717:     else if (document.body.clientHeight) {
                   1718:         Geometry.getViewportHeight =
                   1719:             function() { return document.body.clientHeight; };
                   1720:         Geometry.getViewportWidth =
                   1721:             function() { return document.body.clientWidth; };
                   1722:         Geometry.getHorizontalScroll =
                   1723:             function() { return document.body.scrollLeft; };
                   1724:         Geometry.getVerticalScroll =
                   1725:             function() { return document.body.scrollTop; };
                   1726:     }
                   1727: }
                   1728: 
                   1729: GEOMETRY
                   1730: }
                   1731: 
                   1732: =pod
                   1733: 
1.648     raeburn  1734: =item * &viewport_size_js()
1.590     raeburn  1735: 
                   1736: 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. 
                   1737: 
                   1738: =cut
                   1739: 
                   1740: sub viewport_size_js {
                   1741:     my $geometry = &viewport_geometry_js();
                   1742:     return <<"DIMS";
                   1743: 
                   1744: $geometry
                   1745: 
                   1746: function getViewportDims(width,height) {
                   1747:     init_geometry();
                   1748:     width.value = Geometry.getViewportWidth();
                   1749:     height.value = Geometry.getViewportHeight();
                   1750:     return;
                   1751: }
                   1752: 
                   1753: DIMS
                   1754: }
                   1755: 
                   1756: =pod
                   1757: 
1.648     raeburn  1758: =item * &resize_textarea_js()
1.565     albertel 1759: 
                   1760: emits the needed javascript to resize a textarea to be as big as possible
                   1761: 
                   1762: creates a function resize_textrea that takes two IDs first should be
                   1763: the id of the element to resize, second should be the id of a div that
                   1764: surrounds everything that comes after the textarea, this routine needs
                   1765: to be attached to the <body> for the onload and onresize events.
                   1766: 
                   1767: =cut
                   1768: 
                   1769: sub resize_textarea_js {
1.590     raeburn  1770:     my $geometry = &viewport_geometry_js();
1.565     albertel 1771:     return <<"RESIZE";
                   1772:     <script type="text/javascript">
1.824     bisitz   1773: // <![CDATA[
1.590     raeburn  1774: $geometry
1.565     albertel 1775: 
1.588     albertel 1776: function getX(element) {
                   1777:     var x = 0;
                   1778:     while (element) {
                   1779: 	x += element.offsetLeft;
                   1780: 	element = element.offsetParent;
                   1781:     }
                   1782:     return x;
                   1783: }
                   1784: function getY(element) {
                   1785:     var y = 0;
                   1786:     while (element) {
                   1787: 	y += element.offsetTop;
                   1788: 	element = element.offsetParent;
                   1789:     }
                   1790:     return y;
                   1791: }
                   1792: 
                   1793: 
1.565     albertel 1794: function resize_textarea(textarea_id,bottom_id) {
                   1795:     init_geometry();
                   1796:     var textarea        = document.getElementById(textarea_id);
                   1797:     //alert(textarea);
                   1798: 
1.588     albertel 1799:     var textarea_top    = getY(textarea);
1.565     albertel 1800:     var textarea_height = textarea.offsetHeight;
                   1801:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1802:     var bottom_top      = getY(bottom);
1.565     albertel 1803:     var bottom_height   = bottom.offsetHeight;
                   1804:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1805:     var fudge           = 23;
1.565     albertel 1806:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1807:     if (new_height < 300) {
                   1808: 	new_height = 300;
                   1809:     }
                   1810:     textarea.style.height=new_height+'px';
                   1811: }
1.824     bisitz   1812: // ]]>
1.565     albertel 1813: </script>
                   1814: RESIZE
                   1815: 
                   1816: }
                   1817: 
1.1205    golterma 1818: sub colorfuleditor_js {
1.1248    raeburn  1819:     my $browse_or_search;
                   1820:     my $respath;
                   1821:     my ($cnum,$cdom) = &crsauthor_url();
                   1822:     if ($cnum) {
                   1823:         $respath = "/res/$cdom/$cnum/";
                   1824:         my %js_lt = &Apache::lonlocal::texthash(
                   1825:             sunm => 'Sub-directory name',
                   1826:             save => 'Save page to make this permanent',
                   1827:         );
                   1828:         &js_escape(\%js_lt);
1.1400    raeburn  1829:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1830:         $browse_or_search = <<"END";
                   1831: 
1.1400    raeburn  1832:     $showfile_js
                   1833: 
1.1248    raeburn  1834:     function toggleChooser(form,element,titleid,only,search) {
                   1835:         var disp = 'none';
                   1836:         if (document.getElementById('chooser_'+element)) {
                   1837:             var curr = document.getElementById('chooser_'+element).style.display;
                   1838:             if (curr == 'none') {
                   1839:                 disp='inline';
                   1840:                 if (form.elements['chooser_'+element].length) {
                   1841:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1842:                         form.elements['chooser_'+element][i].checked = false;
                   1843:                     }
                   1844:                 }
                   1845:                 toggleResImport(form,element);
                   1846:             }
                   1847:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1848:             var dirsel = '';
                   1849:             var filesel = '';
                   1850:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1851:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1852:                 if (currcrsres == 'none') {
                   1853:                     dirsel = 'coursepath_'+element;
                   1854:                     var filesel = 'coursefile_'+element;
                   1855:                     var include;
                   1856:                     if (document.getElementById('crsres_include_'+element)) {
                   1857:                         include = document.getElementById('crsres_include_'+element).value;
                   1858:                     }
1.1402    raeburn  1859:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1860:                 }
                   1861:             }
                   1862:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1863:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1864:                 if (currcrsupload == 'none') {
                   1865:                     dirsel = 'crsauthorpath_'+element;
                   1866:                     filesel = '';
1.1402    raeburn  1867:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1868:                 }
                   1869:             }
1.1248    raeburn  1870:         }
                   1871:     }
                   1872: 
1.1400    raeburn  1873:     function toggleCrsFile(form,element) {
1.1248    raeburn  1874:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1875:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1876:             if (curr == 'none') {
1.1400    raeburn  1877:                 if (document.getElementById('coursepath_'+element)) {
                   1878:                     var numdirs;
                   1879:                     if (document.getElementById('coursepath_'+element).length) {
                   1880:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1881:                     }
1.1402    raeburn  1882:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1883:                         (document.getElementById('nocrsres_'+element))) {
                   1884:                         if (numdirs) {
                   1885:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1886:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1887:                         } else {
                   1888:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1889:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1890:                         }
                   1891:                     }
1.1248    raeburn  1892:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1893:                     if (numdirs > 1) {
1.1400    raeburn  1894:                         var selelem = form.elements['coursefile_'+element];
                   1895:                         var i, len = selelem.options.length -1;
                   1896:                         if (len >=0) {
                   1897:                             for (i = len; i >= 0; i--) {
                   1898:                                 selelem.remove(i);
                   1899:                             }
                   1900:                             selelem.options[0] = new Option('','');
                   1901:                         }
1.1248    raeburn  1902:                     }
                   1903:                 }
1.1400    raeburn  1904:             }
1.1248    raeburn  1905:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1906:         }
                   1907:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1908:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1909:             if (document.getElementById('uploadcrsres_'+element)) {
                   1910:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1911:             }
                   1912:         }
                   1913:         return;
                   1914:     }
                   1915: 
1.1400    raeburn  1916:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1917:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1918:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1919:         }
                   1920:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1921:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1922:             if (curr == 'none') {
1.1400    raeburn  1923:                 form.elements['newsubdir_'+element][0].checked = true;
                   1924:                 toggleNewsubdir(form,element);
                   1925:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1926:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1927:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1928:                 }
                   1929:             }
                   1930:         }
                   1931:         return;
                   1932:     }
                   1933: 
                   1934:     function toggleResImport(form,element) {
                   1935:         var choices = new Array('crsres','upload');
                   1936:         for (var i=0; i<choices.length; i++) {
                   1937:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1938:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1939:             }
                   1940:         }
                   1941:     }
                   1942: 
                   1943:     function toggleNewsubdir(form,element) {
                   1944:         var newsub = form.elements['newsubdir_'+element];
                   1945:         if (newsub) {
                   1946:             if (newsub.length) {
                   1947:                 for (var j=0; j<newsub.length; j++) {
                   1948:                     if (newsub[j].checked) {
                   1949:                         if (document.getElementById('newsubdirname_'+element)) {
                   1950:                             if (newsub[j].value == '1') {
                   1951:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1952:                                 if (document.getElementById('newsubdir_'+element)) {
                   1953:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1954:                                 }
                   1955:                             } else {
                   1956:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1957:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1958:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1959:                             }
                   1960:                         }
                   1961:                         break; 
                   1962:                     }
                   1963:                 }
                   1964:             }
                   1965:         }
                   1966:     }
                   1967: 
                   1968:     function updateCrsFile(form,element) {
                   1969:         var directory = form.elements['coursepath_'+element];
                   1970:         var filename = form.elements['coursefile_'+element];
                   1971:         var path = directory.options[directory.selectedIndex].value;
                   1972:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1973:         if (file != '') {
                   1974:             form.elements[element].value = '$respath';
                   1975:             if (path == '/') {
                   1976:                 form.elements[element].value += file;
                   1977:             } else {
                   1978:                 form.elements[element].value += path+'/'+file;
                   1979:             }
                   1980:             unClean();
                   1981:             if (document.getElementById('previewimg_'+element)) {
                   1982:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1983:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1984:             }
                   1985:             if (document.getElementById('showimg_'+element)) {
                   1986:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1987:             }
1.1248    raeburn  1988:         }
                   1989:         toggleChooser(form,element);
                   1990:         return;
                   1991:     }
                   1992: 
                   1993:     function uploadDone(suffix,name) {
                   1994:         if (name) {
                   1995: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1996:             unClean();
                   1997:             toggleChooser(document.forms["lonhomework"],suffix);
                   1998:         }
                   1999:     }
                   2000: 
                   2001: \$(document).ready(function(){
                   2002: 
                   2003:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2004:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2005:             var buttonId = this.id;
                   2006:             var suffix = buttonId.toString();
                   2007:             suffix = suffix.replace(/^crsupload_/,'');
                   2008:             event.preventDefault();
                   2009:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2010:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2011:             \$(this.form).submit();
                   2012:             document.lonhomework.target = '';
                   2013:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2014:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2015:             }
                   2016:             return false;
                   2017:         }
                   2018:     });
                   2019: });
                   2020: END
                   2021:     }
1.1205    golterma 2022:     return <<"COLORFULEDIT"
                   2023: <script type="text/javascript">
                   2024: // <![CDATA[>
                   2025:     function fold_box(curDepth, lastresource){
                   2026: 
                   2027:     // we need a list because there can be several blocks you need to fold in one tag
                   2028:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2029:     // but there is only one folding button per tag
                   2030:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2031: 
                   2032:         if(block.item(0).style.display == 'none'){
                   2033: 
                   2034:             foldbutton.value = '@{[&mt("Hide")]}';
                   2035:             for (i = 0; i < block.length; i++){
                   2036:                 block.item(i).style.display = '';
                   2037:             }
                   2038:         }else{
                   2039: 
                   2040:             foldbutton.value = '@{[&mt("Show")]}';
                   2041:             for (i = 0; i < block.length; i++){
                   2042:                 // block.item(i).style.visibility = 'collapse';
                   2043:                 block.item(i).style.display = 'none';
                   2044:             }
                   2045:         };
                   2046:         saveState(lastresource);
                   2047:     }
                   2048: 
                   2049:     function saveState (lastresource) {
                   2050: 
                   2051:         var tag_list = getTagList();
                   2052:         if(tag_list != null){
                   2053:             var timestamp = new Date().getTime();
                   2054:             var key = lastresource;
                   2055: 
                   2056:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2057:             // starting with timestamp
                   2058:             var value = timestamp+';';
                   2059: 
                   2060:             // building the list of key-value pairs
                   2061:             for(var i = 0; i < tag_list.length; i++){
                   2062:                 value += tag_list[i]+',';
                   2063:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2064:             }
                   2065: 
                   2066:             // only iterate whole storage if nothing to override
                   2067:             if(localStorage.getItem(key) == null){        
                   2068: 
                   2069:                 // prevent storage from growing large
                   2070:                 if(localStorage.length > 50){
                   2071:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2072:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2073:                     var oldest_key;
                   2074:                     
                   2075:                     for(var i = 1; i < localStorage.length; i++){
                   2076:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2077:                             oldest_key = localStorage.key(i);
                   2078:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2079:                         }
                   2080:                     }
                   2081:                     localStorage.removeItem(oldest_key);
                   2082:                 }
                   2083:             }
                   2084:             localStorage.setItem(key,value);
                   2085:         }
                   2086:     }
                   2087: 
                   2088:     // restore folding status of blocks (on page load)
                   2089:     function restoreState (lastresource) {
                   2090:         if(localStorage.getItem(lastresource) != null){
                   2091:             var key = lastresource;
                   2092:             var value = localStorage.getItem(key);
                   2093:             var regex_delTimestamp = /^\d+;/;
                   2094: 
                   2095:             value.replace(regex_delTimestamp, '');
                   2096: 
                   2097:             var valueArr = value.split(';');
                   2098:             var pairs;
                   2099:             var elements;
                   2100:             for (var i = 0; i < valueArr.length; i++){
                   2101:                 pairs = valueArr[i].split(',');
                   2102:                 elements = document.getElementsByName(pairs[0]);
                   2103: 
                   2104:                 for (var j = 0; j < elements.length; j++){  
                   2105:                     elements[j].style.display = pairs[1];
                   2106:                     if (pairs[1] == "none"){
                   2107:                         var regex_id = /([_\\d]+)\$/;
                   2108:                         regex_id.exec(pairs[0]);
                   2109:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2110:                     }
                   2111:                 }
                   2112:             }
                   2113:         }
                   2114:     }
                   2115: 
                   2116:     function getTagList () {
                   2117:         
                   2118:         var stringToSearch = document.lonhomework.innerHTML;
                   2119: 
                   2120:         var ret = new Array();
                   2121:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2122:         var tag_list = stringToSearch.match(regex_findBlock);
                   2123: 
                   2124:         if(tag_list != null){
                   2125:             for(var i = 0; i < tag_list.length; i++){            
                   2126:                 ret.push(tag_list[i].replace(/"/, ''));
                   2127:             }
                   2128:         }
                   2129:         return ret;
                   2130:     }
                   2131: 
                   2132:     function saveScrollPosition (resource) {
                   2133:         var tag_list = getTagList();
                   2134: 
                   2135:         // we dont always want to jump to the first block
                   2136:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2137:         if(\$(window).scrollTop() > 170){
                   2138:             if(tag_list != null){
                   2139:                 var result;
                   2140:                 for(var i = 0; i < tag_list.length; i++){
                   2141:                     if(isElementInViewport(tag_list[i])){
                   2142:                         result += tag_list[i]+';';
                   2143:                     }
                   2144:                 }
                   2145:                 sessionStorage.setItem('anchor_'+resource, result);
                   2146:             }
                   2147:         } else {
                   2148:             // we dont need to save zero, just delete the item to leave everything tidy
                   2149:             sessionStorage.removeItem('anchor_'+resource);
                   2150:         }
                   2151:     }
                   2152: 
                   2153:     function restoreScrollPosition(resource){
                   2154: 
                   2155:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2156:         if(elem != null){
                   2157:             var tag_list = elem.split(';');
                   2158:             var elem_list;
                   2159: 
                   2160:             for(var i = 0; i < tag_list.length; i++){
                   2161:                 elem_list = document.getElementsByName(tag_list[i]);
                   2162:                 
                   2163:                 if(elem_list.length > 0){
                   2164:                     elem = elem_list[0];
                   2165:                     break;
                   2166:                 }
                   2167:             }
                   2168:             elem.scrollIntoView();
                   2169:         }
                   2170:     }
                   2171: 
                   2172:     function isElementInViewport(el) {
                   2173: 
                   2174:         // change to last element instead of first
                   2175:         var elem = document.getElementsByName(el);
                   2176:         var rect = elem[0].getBoundingClientRect();
                   2177: 
                   2178:         return (
                   2179:             rect.top >= 0 &&
                   2180:             rect.left >= 0 &&
                   2181:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2182:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2183:         );
                   2184:     }
                   2185:     
                   2186:     function autosize(depth){
                   2187:         var cmInst = window['cm'+depth];
                   2188:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2189: 
                   2190:         // is fixed size, switching to dynamic
                   2191:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2192:             cmInst.setSize("","auto");
                   2193:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2194:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2195: 
                   2196:         // is dynamic size, switching to fixed
                   2197:         } else {
                   2198:             cmInst.setSize("","300px");
                   2199:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2200:             sessionStorage.removeItem("autosized_"+depth);
                   2201:         }
                   2202:     }
                   2203: 
1.1248    raeburn  2204: $browse_or_search
1.1205    golterma 2205: 
                   2206: // ]]>
                   2207: </script>
                   2208: COLORFULEDIT
                   2209: }
                   2210: 
                   2211: sub xmleditor_js {
                   2212:     return <<XMLEDIT
                   2213: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2214: <script type="text/javascript">
                   2215: // <![CDATA[>
                   2216: 
                   2217:     function saveScrollPosition (resource) {
                   2218: 
                   2219:         var scrollPos = \$(window).scrollTop();
                   2220:         sessionStorage.setItem(resource,scrollPos);
                   2221:     }
                   2222: 
                   2223:     function restoreScrollPosition(resource){
                   2224: 
                   2225:         var scrollPos = sessionStorage.getItem(resource);
                   2226:         \$(window).scrollTop(scrollPos);
                   2227:     }
                   2228: 
                   2229:     // unless internet explorer
                   2230:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2231: 
                   2232:         \$(document).ready(function() {
                   2233:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2234:         });
                   2235:     }
                   2236: 
                   2237:     // inserts text at cursor position into codemirror (xml editor only)
                   2238:     function insertText(text){
                   2239:         cm.focus();
                   2240:         var curPos = cm.getCursor();
                   2241:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2242:     }
                   2243: // ]]>
                   2244: </script>
                   2245: XMLEDIT
                   2246: }
                   2247: 
                   2248: sub insert_folding_button {
                   2249:     my $curDepth = $Apache::lonxml::curdepth;
                   2250:     my $lastresource = $env{'request.ambiguous'};
                   2251: 
                   2252:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2253:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2254: }
                   2255: 
1.1248    raeburn  2256: sub crsauthor_url {
                   2257:     my ($url) = @_;
                   2258:     if ($url eq '') {
                   2259:         $url = $ENV{'REQUEST_URI'};
                   2260:     }
                   2261:     my ($cnum,$cdom);
                   2262:     if ($env{'request.course.id'}) {
                   2263:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2264:         if ($audom ne '' && $auname ne '') {
                   2265:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2266:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2267:                 $cnum = $auname;
                   2268:                 $cdom = $audom;
                   2269:             }
                   2270:         }
                   2271:     }
                   2272:     return ($cnum,$cdom);
                   2273: }
                   2274: 
                   2275: sub import_crsauthor_form {
1.1400    raeburn  2276:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2277:     return (0) unless ($env{'request.course.id'});
                   2278:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2279:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2280:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2281:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2282:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2283:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2284: 
1.1248    raeburn  2285:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2286:         $is_home = 1;
                   2287:     }
1.1400    raeburn  2288:     $toppath = "/priv/$cdom/$cnum";
                   2289:     my $nonemptydir = 1;
                   2290:     my $js_only;
                   2291:     if ($only) {
                   2292:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2293:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2294:     }
                   2295:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2296:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2297:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2298:     my %lt = &Apache::lonlocal::texthash (
                   2299:         fnam => 'Filename',
                   2300:         dire => 'Directory',
1.1400    raeburn  2301:         se   => 'Select',
1.1248    raeburn  2302:     );
1.1402    raeburn  2303:     $output = $lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2304:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2305:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2306:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2307:     if ($files{'/'}) {
                   2308:         $output .= '<option value="/">/</option>'."\n";
                   2309:     }
1.1400    raeburn  2310:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2311:         next if ($key eq '/');
1.1400    raeburn  2312:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2313:     }
                   2314:     $output .= '</select><br />'."\n".
1.1402    raeburn  2315:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2316:                '<option value="" selected="selected"></option>'."\n".
1.1402    raeburn  2317:                '</select>'."\n".
                   2318:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2319:     return ($numdirs,$output);
                   2320: }
                   2321: 
                   2322: sub show_crsfiles_js {
                   2323:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2324:     my $se = &js_escape(&mt('Select'));
                   2325:     my $exclude;
                   2326:     if (ref($excluderef) eq 'HASH') {
                   2327:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2328:     }
                   2329:     my $js = <<"END";
                   2330: 
                   2331: 
1.1402    raeburn  2332:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2333:         var relpath = '';
                   2334:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2335:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2336:             if (currdir == '') {
                   2337:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2338:                     selelem = form.elements[filesel];
                   2339:                     var j, numfiles = selelem.options.length -1;
                   2340:                     if (numfiles >=0) {
                   2341:                         for (j = numfiles; j >= 0; j--) {
                   2342:                             selelem.remove(j);
                   2343:                         }
                   2344:                     }
                   2345:                     if (selelem.options.length == 0) {
                   2346:                         selelem.options[selelem.options.length] = new Option('','');
                   2347:                         selelem.selectedIndex = 0;
1.1248    raeburn  2348:                     }
                   2349:                 }
1.1400    raeburn  2350:                 return;
                   2351:             } else {
                   2352:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2353:             }
                   2354:         }
1.1400    raeburn  2355:         var http = new XMLHttpRequest();
                   2356:         var url = "/adm/courseauthor";
                   2357:         var crsrole = "$env{'request.role'}";
                   2358:         var exclude = '';
                   2359:         if (exc) {
                   2360:             exclude = '$exclude';
                   2361:         }
1.1402    raeburn  2362:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2363:         http.open("POST", url, true);
                   2364:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2365:         http.onreadystatechange = function() {
                   2366:             if (http.readyState == 4 && http.status == 200) {
                   2367:                 var data = JSON.parse(http.responseText);
                   2368:                 var selelem;
                   2369:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2370:                     if (Array.isArray(data.dirs)) {
                   2371:                         selelem = form.elements[dirsel];
                   2372:                         var i, numdirs = selelem.options.length -1;
                   2373:                         if (numdirs >=0) {
                   2374:                             for (i = numdirs; i >= 0; i--) {
                   2375:                                 selelem.remove(i);
                   2376:                             }
                   2377:                         }
                   2378:                         var len = data.dirs.length;
                   2379:                         if (len) {
1.1402    raeburn  2380:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2381:                             var j;
                   2382:                             for (j = 0; j < len; j++) {
                   2383:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2384:                             }
                   2385:                             selelem.selectedIndex = 0;
                   2386:                         }
                   2387:                         if (!setfile) {
                   2388:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2389:                                 selelem = form.elements[filesel];
                   2390:                                 var j, numfiles = selelem.options.length -1;
                   2391:                                 if (numfiles >=0) {
                   2392:                                     for (j = numfiles; j >= 0; j--) {
                   2393:                                         selelem.remove(j);
                   2394:                                     }
                   2395:                                 }
                   2396:                                 if (selelem.options.length == 0) {
                   2397:                                     selelem.options[selelem.options.length] = new Option('','');
                   2398:                                     selelem.selectedIndex = 0;
                   2399:                                 }
                   2400:                             }
                   2401:                         }
                   2402:                     }
                   2403:                 }
                   2404:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2405:                     selelem = form.elements[filesel];
                   2406:                     var i, numfiles = selelem.options.length -1;
                   2407:                     if (numfiles >=0) {
                   2408:                         for (i = numfiles; i >= 0; i--) {
                   2409:                             selelem.remove(i);
                   2410:                         }
                   2411:                     }
                   2412:                     var x;
                   2413:                     for (x in data.files) {
                   2414:                         if (Array.isArray(data.files[x])) {
                   2415:                             if (data.files[x].length > 1) {
                   2416:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2417:                             }
                   2418:                             var len = data.files[x].length;
                   2419:                             if (len) {
                   2420:                                 var k;
                   2421:                                 for (k = 0; k < len; k++) {
                   2422:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2423:                                 }
                   2424:                                 selelem.selectedIndex = 0;
                   2425:                             }
                   2426:                         }
                   2427:                     }
                   2428:                     if (selelem.options.length == 0) {
                   2429:                         selelem.options[selelem.options.length] = new Option('','');
                   2430:                         selelem.selectedIndex = 0;
                   2431:                     }
1.1248    raeburn  2432:                 }
                   2433:             }
                   2434:         }
1.1400    raeburn  2435:         http.send(params);
1.1248    raeburn  2436:     }
1.1400    raeburn  2437: END
1.1248    raeburn  2438: }
                   2439: 
1.1426    raeburn  2440: sub crsauthor_rights {
                   2441:     my ($rightsfile,$path,$docroot,$cnum,$cdom) = @_;
                   2442:     my $sourcerights = "$path/$rightsfile";
                   2443:     my $now = time;
                   2444:     if (!-e $sourcerights) {
                   2445:         my $cid = $cdom.'_'.$cnum;
                   2446:         if (!-e "$docroot/priv/$cdom") {
                   2447:             mkdir("$docroot/priv/$cdom",0755);
                   2448:         }
                   2449:         if (!-e "$docroot/priv/$cdom/$cnum") {
                   2450:             mkdir("$docroot/priv/$cdom/$cnum",0755);
                   2451:         }
                   2452:         if (open(my $fh,">$sourcerights")) {
                   2453:             print $fh <<END;
                   2454: <accessrule effect="deny" realm="" type="course" role="" />
                   2455: <accessrule effect="allow" realm="$cid" type="course" role="" />
                   2456: END
                   2457:             close($fh);
                   2458:         }
                   2459:     }
                   2460:     if (!-e "$sourcerights.meta") {
                   2461:         if (open(my $fh,">$sourcerights.meta")) {
                   2462:             my $author=$env{'environment.firstname'}.' '.
                   2463:                        $env{'environment.middlename'}.' '.
                   2464:                        $env{'environment.lastname'}.' '.
                   2465:                        $env{'environment.generation'};
                   2466:             $author =~ s/\s+$//;
                   2467:             print $fh <<"END";
                   2468: 
                   2469: <abstract></abstract>
                   2470: <author>$author</author>
                   2471: <authorspace>$cnum:$cdom</authorspace>
                   2472: <copyright>private</copyright>
                   2473: <creationdate>$now</creationdate>
                   2474: <customdistributionfile></customdistributionfile>
                   2475: <dependencies></dependencies>
                   2476: <domain>$cdom</domain>
                   2477: <highestgradelevel>0</highestgradelevel>
                   2478: <keywords></keywords>
1.1445    raeburn  2479: <language>notset</language>
1.1426    raeburn  2480: <lastrevisiondate>$now</lastrevisiondate>
                   2481: <lowestgradelevel>0</lowestgradelevel>
                   2482: <mime>rights</mime>
                   2483: <modifyinguser>$env{'user.name'}:$env{'user.domain'}</modifyinguser>
                   2484: <notes></notes>
                   2485: <obsolete></obsolete>
                   2486: <obsoletereplacement></obsoletereplacement>
                   2487: <owner>$cnum:$cdom</owner>
                   2488: <rule>deny:::course,allow:$cid::course</rule>
                   2489: <sourceavail></sourceavail>
                   2490: <standards></standards>
                   2491: <subject></subject>
                   2492: <title>Course Authoring Rights</title>
                   2493: END
                   2494:             close($fh);
                   2495:         }
                   2496:     }
                   2497:     return;
                   2498: }
                   2499: 
1.565     albertel 2500: =pod
                   2501: 
1.1420    raeburn  2502: =item * &iframe_wrapper_headjs()
                   2503: 
1.1425    raeburn  2504: emits javascript containing two global vars to facilitate handling of resizing
                   2505: by code in iframe_wrapper_resizejs() used when an iframe is present in a page
                   2506: with standard LON-CAPA menus.
                   2507: 
                   2508: =cut
                   2509: 
1.1420    raeburn  2510: #
                   2511: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2512: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2513: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2514: # do not obscure the Functions menu.
                   2515: #
                   2516: 
                   2517: sub iframe_wrapper_headjs {
                   2518:     return <<"ENDJS";
                   2519: <script type="text/javascript">
                   2520: // <![CDATA[
                   2521: var LCnotready = 0;
                   2522: var LCresizedef = 0;
                   2523: // ]]>
                   2524: </script>
                   2525: 
                   2526: ENDJS
                   2527: 
                   2528: }
                   2529: 
                   2530: =pod
                   2531: 
                   2532: =item * &iframe_wrapper_resizejs()
                   2533: 
1.1425    raeburn  2534: emits javascript used to handle resizing for a page containing
                   2535: an iframe, to ensure that the iframe does not obscure any
                   2536: standard LON-CAPA menu items.
                   2537: 
                   2538: =back
                   2539: 
                   2540: =cut
                   2541: 
1.1420    raeburn  2542: #
                   2543: # jQuery to use when iframe is in use and a page resize occurs.
                   2544: # This script will ensure that the iframe does not obscure any
                   2545: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2546: # breadcrumbs and Functions menus. Expects javascript from
                   2547: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2548: # e.g., by inclusion in second arg passed to &start_page().
                   2549: #
                   2550: 
                   2551: sub iframe_wrapper_resizejs {
                   2552:     my $offset = 5;
                   2553:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2554:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2555:         $offset = 0;
                   2556:     }
                   2557:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2558:     \$(document).ready( function() {
                   2559:         \$(window).unbind('resize').resize(function(){
                   2560:             var header = null;
                   2561:             var offset = $offset;
                   2562:             var height = 0;
                   2563:             var hdrtop = 0;
1.1421    raeburn  2564:             if (\$('div.LC_menus_content:first').length) {
                   2565:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2566:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2567:                     offset = 12;
1.1421    raeburn  2568:                 }
                   2569:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2570:                 header = \$('div.LC_head_subbox:first');
                   2571:                 offset = 9;
                   2572:             } else {
                   2573:                 if (\$('#LC_breadcrumbs').length) {
                   2574:                     header = \$('#LC_breadcrumbs');
                   2575:                 }
                   2576:             }
                   2577:             if (header != null && header.length) {
                   2578:                 height = header.height();
                   2579:                 hdrtop = header.position().top;
                   2580:             }
                   2581:             var pos = height + hdrtop + offset;
                   2582:             \$('.LC_iframecontainer').css('top', pos);
                   2583:         });
                   2584:         LCresizedef = 1;
                   2585:         if (LCnotready == 1) {
                   2586:             LCnotready = 0;
                   2587:             \$(window).trigger('resize');
                   2588:         }
                   2589:     });
                   2590:     window.onload = function(){
                   2591:          if (LCresizedef) {
                   2592:              LCnotready = 0;
                   2593:              \$(window).trigger('resize');
                   2594:          } else {
                   2595:              LCnotready = 1;
                   2596:          }
                   2597:     };
                   2598: SCRIPT
                   2599: 
                   2600: }
                   2601: 
                   2602: =pod
                   2603: 
1.256     matthew  2604: =head1 Excel and CSV file utility routines
                   2605: 
                   2606: =cut
                   2607: 
                   2608: ###############################################################
                   2609: ###############################################################
                   2610: 
                   2611: =pod
                   2612: 
1.1162    raeburn  2613: =over 4
                   2614: 
1.648     raeburn  2615: =item * &csv_translate($text) 
1.37      matthew  2616: 
1.185     www      2617: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2618: format.
                   2619: 
                   2620: =cut
                   2621: 
1.180     matthew  2622: ###############################################################
                   2623: ###############################################################
1.37      matthew  2624: sub csv_translate {
                   2625:     my $text = shift;
                   2626:     $text =~ s/\"/\"\"/g;
1.209     albertel 2627:     $text =~ s/\n/ /g;
1.37      matthew  2628:     return $text;
                   2629: }
1.180     matthew  2630: 
                   2631: ###############################################################
                   2632: ###############################################################
                   2633: 
                   2634: =pod
                   2635: 
1.648     raeburn  2636: =item * &define_excel_formats()
1.180     matthew  2637: 
                   2638: Define some commonly used Excel cell formats.
                   2639: 
                   2640: Currently supported formats:
                   2641: 
                   2642: =over 4
                   2643: 
                   2644: =item header
                   2645: 
                   2646: =item bold
                   2647: 
                   2648: =item h1
                   2649: 
                   2650: =item h2
                   2651: 
                   2652: =item h3
                   2653: 
1.256     matthew  2654: =item h4
                   2655: 
                   2656: =item i
                   2657: 
1.180     matthew  2658: =item date
                   2659: 
                   2660: =back
                   2661: 
                   2662: Inputs: $workbook
                   2663: 
                   2664: Returns: $format, a hash reference.
                   2665: 
1.1057    foxr     2666: 
1.180     matthew  2667: =cut
                   2668: 
                   2669: ###############################################################
                   2670: ###############################################################
                   2671: sub define_excel_formats {
                   2672:     my ($workbook) = @_;
                   2673:     my $format;
                   2674:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2675:                                                 bottom    => 1,
                   2676:                                                 align     => 'center');
                   2677:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2678:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2679:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2680:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2681:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2682:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2683:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2684:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2685:     return $format;
                   2686: }
                   2687: 
                   2688: ###############################################################
                   2689: ###############################################################
1.113     bowersj2 2690: 
                   2691: =pod
                   2692: 
1.648     raeburn  2693: =item * &create_workbook()
1.255     matthew  2694: 
                   2695: Create an Excel worksheet.  If it fails, output message on the
                   2696: request object and return undefs.
                   2697: 
                   2698: Inputs: Apache request object
                   2699: 
                   2700: Returns (undef) on failure, 
                   2701:     Excel worksheet object, scalar with filename, and formats 
                   2702:     from &Apache::loncommon::define_excel_formats on success
                   2703: 
                   2704: =cut
                   2705: 
                   2706: ###############################################################
                   2707: ###############################################################
                   2708: sub create_workbook {
                   2709:     my ($r) = @_;
                   2710:         #
                   2711:     # Create the excel spreadsheet
                   2712:     my $filename = '/prtspool/'.
1.258     albertel 2713:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2714:         time.'_'.rand(1000000000).'.xls';
                   2715:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2716:     if (! defined($workbook)) {
                   2717:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2718:         $r->print(
                   2719:             '<p class="LC_error">'
                   2720:            .&mt('Problems occurred in creating the new Excel file.')
                   2721:            .' '.&mt('This error has been logged.')
                   2722:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2723:            .'</p>'
                   2724:         );
1.255     matthew  2725:         return (undef);
                   2726:     }
                   2727:     #
1.1014    foxr     2728:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2729:     #
                   2730:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2731:     return ($workbook,$filename,$format);
                   2732: }
                   2733: 
                   2734: ###############################################################
                   2735: ###############################################################
                   2736: 
                   2737: =pod
                   2738: 
1.648     raeburn  2739: =item * &create_text_file()
1.113     bowersj2 2740: 
1.542     raeburn  2741: Create a file to write to and eventually make available to the user.
1.256     matthew  2742: If file creation fails, outputs an error message on the request object and 
                   2743: return undefs.
1.113     bowersj2 2744: 
1.256     matthew  2745: Inputs: Apache request object, and file suffix
1.113     bowersj2 2746: 
1.256     matthew  2747: Returns (undef) on failure, 
                   2748:     Filehandle and filename on success.
1.113     bowersj2 2749: 
                   2750: =cut
                   2751: 
1.256     matthew  2752: ###############################################################
                   2753: ###############################################################
                   2754: sub create_text_file {
                   2755:     my ($r,$suffix) = @_;
                   2756:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2757:     my $fh;
                   2758:     my $filename = '/prtspool/'.
1.258     albertel 2759:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2760:         time.'_'.rand(1000000000).'.'.$suffix;
                   2761:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2762:     if (! defined($fh)) {
                   2763:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2764:         $r->print(
                   2765:             '<p class="LC_error">'
                   2766:            .&mt('Problems occurred in creating the output file.')
                   2767:            .' '.&mt('This error has been logged.')
                   2768:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2769:            .'</p>'
                   2770:         );
1.113     bowersj2 2771:     }
1.256     matthew  2772:     return ($fh,$filename)
1.113     bowersj2 2773: }
                   2774: 
                   2775: 
1.256     matthew  2776: =pod 
1.113     bowersj2 2777: 
                   2778: =back
                   2779: 
                   2780: =cut
1.37      matthew  2781: 
                   2782: ###############################################################
1.33      matthew  2783: ##        Home server <option> list generating code          ##
                   2784: ###############################################################
1.35      matthew  2785: 
1.169     www      2786: # ------------------------------------------
                   2787: 
                   2788: sub domain_select {
1.1289    raeburn  2789:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2790:     my @possdoms;
                   2791:     if (ref($incdoms) eq 'ARRAY') {
                   2792:         @possdoms = @{$incdoms};
                   2793:     } else {
                   2794:         @possdoms = &Apache::lonnet::all_domains();
                   2795:     }
                   2796: 
1.169     www      2797:     my %domains=map { 
1.514     albertel 2798: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2799:     } @possdoms;
                   2800: 
                   2801:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2802:         foreach my $dom (@{$excdoms}) {
                   2803:             delete($domains{$dom});
                   2804:         }
                   2805:     }
                   2806: 
1.169     www      2807:     if ($multiple) {
                   2808: 	$domains{''}=&mt('Any domain');
1.550     albertel 2809: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2810: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2811:     } else {
1.550     albertel 2812: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2813: 	return &select_form($name,$value,\%domains);
1.169     www      2814:     }
                   2815: }
                   2816: 
1.282     albertel 2817: #-------------------------------------------
                   2818: 
                   2819: =pod
                   2820: 
1.519     raeburn  2821: =head1 Routines for form select boxes
                   2822: 
                   2823: =over 4
                   2824: 
1.648     raeburn  2825: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2826: 
                   2827: Returns a string containing a <select> element int multiple mode
                   2828: 
                   2829: 
                   2830: Args:
                   2831:   $name - name of the <select> element
1.506     raeburn  2832:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2833:   $size - number of rows long the select element is
1.283     albertel 2834:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2835:           (shown text should already have been &mt())
1.506     raeburn  2836:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2837: 
1.282     albertel 2838: =cut
                   2839: 
                   2840: #-------------------------------------------
1.169     www      2841: sub multiple_select_form {
1.284     albertel 2842:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2843:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2844:     my $output='';
1.191     matthew  2845:     if (! defined($size)) {
                   2846:         $size = 4;
1.283     albertel 2847:         if (scalar(keys(%$hash))<4) {
                   2848:             $size = scalar(keys(%$hash));
1.191     matthew  2849:         }
                   2850:     }
1.734     bisitz   2851:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2852:     my @order;
1.506     raeburn  2853:     if (ref($order) eq 'ARRAY')  {
                   2854:         @order = @{$order};
                   2855:     } else {
                   2856:         @order = sort(keys(%$hash));
1.501     banghart 2857:     }
                   2858:     if (exists($$hash{'select_form_order'})) {
                   2859:         @order = @{$$hash{'select_form_order'}};
                   2860:     }
                   2861:         
1.284     albertel 2862:     foreach my $key (@order) {
1.356     albertel 2863:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2864:         $output.='selected="selected" ' if ($selected{$key});
                   2865:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2866:     }
                   2867:     $output.="</select>\n";
                   2868:     return $output;
                   2869: }
                   2870: 
1.88      www      2871: #-------------------------------------------
                   2872: 
                   2873: =pod
                   2874: 
1.1254    raeburn  2875: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2876: 
                   2877: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2878: allow a user to select options from a ref to a hash containing:
                   2879: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2880: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2881: An optional arg -- $readonly -- if true will cause the select form
                   2882: to be disabled, e.g., for the case where an instructor has a section-
                   2883: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2884: 
1.88      www      2885: See lonrights.pm for an example invocation and use.
                   2886: 
                   2887: =cut
                   2888: 
                   2889: #-------------------------------------------
                   2890: sub select_form {
1.1228    raeburn  2891:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2892:     return unless (ref($hashref) eq 'HASH');
                   2893:     if ($onchange) {
                   2894:         $onchange = ' onchange="'.$onchange.'"';
                   2895:     }
1.1228    raeburn  2896:     my $disabled;
                   2897:     if ($readonly) {
                   2898:         $disabled = ' disabled="disabled"';
                   2899:     }
                   2900:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2901:     my @keys;
1.970     raeburn  2902:     if (exists($hashref->{'select_form_order'})) {
                   2903: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2904:     } else {
1.970     raeburn  2905: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2906:     }
1.356     albertel 2907:     foreach my $key (@keys) {
                   2908:         $selectform.=
                   2909: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2910:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2911:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2912:     }
                   2913:     $selectform.="</select>";
                   2914:     return $selectform;
                   2915: }
                   2916: 
1.475     www      2917: # For display filters
                   2918: 
                   2919: sub display_filter {
1.1074    raeburn  2920:     my ($context) = @_;
1.475     www      2921:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2922:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2923:     my $phraseinput = 'hidden';
                   2924:     my $includeinput = 'hidden';
                   2925:     my ($checked,$includetypestext);
                   2926:     if ($env{'form.displayfilter'} eq 'containing') {
                   2927:         $phraseinput = 'text'; 
                   2928:         if ($context eq 'parmslog') {
                   2929:             $includeinput = 'checkbox';
                   2930:             if ($env{'form.includetypes'}) {
                   2931:                 $checked = ' checked="checked"';
                   2932:             }
                   2933:             $includetypestext = &mt('Include parameter types');
                   2934:         }
                   2935:     } else {
                   2936:         $includetypestext = '&nbsp;';
                   2937:     }
                   2938:     my ($additional,$secondid,$thirdid);
                   2939:     if ($context eq 'parmslog') {
                   2940:         $additional = 
                   2941:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2942:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2943:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2944:             '</label>';
                   2945:         $secondid = 'includetypes';
                   2946:         $thirdid = 'includetypestext';
                   2947:     }
                   2948:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2949:                                                     '$secondid','$thirdid')";
                   2950:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2951: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2952: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2953: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2954:            &mt('Filter: [_1]',
1.477     www      2955: 	   &select_form($env{'form.displayfilter'},
                   2956: 			'displayfilter',
1.970     raeburn  2957: 			{'currentfolder' => 'Current folder/page',
1.477     www      2958: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2959: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2960: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2961:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2962:                          '" />'.$additional;
                   2963: }
                   2964: 
                   2965: sub display_filter_js {
                   2966:     my $includetext = &mt('Include parameter types');
                   2967:     return <<"ENDJS";
                   2968:   
                   2969: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2970:     var firstType = 'hidden';
                   2971:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2972:         firstType = 'text';
                   2973:     }
                   2974:     firstObject = document.getElementById(firstid);
                   2975:     if (typeof(firstObject) == 'object') {
                   2976:         if (firstObject.type != firstType) {
                   2977:             changeInputType(firstObject,firstType);
                   2978:         }
                   2979:     }
                   2980:     if (context == 'parmslog') {
                   2981:         var secondType = 'hidden';
                   2982:         if (firstType == 'text') {
                   2983:             secondType = 'checkbox';
                   2984:         }
                   2985:         secondObject = document.getElementById(secondid);  
                   2986:         if (typeof(secondObject) == 'object') {
                   2987:             if (secondObject.type != secondType) {
                   2988:                 changeInputType(secondObject,secondType);
                   2989:             }
                   2990:         }
                   2991:         var textItem = document.getElementById(thirdid);
                   2992:         var currtext = textItem.innerHTML;
                   2993:         var newtext;
                   2994:         if (firstType == 'text') {
                   2995:             newtext = '$includetext';
                   2996:         } else {
                   2997:             newtext = '&nbsp;';
                   2998:         }
                   2999:         if (currtext != newtext) {
                   3000:             textItem.innerHTML = newtext;
                   3001:         }
                   3002:     }
                   3003:     return;
                   3004: }
                   3005: 
                   3006: function changeInputType(oldObject,newType) {
                   3007:     var newObject = document.createElement('input');
                   3008:     newObject.type = newType;
                   3009:     if (oldObject.size) {
                   3010:         newObject.size = oldObject.size;
                   3011:     }
                   3012:     if (oldObject.value) {
                   3013:         newObject.value = oldObject.value;
                   3014:     }
                   3015:     if (oldObject.name) {
                   3016:         newObject.name = oldObject.name;
                   3017:     }
                   3018:     if (oldObject.id) {
                   3019:         newObject.id = oldObject.id;
                   3020:     }
                   3021:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   3022:     return;
                   3023: }
                   3024: 
                   3025: ENDJS
1.475     www      3026: }
                   3027: 
1.167     www      3028: sub gradeleveldescription {
                   3029:     my $gradelevel=shift;
                   3030:     my %gradelevels=(0 => 'Not specified',
                   3031: 		     1 => 'Grade 1',
                   3032: 		     2 => 'Grade 2',
                   3033: 		     3 => 'Grade 3',
                   3034: 		     4 => 'Grade 4',
                   3035: 		     5 => 'Grade 5',
                   3036: 		     6 => 'Grade 6',
                   3037: 		     7 => 'Grade 7',
                   3038: 		     8 => 'Grade 8',
                   3039: 		     9 => 'Grade 9',
                   3040: 		     10 => 'Grade 10',
                   3041: 		     11 => 'Grade 11',
                   3042: 		     12 => 'Grade 12',
                   3043: 		     13 => 'Grade 13',
                   3044: 		     14 => '100 Level',
                   3045: 		     15 => '200 Level',
                   3046: 		     16 => '300 Level',
                   3047: 		     17 => '400 Level',
                   3048: 		     18 => 'Graduate Level');
                   3049:     return &mt($gradelevels{$gradelevel});
                   3050: }
                   3051: 
1.163     www      3052: sub select_level_form {
                   3053:     my ($deflevel,$name)=@_;
                   3054:     unless ($deflevel) { $deflevel=0; }
1.167     www      3055:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   3056:     for (my $i=0; $i<=18; $i++) {
                   3057:         $selectform.="<option value=\"$i\" ".
1.253     albertel 3058:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      3059:                 ">".&gradeleveldescription($i)."</option>\n";
                   3060:     }
                   3061:     $selectform.="</select>";
                   3062:     return $selectform;
1.163     www      3063: }
1.167     www      3064: 
1.35      matthew  3065: #-------------------------------------------
                   3066: 
1.45      matthew  3067: =pod
                   3068: 
1.1256    raeburn  3069: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  3070: 
                   3071: Returns a string containing a <select name='$name' size='1'> form to 
                   3072: allow a user to select the domain to preform an operation in.  
                   3073: See loncreateuser.pm for an example invocation and use.
                   3074: 
1.90      www      3075: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3076: selected");
                   3077: 
1.743     raeburn  3078: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3079: 
1.910     raeburn  3080: 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.
                   3081: 
1.1121    raeburn  3082: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3083: 
                   3084: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3085: 
1.1256    raeburn  3086: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3087: 
1.35      matthew  3088: =cut
                   3089: 
                   3090: #-------------------------------------------
1.34      matthew  3091: sub select_dom_form {
1.1256    raeburn  3092:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  3093:     if ($onchange) {
1.874     raeburn  3094:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3095:     }
1.1256    raeburn  3096:     if ($disabled) {
                   3097:         $disabled = ' disabled="disabled"';
                   3098:     }
1.1121    raeburn  3099:     my (@domains,%exclude);
1.910     raeburn  3100:     if (ref($incdoms) eq 'ARRAY') {
                   3101:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3102:     } else {
                   3103:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3104:     }
1.90      www      3105:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3106:     if (ref($excdoms) eq 'ARRAY') {
                   3107:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3108:     }
1.1256    raeburn  3109:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 3110:     foreach my $dom (@domains) {
1.1121    raeburn  3111:         next if ($exclude{$dom});
1.356     albertel 3112:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3113:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3114:         if ($showdomdesc) {
                   3115:             if ($dom ne '') {
                   3116:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3117:                 if ($domdesc ne '') {
                   3118:                     $selectdomain .= ' ('.$domdesc.')';
                   3119:                 }
                   3120:             } 
                   3121:         }
                   3122:         $selectdomain .= "</option>\n";
1.34      matthew  3123:     }
                   3124:     $selectdomain.="</select>";
                   3125:     return $selectdomain;
                   3126: }
                   3127: 
1.35      matthew  3128: #-------------------------------------------
                   3129: 
1.45      matthew  3130: =pod
                   3131: 
1.648     raeburn  3132: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3133: 
1.586     raeburn  3134: input: 4 arguments (two required, two optional) - 
                   3135:     $domain - domain of new user
                   3136:     $name - name of form element
                   3137:     $default - Value of 'default' causes a default item to be first 
                   3138:                             option, and selected by default. 
                   3139:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3140:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3141: output: returns 2 items: 
1.586     raeburn  3142: (a) form element which contains either:
                   3143:    (i) <select name="$name">
                   3144:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3145:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3146:        </select>
                   3147:        form item if there are multiple library servers in $domain, or
                   3148:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3149:        if there is only one library server in $domain.
                   3150: 
                   3151: (b) number of library servers found.
                   3152: 
                   3153: See loncreateuser.pm for example of use.
1.35      matthew  3154: 
                   3155: =cut
                   3156: 
                   3157: #-------------------------------------------
1.586     raeburn  3158: sub home_server_form_item {
                   3159:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3160:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3161:     my $result;
                   3162:     my $numlib = keys(%servers);
                   3163:     if ($numlib > 1) {
                   3164:         $result .= '<select name="'.$name.'" />'."\n";
                   3165:         if ($default) {
1.804     bisitz   3166:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3167:                        '</option>'."\n";
                   3168:         }
                   3169:         foreach my $hostid (sort(keys(%servers))) {
                   3170:             $result.= '<option value="'.$hostid.'">'.
                   3171: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3172:         }
                   3173:         $result .= '</select>'."\n";
                   3174:     } elsif ($numlib == 1) {
                   3175:         my $hostid;
                   3176:         foreach my $item (keys(%servers)) {
                   3177:             $hostid = $item;
                   3178:         }
                   3179:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3180:                    $hostid.'" />';
                   3181:                    if (!$hide) {
                   3182:                        $result .= $hostid.' '.$servers{$hostid};
                   3183:                    }
                   3184:                    $result .= "\n";
                   3185:     } elsif ($default) {
                   3186:         $result .= '<input type="hidden" name="'.$name.
                   3187:                    '" value="default" />';
                   3188:                    if (!$hide) {
                   3189:                        $result .= &mt('default');
                   3190:                    }
                   3191:                    $result .= "\n";
1.33      matthew  3192:     }
1.586     raeburn  3193:     return ($result,$numlib);
1.33      matthew  3194: }
1.112     bowersj2 3195: 
                   3196: =pod
                   3197: 
1.534     albertel 3198: =back 
                   3199: 
1.112     bowersj2 3200: =cut
1.87      matthew  3201: 
                   3202: ###############################################################
1.112     bowersj2 3203: ##                  Decoding User Agent                      ##
1.87      matthew  3204: ###############################################################
                   3205: 
                   3206: =pod
                   3207: 
1.112     bowersj2 3208: =head1 Decoding the User Agent
                   3209: 
                   3210: =over 4
                   3211: 
                   3212: =item * &decode_user_agent()
1.87      matthew  3213: 
                   3214: Inputs: $r
                   3215: 
                   3216: Outputs:
                   3217: 
                   3218: =over 4
                   3219: 
1.112     bowersj2 3220: =item * $httpbrowser
1.87      matthew  3221: 
1.112     bowersj2 3222: =item * $clientbrowser
1.87      matthew  3223: 
1.112     bowersj2 3224: =item * $clientversion
1.87      matthew  3225: 
1.112     bowersj2 3226: =item * $clientmathml
1.87      matthew  3227: 
1.112     bowersj2 3228: =item * $clientunicode
1.87      matthew  3229: 
1.112     bowersj2 3230: =item * $clientos
1.87      matthew  3231: 
1.1137    raeburn  3232: =item * $clientmobile
                   3233: 
1.1141    raeburn  3234: =item * $clientinfo
                   3235: 
1.1194    raeburn  3236: =item * $clientosversion
                   3237: 
1.87      matthew  3238: =back
                   3239: 
1.157     matthew  3240: =back 
                   3241: 
1.87      matthew  3242: =cut
                   3243: 
                   3244: ###############################################################
                   3245: ###############################################################
                   3246: sub decode_user_agent {
1.247     albertel 3247:     my ($r)=@_;
1.87      matthew  3248:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3249:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3250:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3251:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3252:     my $clientbrowser='unknown';
                   3253:     my $clientversion='0';
                   3254:     my $clientmathml='';
                   3255:     my $clientunicode='0';
1.1137    raeburn  3256:     my $clientmobile=0;
1.1194    raeburn  3257:     my $clientosversion='';
1.87      matthew  3258:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3259:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3260: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3261: 	    $clientbrowser=$bname;
                   3262:             $httpbrowser=~/$vreg/i;
                   3263: 	    $clientversion=$1;
                   3264:             $clientmathml=($clientversion>=$minv);
                   3265:             $clientunicode=($clientversion>=$univ);
                   3266: 	}
                   3267:     }
                   3268:     my $clientos='unknown';
1.1141    raeburn  3269:     my $clientinfo;
1.87      matthew  3270:     if (($httpbrowser=~/linux/i) ||
                   3271:         ($httpbrowser=~/unix/i) ||
                   3272:         ($httpbrowser=~/ux/i) ||
                   3273:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3274:     if (($httpbrowser=~/vax/i) ||
                   3275:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3276:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3277:     if (($httpbrowser=~/mac/i) ||
                   3278:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3279:     if ($httpbrowser=~/win/i) {
                   3280:         $clientos='win';
                   3281:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3282:             $clientosversion = $1;
                   3283:         }
                   3284:     }
1.87      matthew  3285:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3286:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3287:         $clientmobile=lc($1);
                   3288:     }
1.1141    raeburn  3289:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3290:         $clientinfo = 'firefox-'.$1;
                   3291:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3292:         $clientinfo = 'chromeframe-'.$1;
                   3293:     }
1.87      matthew  3294:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3295:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3296:             $clientosversion);
1.87      matthew  3297: }
                   3298: 
1.32      matthew  3299: ###############################################################
                   3300: ##    Authentication changing form generation subroutines    ##
                   3301: ###############################################################
                   3302: ##
                   3303: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3304: ## hash, and have reasonable default values.
                   3305: ##
                   3306: ##    formname = the name given in the <form> tag.
1.35      matthew  3307: #-------------------------------------------
                   3308: 
1.45      matthew  3309: =pod
                   3310: 
1.112     bowersj2 3311: =head1 Authentication Routines
                   3312: 
                   3313: =over 4
                   3314: 
1.648     raeburn  3315: =item * &authform_xxxxxx()
1.35      matthew  3316: 
                   3317: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3318: handle some of the conveniences required for authentication forms.  
                   3319: This is not an optimal method, but it works.  
                   3320: 
                   3321: =over 4
                   3322: 
1.112     bowersj2 3323: =item * authform_header
1.35      matthew  3324: 
1.112     bowersj2 3325: =item * authform_authorwarning
1.35      matthew  3326: 
1.112     bowersj2 3327: =item * authform_nochange
1.35      matthew  3328: 
1.112     bowersj2 3329: =item * authform_kerberos
1.35      matthew  3330: 
1.112     bowersj2 3331: =item * authform_internal
1.35      matthew  3332: 
1.112     bowersj2 3333: =item * authform_filesystem
1.35      matthew  3334: 
1.1310    raeburn  3335: =item * authform_lti
                   3336: 
1.35      matthew  3337: =back
                   3338: 
1.648     raeburn  3339: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3340: 
1.35      matthew  3341: =cut
                   3342: 
                   3343: #-------------------------------------------
1.32      matthew  3344: sub authform_header{  
                   3345:     my %in = (
                   3346:         formname => 'cu',
1.80      albertel 3347:         kerb_def_dom => '',
1.32      matthew  3348:         @_,
                   3349:     );
                   3350:     $in{'formname'} = 'document.' . $in{'formname'};
                   3351:     my $result='';
1.80      albertel 3352: 
                   3353: #---------------------------------------------- Code for upper case translation
                   3354:     my $Javascript_toUpperCase;
                   3355:     unless ($in{kerb_def_dom}) {
                   3356:         $Javascript_toUpperCase =<<"END";
                   3357:         switch (choice) {
                   3358:            case 'krb': currentform.elements[choicearg].value =
                   3359:                currentform.elements[choicearg].value.toUpperCase();
                   3360:                break;
                   3361:            default:
                   3362:         }
                   3363: END
                   3364:     } else {
                   3365:         $Javascript_toUpperCase = "";
                   3366:     }
                   3367: 
1.165     raeburn  3368:     my $radioval = "'nochange'";
1.591     raeburn  3369:     if (defined($in{'curr_authtype'})) {
                   3370:         if ($in{'curr_authtype'} ne '') {
                   3371:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3372:         }
1.174     matthew  3373:     }
1.165     raeburn  3374:     my $argfield = 'null';
1.591     raeburn  3375:     if (defined($in{'mode'})) {
1.165     raeburn  3376:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3377:             if (defined($in{'curr_autharg'})) {
                   3378:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3379:                     $argfield = "'$in{'curr_autharg'}'";
                   3380:                 }
                   3381:             }
                   3382:         }
                   3383:     }
                   3384: 
1.32      matthew  3385:     $result.=<<"END";
                   3386: var current = new Object();
1.165     raeburn  3387: current.radiovalue = $radioval;
                   3388: current.argfield = $argfield;
1.32      matthew  3389: 
                   3390: function changed_radio(choice,currentform) {
                   3391:     var choicearg = choice + 'arg';
                   3392:     // If a radio button in changed, we need to change the argfield
                   3393:     if (current.radiovalue != choice) {
                   3394:         current.radiovalue = choice;
                   3395:         if (current.argfield != null) {
                   3396:             currentform.elements[current.argfield].value = '';
                   3397:         }
                   3398:         if (choice == 'nochange') {
                   3399:             current.argfield = null;
                   3400:         } else {
                   3401:             current.argfield = choicearg;
                   3402:             switch(choice) {
                   3403:                 case 'krb': 
                   3404:                     currentform.elements[current.argfield].value = 
                   3405:                         "$in{'kerb_def_dom'}";
                   3406:                 break;
                   3407:               default:
                   3408:                 break;
                   3409:             }
                   3410:         }
                   3411:     }
                   3412:     return;
                   3413: }
1.22      www      3414: 
1.32      matthew  3415: function changed_text(choice,currentform) {
                   3416:     var choicearg = choice + 'arg';
                   3417:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3418:         $Javascript_toUpperCase
1.32      matthew  3419:         // clear old field
                   3420:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3421:             currentform.elements[current.argfield].value = '';
                   3422:         }
                   3423:         current.argfield = choicearg;
                   3424:     }
                   3425:     set_auth_radio_buttons(choice,currentform);
                   3426:     return;
1.20      www      3427: }
1.32      matthew  3428: 
                   3429: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3430:     var numauthchoices = currentform.login.length;
                   3431:     if (typeof numauthchoices  == "undefined") {
                   3432:         return;
                   3433:     } 
1.32      matthew  3434:     var i=0;
1.986     raeburn  3435:     while (i < numauthchoices) {
1.32      matthew  3436:         if (currentform.login[i].value == newvalue) { break; }
                   3437:         i++;
                   3438:     }
1.986     raeburn  3439:     if (i == numauthchoices) {
1.32      matthew  3440:         return;
                   3441:     }
                   3442:     current.radiovalue = newvalue;
                   3443:     currentform.login[i].checked = true;
                   3444:     return;
                   3445: }
                   3446: END
                   3447:     return $result;
                   3448: }
                   3449: 
1.1106    raeburn  3450: sub authform_authorwarning {
1.32      matthew  3451:     my $result='';
1.144     matthew  3452:     $result='<i>'.
                   3453:         &mt('As a general rule, only authors or co-authors should be '.
                   3454:             'filesystem authenticated '.
                   3455:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3456:     return $result;
                   3457: }
                   3458: 
1.1106    raeburn  3459: sub authform_nochange {
1.32      matthew  3460:     my %in = (
                   3461:               formname => 'document.cu',
                   3462:               kerb_def_dom => 'MSU.EDU',
                   3463:               @_,
                   3464:           );
1.1106    raeburn  3465:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3466:     my $result;
1.1104    raeburn  3467:     if (!$authnum) {
1.1105    raeburn  3468:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3469:     } else {
                   3470:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3471:                   '<input type="radio" name="login" value="nochange" '.
                   3472:                   'checked="checked" onclick="'.
1.281     albertel 3473:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3474: 	    '</label>';
1.586     raeburn  3475:     }
1.32      matthew  3476:     return $result;
                   3477: }
                   3478: 
1.591     raeburn  3479: sub authform_kerberos {
1.32      matthew  3480:     my %in = (
                   3481:               formname => 'document.cu',
                   3482:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3483:               kerb_def_auth => 'krb4',
1.32      matthew  3484:               @_,
                   3485:               );
1.586     raeburn  3486:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3487:         $autharg,$jscall,$disabled);
1.1106    raeburn  3488:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3489:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3490:        $check5 = ' checked="checked"';
1.80      albertel 3491:     } else {
1.772     bisitz   3492:        $check4 = ' checked="checked"';
1.80      albertel 3493:     }
1.1259    raeburn  3494:     if ($in{'readonly'}) {
                   3495:         $disabled = ' disabled="disabled"';
                   3496:     }
1.165     raeburn  3497:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3498:     if (defined($in{'curr_authtype'})) {
                   3499:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3500:             $krbcheck = ' checked="checked"';
1.623     raeburn  3501:             if (defined($in{'mode'})) {
                   3502:                 if ($in{'mode'} eq 'modifyuser') {
                   3503:                     $krbcheck = '';
                   3504:                 }
                   3505:             }
1.591     raeburn  3506:             if (defined($in{'curr_kerb_ver'})) {
                   3507:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3508:                     $check5 = ' checked="checked"';
1.591     raeburn  3509:                     $check4 = '';
                   3510:                 } else {
1.772     bisitz   3511:                     $check4 = ' checked="checked"';
1.591     raeburn  3512:                     $check5 = '';
                   3513:                 }
1.586     raeburn  3514:             }
1.591     raeburn  3515:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3516:                 $krbarg = $in{'curr_autharg'};
                   3517:             }
1.586     raeburn  3518:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3519:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3520:                     $result = 
                   3521:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3522:         $in{'curr_autharg'},$krbver);
                   3523:                 } else {
                   3524:                     $result =
                   3525:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3526:                 }
                   3527:                 return $result; 
                   3528:             }
                   3529:         }
                   3530:     } else {
                   3531:         if ($authnum == 1) {
1.784     bisitz   3532:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3533:         }
                   3534:     }
1.586     raeburn  3535:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3536:         return;
1.587     raeburn  3537:     } elsif ($authtype eq '') {
1.591     raeburn  3538:         if (defined($in{'mode'})) {
1.587     raeburn  3539:             if ($in{'mode'} eq 'modifycourse') {
                   3540:                 if ($authnum == 1) {
1.1259    raeburn  3541:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3542:                 }
                   3543:             }
                   3544:         }
1.586     raeburn  3545:     }
                   3546:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3547:     if ($authtype eq '') {
                   3548:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3549:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3550:                     $krbcheck.$disabled.' />';
1.586     raeburn  3551:     }
                   3552:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3553:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3554:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3555:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3556:          $in{'curr_authtype'} eq 'krb4')) {
                   3557:         $result .= &mt
1.144     matthew  3558:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3559:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3560:          '<label>'.$authtype,
1.281     albertel 3561:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3562:              'value="'.$krbarg.'" '.
1.1259    raeburn  3563:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3564:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3565:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3566: 	 '</label>');
1.586     raeburn  3567:     } elsif ($can_assign{'krb4'}) {
                   3568:         $result .= &mt
                   3569:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3570:          '[_3] Version 4 [_4]',
                   3571:          '<label>'.$authtype,
                   3572:          '</label><input type="text" size="10" name="krbarg" '.
                   3573:              'value="'.$krbarg.'" '.
1.1259    raeburn  3574:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3575:          '<label><input type="hidden" name="krbver" value="4" />',
                   3576:          '</label>');
                   3577:     } elsif ($can_assign{'krb5'}) {
                   3578:         $result .= &mt
                   3579:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3580:          '[_3] Version 5 [_4]',
                   3581:          '<label>'.$authtype,
                   3582:          '</label><input type="text" size="10" name="krbarg" '.
                   3583:              'value="'.$krbarg.'" '.
1.1259    raeburn  3584:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3585:          '<label><input type="hidden" name="krbver" value="5" />',
                   3586:          '</label>');
                   3587:     }
1.32      matthew  3588:     return $result;
                   3589: }
                   3590: 
1.1106    raeburn  3591: sub authform_internal {
1.586     raeburn  3592:     my %in = (
1.32      matthew  3593:                 formname => 'document.cu',
                   3594:                 kerb_def_dom => 'MSU.EDU',
                   3595:                 @_,
                   3596:                 );
1.1259    raeburn  3597:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3598:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3599:     if ($in{'readonly'}) {
                   3600:         $disabled = ' disabled="disabled"';
                   3601:     }
1.591     raeburn  3602:     if (defined($in{'curr_authtype'})) {
                   3603:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3604:             if ($can_assign{'int'}) {
1.772     bisitz   3605:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3606:                 if (defined($in{'mode'})) {
                   3607:                     if ($in{'mode'} eq 'modifyuser') {
                   3608:                         $intcheck = '';
                   3609:                     }
                   3610:                 }
1.591     raeburn  3611:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3612:                     $intarg = $in{'curr_autharg'};
                   3613:                 }
                   3614:             } else {
                   3615:                 $result = &mt('Currently internally authenticated.');
                   3616:                 return $result;
1.165     raeburn  3617:             }
                   3618:         }
1.586     raeburn  3619:     } else {
                   3620:         if ($authnum == 1) {
1.784     bisitz   3621:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3622:         }
                   3623:     }
                   3624:     if (!$can_assign{'int'}) {
                   3625:         return;
1.587     raeburn  3626:     } elsif ($authtype eq '') {
1.591     raeburn  3627:         if (defined($in{'mode'})) {
1.587     raeburn  3628:             if ($in{'mode'} eq 'modifycourse') {
                   3629:                 if ($authnum == 1) {
1.1259    raeburn  3630:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3631:                 }
                   3632:             }
                   3633:         }
1.165     raeburn  3634:     }
1.586     raeburn  3635:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3636:     if ($authtype eq '') {
                   3637:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3638:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3639:     }
1.605     bisitz   3640:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3641:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3642:     $result = &mt
1.144     matthew  3643:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3644:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3645:     $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  3646:     return $result;
                   3647: }
                   3648: 
1.1104    raeburn  3649: sub authform_local {
1.32      matthew  3650:     my %in = (
                   3651:               formname => 'document.cu',
                   3652:               kerb_def_dom => 'MSU.EDU',
                   3653:               @_,
                   3654:               );
1.1259    raeburn  3655:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3656:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3657:     if ($in{'readonly'}) {
                   3658:         $disabled = ' disabled="disabled"';
                   3659:     } 
1.591     raeburn  3660:     if (defined($in{'curr_authtype'})) {
                   3661:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3662:             if ($can_assign{'loc'}) {
1.772     bisitz   3663:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3664:                 if (defined($in{'mode'})) {
                   3665:                     if ($in{'mode'} eq 'modifyuser') {
                   3666:                         $loccheck = '';
                   3667:                     }
                   3668:                 }
1.591     raeburn  3669:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3670:                     $locarg = $in{'curr_autharg'};
                   3671:                 }
                   3672:             } else {
                   3673:                 $result = &mt('Currently using local (institutional) authentication.');
                   3674:                 return $result;
1.165     raeburn  3675:             }
                   3676:         }
1.586     raeburn  3677:     } else {
                   3678:         if ($authnum == 1) {
1.784     bisitz   3679:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3680:         }
                   3681:     }
                   3682:     if (!$can_assign{'loc'}) {
                   3683:         return;
1.587     raeburn  3684:     } elsif ($authtype eq '') {
1.591     raeburn  3685:         if (defined($in{'mode'})) {
1.587     raeburn  3686:             if ($in{'mode'} eq 'modifycourse') {
                   3687:                 if ($authnum == 1) {
1.1259    raeburn  3688:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3689:                 }
                   3690:             }
                   3691:         }
1.165     raeburn  3692:     }
1.586     raeburn  3693:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3694:     if ($authtype eq '') {
                   3695:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3696:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3697:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3698:     }
                   3699:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3700:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3701:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3702:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3703:     return $result;
                   3704: }
                   3705: 
1.1106    raeburn  3706: sub authform_filesystem {
1.32      matthew  3707:     my %in = (
                   3708:               formname => 'document.cu',
                   3709:               kerb_def_dom => 'MSU.EDU',
                   3710:               @_,
                   3711:               );
1.1259    raeburn  3712:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3713:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3714:     if ($in{'readonly'}) {
                   3715:         $disabled = ' disabled="disabled"';
                   3716:     }
1.591     raeburn  3717:     if (defined($in{'curr_authtype'})) {
                   3718:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3719:             if ($can_assign{'fsys'}) {
1.772     bisitz   3720:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3721:                 if (defined($in{'mode'})) {
                   3722:                     if ($in{'mode'} eq 'modifyuser') {
                   3723:                         $fsyscheck = '';
                   3724:                     }
                   3725:                 }
1.586     raeburn  3726:             } else {
                   3727:                 $result = &mt('Currently Filesystem Authenticated.');
                   3728:                 return $result;
1.1259    raeburn  3729:             }
1.586     raeburn  3730:         }
                   3731:     } else {
                   3732:         if ($authnum == 1) {
1.784     bisitz   3733:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3734:         }
                   3735:     }
                   3736:     if (!$can_assign{'fsys'}) {
                   3737:         return;
1.587     raeburn  3738:     } elsif ($authtype eq '') {
1.591     raeburn  3739:         if (defined($in{'mode'})) {
1.587     raeburn  3740:             if ($in{'mode'} eq 'modifycourse') {
                   3741:                 if ($authnum == 1) {
1.1259    raeburn  3742:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3743:                 }
                   3744:             }
                   3745:         }
1.586     raeburn  3746:     }
                   3747:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3748:     if ($authtype eq '') {
                   3749:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3750:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3751:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3752:     }
1.1310    raeburn  3753:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3754:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3755:     $result = &mt
1.144     matthew  3756:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3757:          '<label>'.$authtype,'</label>'.$autharg);
                   3758:     return $result;
                   3759: }
                   3760: 
                   3761: sub authform_lti {
                   3762:     my %in = (
                   3763:               formname => 'document.cu',
                   3764:               kerb_def_dom => 'MSU.EDU',
                   3765:               @_,
                   3766:               );
                   3767:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3768:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3769:     if ($in{'readonly'}) {
                   3770:         $disabled = ' disabled="disabled"';
                   3771:     }
                   3772:     if (defined($in{'curr_authtype'})) {
                   3773:         if ($in{'curr_authtype'} eq 'lti') {
                   3774:             if ($can_assign{'lti'}) {
                   3775:                 $lticheck = 'checked="checked" ';
                   3776:                 if (defined($in{'mode'})) {
                   3777:                     if ($in{'mode'} eq 'modifyuser') {
                   3778:                         $lticheck = '';
                   3779:                     }
                   3780:                 }
                   3781:             } else {
                   3782:                 $result = &mt('Currently LTI Authenticated.');
                   3783:                 return $result;
                   3784:             }
                   3785:         }
                   3786:     } else {
                   3787:         if ($authnum == 1) {
                   3788:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3789:         }
                   3790:     }
                   3791:     if (!$can_assign{'lti'}) {
                   3792:         return;
                   3793:     } elsif ($authtype eq '') {
                   3794:         if (defined($in{'mode'})) {
                   3795:             if ($in{'mode'} eq 'modifycourse') {
                   3796:                 if ($authnum == 1) {
                   3797:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3798:                 }
                   3799:             }
                   3800:         }
                   3801:     }
                   3802:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3803:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3804:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3805:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3806:                     $jscall.'"'.$disabled.' />';
                   3807:     }
                   3808:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3809:     if ($authtype) {
                   3810:         $result = &mt('[_1] LTI Authenticated',
                   3811:                       '<label>'.$authtype.'</label>'.$autharg);
                   3812:     } else {
                   3813:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3814:                   $autharg;
                   3815:     }
1.32      matthew  3816:     return $result;
                   3817: }
                   3818: 
1.586     raeburn  3819: sub get_assignable_auth {
                   3820:     my ($dom) = @_;
                   3821:     if ($dom eq '') {
                   3822:         $dom = $env{'request.role.domain'};
                   3823:     }
                   3824:     my %can_assign = (
                   3825:                           krb4 => 1,
                   3826:                           krb5 => 1,
                   3827:                           int  => 1,
                   3828:                           loc  => 1,
1.1310    raeburn  3829:                           lti  => 1,
1.586     raeburn  3830:                      );
                   3831:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3832:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3833:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3834:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3835:             my $context;
                   3836:             if ($env{'request.role'} =~ /^au/) {
                   3837:                 $context = 'author';
1.1259    raeburn  3838:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3839:                 $context = 'domain';
                   3840:             } elsif ($env{'request.course.id'}) {
                   3841:                 $context = 'course';
                   3842:             }
                   3843:             if ($context) {
                   3844:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3845:                    %can_assign = %{$authhash->{$context}}; 
                   3846:                 }
                   3847:             }
                   3848:         }
                   3849:     }
                   3850:     my $authnum = 0;
                   3851:     foreach my $key (keys(%can_assign)) {
                   3852:         if ($can_assign{$key}) {
                   3853:             $authnum ++;
                   3854:         }
                   3855:     }
                   3856:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3857:         $authnum --;
                   3858:     }
                   3859:     return ($authnum,%can_assign);
                   3860: }
                   3861: 
1.1331    raeburn  3862: sub check_passwd_rules {
                   3863:     my ($domain,$plainpass) = @_;
                   3864:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3865:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3866:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3867:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3868:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3869:             if ($passwdconf{'min'} > $min) {
                   3870:                 $min = $passwdconf{'min'};
                   3871:             }
1.1331    raeburn  3872:         }
                   3873:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3874:             $max = $passwdconf{'max'};
                   3875:         }
                   3876:         @chars = @{$passwdconf{'chars'}};
                   3877:     }
                   3878:     if (($min) && (length($plainpass) < $min)) {
                   3879:         push(@brokerule,'min');
                   3880:     }
                   3881:     if (($max) && (length($plainpass) > $max)) {
                   3882:         push(@brokerule,'max');
                   3883:     }
                   3884:     if (@chars) {
                   3885:         my %rules;
                   3886:         map { $rules{$_} = 1; } @chars;
                   3887:         if ($rules{'uc'}) {
                   3888:             unless ($plainpass =~ /[A-Z]/) {
                   3889:                 push(@brokerule,'uc');
                   3890:             }
                   3891:         }
                   3892:         if ($rules{'lc'}) {
1.1332    raeburn  3893:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3894:                 push(@brokerule,'lc');
                   3895:             }
                   3896:         }
                   3897:         if ($rules{'num'}) {
                   3898:             unless ($plainpass =~ /\d/) {
                   3899:                 push(@brokerule,'num');
                   3900:             }
                   3901:         }
                   3902:         if ($rules{'spec'}) {
                   3903:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3904:                 push(@brokerule,'spec');
                   3905:             }
                   3906:         }
                   3907:     }
                   3908:     if (@brokerule) {
                   3909:         my %rulenames = &Apache::lonlocal::texthash(
                   3910:             uc   => 'At least one upper case letter',
                   3911:             lc   => 'At least one lower case letter',
                   3912:             num  => 'At least one number',
                   3913:             spec => 'At least one non-alphanumeric',
                   3914:         );
                   3915:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3916:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3917:         $rulenames{'num'} .= ': 0123456789';
                   3918:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3919:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3920:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3921:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3922:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3923:             if (grep(/^$rule$/,@brokerule)) {
                   3924:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3925:             }
                   3926:         }
                   3927:         $warning .= '</ul>';
                   3928:     }
1.1332    raeburn  3929:     if (wantarray) {
                   3930:         return @brokerule;
                   3931:     }
1.1331    raeburn  3932:     return $warning;
                   3933: }
                   3934: 
1.1376    raeburn  3935: sub passwd_validation_js {
1.1377    raeburn  3936:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3937:     my (%passwdconf,$alertmsg);
                   3938:     if ($context eq 'linkprot') {
                   3939:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3940:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3941:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3942:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3943:             }
                   3944:         }
                   3945:         if ($id eq 'add') {
                   3946:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3947:         } elsif ($id =~ /^\d+$/) {
                   3948:             my $pos = $id+1;
                   3949:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3950:         } else {
                   3951:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3952:         }
1.1434    raeburn  3953:     } elsif ($context eq 'ltitools') {
                   3954:         my %domconfig = &Apache::lonnet::get_dom('configuration',['toolsec'],$domain);
                   3955:         if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   3956:             if (ref($domconfig{'toolsec'}{'rules'}) eq 'HASH') {
                   3957:                 %passwdconf = %{$domconfig{'toolsec'}{'rules'}};
                   3958:             }
                   3959:         }
                   3960:         if ($id eq 'add') {
                   3961:             $alertmsg = &mt('Secret for added external tool did not satisfy requirement(s):').'\n\n';
                   3962:         } elsif ($id =~ /^\d+$/) {
                   3963:             my $pos = $id+1;
                   3964:             $alertmsg = &mt('Secret for external tool [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3965:         } else {
                   3966:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3967:         }
1.1377    raeburn  3968:     } else {
                   3969:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3970:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3971:     }
1.1376    raeburn  3972:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3973:     $numrules = 0;
                   3974:     $min = $Apache::lonnet::passwdmin;
                   3975:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3976:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3977:             if ($passwdconf{'min'} > $min) {
                   3978:                 $min = $passwdconf{'min'};
                   3979:             }
                   3980:         }
                   3981:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3982:             $max = $passwdconf{'max'};
                   3983:             $numrules ++;
                   3984:         }
                   3985:         @chars = @{$passwdconf{'chars'}};
                   3986:         if (@chars) {
                   3987:             $numrules ++;
                   3988:         }
                   3989:     }
                   3990:     if ($min > 0) {
                   3991:         $numrules ++;
                   3992:     }
                   3993:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3994:         if ($min) {
                   3995:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3996:         }
                   3997:         if ($max) {
                   3998:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3999:         }
                   4000:         my (@charalerts,@charrules);
                   4001:         if (@chars) {
                   4002:             if (grep(/^uc$/,@chars)) {
                   4003:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   4004:                 push(@charrules,'uc');
                   4005:             }
                   4006:             if (grep(/^lc$/,@chars)) {
                   4007:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   4008:                 push(@charrules,'lc');
                   4009:             }
                   4010:             if (grep(/^num$/,@chars)) {
                   4011:                 push(@charalerts,&mt('contain at least one number'));
                   4012:                 push(@charrules,'num');
                   4013:             }
                   4014:             if (grep(/^spec$/,@chars)) {
                   4015:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   4016:                 push(@charrules,'spec');
                   4017:             }
                   4018:         }
                   4019:         $intargjs = qq|            var rulesmsg = '';\n|.
                   4020:                     qq|            var currpwval = $currpasswdval;\n|;
                   4021:             if ($min) {
                   4022:                 $intargjs .= qq|
                   4023:             if (currpwval.length < $min) {
                   4024:                 rulesmsg += ' - $alert{min}';
                   4025:             }
                   4026: |;
                   4027:             }
                   4028:             if ($max) {
                   4029:                 $intargjs .= qq|
                   4030:             if (currpwval.length > $max) {
                   4031:                 rulesmsg += ' - $alert{max}';
                   4032:             }
                   4033: |;
                   4034:             }
                   4035:             if (@chars > 0) {
                   4036:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   4037:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   4038:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   4039:                              qq|            var charrules = new Array($charrulestr);\n|.
                   4040:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   4041:                 my %rules;
                   4042:                 map { $rules{$_} = 1; } @chars;
                   4043:                 if ($rules{'uc'}) {
                   4044:                     $intargjs .= qq|
                   4045:             var ucRegExp = /[A-Z]/;
                   4046:             if (!ucRegExp.test(currpwval)) {
                   4047:                 brokerules.push('uc');
                   4048:             }
                   4049: |;
                   4050:                 }
                   4051:                 if ($rules{'lc'}) {
                   4052:                     $intargjs .= qq|
                   4053:             var lcRegExp = /[a-z]/;
                   4054:             if (!lcRegExp.test(currpwval)) {
                   4055:                 brokerules.push('lc');
                   4056:             }
                   4057: |;
                   4058:                 }
                   4059:                 if ($rules{'num'}) {
                   4060:                      $intargjs .= qq|
                   4061:             var numRegExp = /[0-9]/;
                   4062:             if (!numRegExp.test(currpwval)) {
                   4063:                 brokerules.push('num');
                   4064:             }
                   4065: |;
                   4066:                 }
                   4067:                 if ($rules{'spec'}) {
                   4068:                      $intargjs .= q|
                   4069:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   4070:             if (!specRegExp.test(currpwval)) {
                   4071:                 brokerules.push('spec');
                   4072:             }
                   4073: |;
                   4074:                 }
                   4075:                 $intargjs .= qq|
                   4076:             if (brokerules.length > 0) {
                   4077:                 for (var i=0; i<brokerules.length; i++) {
                   4078:                     for (var j=0; j<charrules.length; j++) {
                   4079:                         if (brokerules[i] == charrules[j]) {
                   4080:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4081:                             break;
                   4082:                         }
                   4083:                     }
                   4084:                 }
                   4085:             }
                   4086: |;
                   4087:             }
                   4088:             $intargjs .= qq|
                   4089:             if (rulesmsg != '') {
                   4090:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4091:                 alert(rulesmsg);
                   4092:                 return false;
                   4093:             }
                   4094: |;
                   4095:     }
                   4096:     return ($numrules,$intargjs);
                   4097: }
                   4098: 
1.80      albertel 4099: ###############################################################
                   4100: ##    Get Kerberos Defaults for Domain                 ##
                   4101: ###############################################################
                   4102: ##
                   4103: ## Returns default kerberos version and an associated argument
                   4104: ## as listed in file domain.tab. If not listed, provides
                   4105: ## appropriate default domain and kerberos version.
                   4106: ##
                   4107: #-------------------------------------------
                   4108: 
                   4109: =pod
                   4110: 
1.648     raeburn  4111: =item * &get_kerberos_defaults()
1.80      albertel 4112: 
                   4113: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4114: version and domain. If not found, it defaults to version 4 and the 
                   4115: domain of the server.
1.80      albertel 4116: 
1.648     raeburn  4117: =over 4
                   4118: 
1.80      albertel 4119: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4120: 
1.648     raeburn  4121: =back
                   4122: 
                   4123: =back
                   4124: 
1.80      albertel 4125: =cut
                   4126: 
                   4127: #-------------------------------------------
                   4128: sub get_kerberos_defaults {
                   4129:     my $domain=shift;
1.641     raeburn  4130:     my ($krbdef,$krbdefdom);
                   4131:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4132:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4133:         $krbdef = $domdefaults{'auth_def'};
                   4134:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4135:     } else {
1.80      albertel 4136:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4137:         my $krbdefdom=$1;
                   4138:         $krbdefdom=~tr/a-z/A-Z/;
                   4139:         $krbdef = "krb4";
                   4140:     }
                   4141:     return ($krbdef,$krbdefdom);
                   4142: }
1.112     bowersj2 4143: 
1.32      matthew  4144: 
1.46      matthew  4145: ###############################################################
                   4146: ##                Thesaurus Functions                        ##
                   4147: ###############################################################
1.20      www      4148: 
1.46      matthew  4149: =pod
1.20      www      4150: 
1.112     bowersj2 4151: =head1 Thesaurus Functions
                   4152: 
                   4153: =over 4
                   4154: 
1.648     raeburn  4155: =item * &initialize_keywords()
1.46      matthew  4156: 
                   4157: Initializes the package variable %Keywords if it is empty.  Uses the
                   4158: package variable $thesaurus_db_file.
                   4159: 
                   4160: =cut
                   4161: 
                   4162: ###################################################
                   4163: 
                   4164: sub initialize_keywords {
                   4165:     return 1 if (scalar keys(%Keywords));
                   4166:     # If we are here, %Keywords is empty, so fill it up
                   4167:     #   Make sure the file we need exists...
                   4168:     if (! -e $thesaurus_db_file) {
                   4169:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4170:                                  " failed because it does not exist");
                   4171:         return 0;
                   4172:     }
                   4173:     #   Set up the hash as a database
                   4174:     my %thesaurus_db;
                   4175:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4176:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4177:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4178:                                  $thesaurus_db_file);
                   4179:         return 0;
                   4180:     } 
                   4181:     #  Get the average number of appearances of a word.
                   4182:     my $avecount = $thesaurus_db{'average.count'};
                   4183:     #  Put keywords (those that appear > average) into %Keywords
                   4184:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4185:         my ($count,undef) = split /:/,$data;
                   4186:         $Keywords{$word}++ if ($count > $avecount);
                   4187:     }
                   4188:     untie %thesaurus_db;
                   4189:     # Remove special values from %Keywords.
1.356     albertel 4190:     foreach my $value ('total.count','average.count') {
                   4191:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4192:   }
1.46      matthew  4193:     return 1;
                   4194: }
                   4195: 
                   4196: ###################################################
                   4197: 
                   4198: =pod
                   4199: 
1.648     raeburn  4200: =item * &keyword($word)
1.46      matthew  4201: 
                   4202: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4203: than the average number of times in the thesaurus database.  Calls 
                   4204: &initialize_keywords
                   4205: 
                   4206: =cut
                   4207: 
                   4208: ###################################################
1.20      www      4209: 
                   4210: sub keyword {
1.46      matthew  4211:     return if (!&initialize_keywords());
                   4212:     my $word=lc(shift());
                   4213:     $word=~s/\W//g;
                   4214:     return exists($Keywords{$word});
1.20      www      4215: }
1.46      matthew  4216: 
                   4217: ###############################################################
                   4218: 
                   4219: =pod 
1.20      www      4220: 
1.648     raeburn  4221: =item * &get_related_words()
1.46      matthew  4222: 
1.160     matthew  4223: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4224: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4225: will be returned.  The order of the words returned is determined by the
                   4226: database which holds them.
                   4227: 
                   4228: Uses global $thesaurus_db_file.
                   4229: 
1.1057    foxr     4230: 
1.46      matthew  4231: =cut
                   4232: 
                   4233: ###############################################################
                   4234: sub get_related_words {
                   4235:     my $keyword = shift;
                   4236:     my %thesaurus_db;
                   4237:     if (! -e $thesaurus_db_file) {
                   4238:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4239:                                  "failed because the file does not exist");
                   4240:         return ();
                   4241:     }
                   4242:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4243:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4244:         return ();
                   4245:     } 
                   4246:     my @Words=();
1.429     www      4247:     my $count=0;
1.46      matthew  4248:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4249: 	# The first element is the number of times
                   4250: 	# the word appears.  We do not need it now.
1.429     www      4251: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4252: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4253: 	my $threshold=$mostfrequentcount/10;
                   4254:         foreach my $possibleword (@RelatedWords) {
                   4255:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4256:             if ($wordcount>$threshold) {
                   4257: 		push(@Words,$word);
                   4258:                 $count++;
                   4259:                 if ($count>10) { last; }
                   4260: 	    }
1.20      www      4261:         }
                   4262:     }
1.46      matthew  4263:     untie %thesaurus_db;
                   4264:     return @Words;
1.14      harris41 4265: }
1.1090    foxr     4266: ###############################################################
                   4267: #
                   4268: #  Spell checking
                   4269: #
                   4270: 
                   4271: =pod
                   4272: 
1.1142    raeburn  4273: =back
                   4274: 
1.1090    foxr     4275: =head1 Spell checking
                   4276: 
                   4277: =over 4
                   4278: 
                   4279: =item * &check_spelling($wordlist $language)
                   4280: 
                   4281: Takes a string containing words and feeds it to an external
                   4282: spellcheck program via a pipeline. Returns a string containing
                   4283: them mis-spelled words.
                   4284: 
                   4285: Parameters:
                   4286: 
                   4287: =over 4
                   4288: 
                   4289: =item - $wordlist
                   4290: 
                   4291: String that will be fed into the spellcheck program.
                   4292: 
                   4293: =item - $language
                   4294: 
                   4295: Language string that specifies the language for which the spell
                   4296: check will be performed.
                   4297: 
                   4298: =back
                   4299: 
                   4300: =back
                   4301: 
                   4302: Note: This sub assumes that aspell is installed.
                   4303: 
                   4304: 
                   4305: =cut
                   4306: 
1.46      matthew  4307: 
1.1090    foxr     4308: sub check_spelling {
                   4309:     my ($wordlist, $language) = @_;
1.1091    foxr     4310:     my @misspellings;
                   4311:     
                   4312:     # Generate the speller and set the langauge.
                   4313:     # if explicitly selected:
1.1090    foxr     4314: 
1.1091    foxr     4315:     my $speller = Text::Aspell->new;
1.1090    foxr     4316:     if ($language) {
1.1091    foxr     4317: 	$speller->set_option('lang', $language);
1.1090    foxr     4318:     }
                   4319: 
1.1091    foxr     4320:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4321: 
1.1091    foxr     4322:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4323: 
1.1091    foxr     4324:     foreach my $word (@words) {
                   4325: 	if(! $speller->check($word)) {
                   4326: 	    push(@misspellings, $word);
1.1090    foxr     4327: 	}
                   4328:     }
1.1091    foxr     4329:     return join(' ', @misspellings);
                   4330:     
1.1090    foxr     4331: }
                   4332: 
1.61      www      4333: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4334: =pod
                   4335: 
1.112     bowersj2 4336: =head1 User Name Functions
                   4337: 
                   4338: =over 4
                   4339: 
1.648     raeburn  4340: =item * &plainname($uname,$udom,$first)
1.81      albertel 4341: 
1.112     bowersj2 4342: Takes a users logon name and returns it as a string in
1.226     albertel 4343: "first middle last generation" form 
                   4344: if $first is set to 'lastname' then it returns it as
                   4345: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4346: 
                   4347: =cut
1.61      www      4348: 
1.295     www      4349: 
1.81      albertel 4350: ###############################################################
1.61      www      4351: sub plainname {
1.226     albertel 4352:     my ($uname,$udom,$first)=@_;
1.537     albertel 4353:     return if (!defined($uname) || !defined($udom));
1.295     www      4354:     my %names=&getnames($uname,$udom);
1.226     albertel 4355:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4356: 					  $names{'middlename'},
                   4357: 					  $names{'lastname'},
                   4358: 					  $names{'generation'},$first);
                   4359:     $name=~s/^\s+//;
1.62      www      4360:     $name=~s/\s+$//;
                   4361:     $name=~s/\s+/ /g;
1.353     albertel 4362:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4363:     return $name;
1.61      www      4364: }
1.66      www      4365: 
                   4366: # -------------------------------------------------------------------- Nickname
1.81      albertel 4367: =pod
                   4368: 
1.648     raeburn  4369: =item * &nickname($uname,$udom)
1.81      albertel 4370: 
                   4371: Gets a users name and returns it as a string as
                   4372: 
                   4373: "&quot;nickname&quot;"
1.66      www      4374: 
1.81      albertel 4375: if the user has a nickname or
                   4376: 
                   4377: "first middle last generation"
                   4378: 
                   4379: if the user does not
                   4380: 
                   4381: =cut
1.66      www      4382: 
                   4383: sub nickname {
                   4384:     my ($uname,$udom)=@_;
1.537     albertel 4385:     return if (!defined($uname) || !defined($udom));
1.295     www      4386:     my %names=&getnames($uname,$udom);
1.68      albertel 4387:     my $name=$names{'nickname'};
1.66      www      4388:     if ($name) {
                   4389:        $name='&quot;'.$name.'&quot;'; 
                   4390:     } else {
                   4391:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4392: 	     $names{'lastname'}.' '.$names{'generation'};
                   4393:        $name=~s/\s+$//;
                   4394:        $name=~s/\s+/ /g;
                   4395:     }
                   4396:     return $name;
                   4397: }
                   4398: 
1.295     www      4399: sub getnames {
                   4400:     my ($uname,$udom)=@_;
1.537     albertel 4401:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4402:     if ($udom eq 'public' && $uname eq 'public') {
                   4403: 	return ('lastname' => &mt('Public'));
                   4404:     }
1.295     www      4405:     my $id=$uname.':'.$udom;
                   4406:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4407:     if ($cached) {
                   4408: 	return %{$names};
                   4409:     } else {
                   4410: 	my %loadnames=&Apache::lonnet::get('environment',
                   4411:                     ['firstname','middlename','lastname','generation','nickname'],
                   4412: 					 $udom,$uname);
                   4413: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4414: 	return %loadnames;
                   4415:     }
                   4416: }
1.61      www      4417: 
1.542     raeburn  4418: # -------------------------------------------------------------------- getemails
1.648     raeburn  4419: 
1.542     raeburn  4420: =pod
                   4421: 
1.648     raeburn  4422: =item * &getemails($uname,$udom)
1.542     raeburn  4423: 
                   4424: Gets a user's email information and returns it as a hash with keys:
                   4425: notification, critnotification, permanentemail
                   4426: 
                   4427: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4428: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4429:  
1.648     raeburn  4430: 
1.542     raeburn  4431: =cut
                   4432: 
1.648     raeburn  4433: 
1.466     albertel 4434: sub getemails {
                   4435:     my ($uname,$udom)=@_;
                   4436:     if ($udom eq 'public' && $uname eq 'public') {
                   4437: 	return;
                   4438:     }
1.467     www      4439:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4440:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4441:     my $id=$uname.':'.$udom;
                   4442:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4443:     if ($cached) {
                   4444: 	return %{$names};
                   4445:     } else {
                   4446: 	my %loadnames=&Apache::lonnet::get('environment',
                   4447:                     			   ['notification','critnotification',
                   4448: 					    'permanentemail'],
                   4449: 					   $udom,$uname);
                   4450: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4451: 	return %loadnames;
                   4452:     }
                   4453: }
                   4454: 
1.551     albertel 4455: sub flush_email_cache {
                   4456:     my ($uname,$udom)=@_;
                   4457:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4458:     if (!$uname) { $uname=$env{'user.name'};   }
                   4459:     return if ($udom eq 'public' && $uname eq 'public');
                   4460:     my $id=$uname.':'.$udom;
                   4461:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4462: }
                   4463: 
1.728     raeburn  4464: # -------------------------------------------------------------------- getlangs
                   4465: 
                   4466: =pod
                   4467: 
                   4468: =item * &getlangs($uname,$udom)
                   4469: 
                   4470: Gets a user's language preference and returns it as a hash with key:
                   4471: language.
                   4472: 
                   4473: =cut
                   4474: 
                   4475: 
                   4476: sub getlangs {
                   4477:     my ($uname,$udom) = @_;
                   4478:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4479:     if (!$uname) { $uname=$env{'user.name'};   }
                   4480:     my $id=$uname.':'.$udom;
                   4481:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4482:     if ($cached) {
                   4483:         return %{$langs};
                   4484:     } else {
                   4485:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4486:                                            $udom,$uname);
                   4487:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4488:         return %loadlangs;
                   4489:     }
                   4490: }
                   4491: 
                   4492: sub flush_langs_cache {
                   4493:     my ($uname,$udom)=@_;
                   4494:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4495:     if (!$uname) { $uname=$env{'user.name'};   }
                   4496:     return if ($udom eq 'public' && $uname eq 'public');
                   4497:     my $id=$uname.':'.$udom;
                   4498:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4499: }
                   4500: 
1.61      www      4501: # ------------------------------------------------------------------ Screenname
1.81      albertel 4502: 
                   4503: =pod
                   4504: 
1.648     raeburn  4505: =item * &screenname($uname,$udom)
1.81      albertel 4506: 
                   4507: Gets a users screenname and returns it as a string
                   4508: 
                   4509: =cut
1.61      www      4510: 
                   4511: sub screenname {
                   4512:     my ($uname,$udom)=@_;
1.258     albertel 4513:     if ($uname eq $env{'user.name'} &&
                   4514: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4515:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4516:     return $names{'screenname'};
1.62      www      4517: }
                   4518: 
1.212     albertel 4519: 
1.802     bisitz   4520: # ------------------------------------------------------------- Confirm Wrapper
                   4521: =pod
                   4522: 
1.1142    raeburn  4523: =item * &confirmwrapper($message)
1.802     bisitz   4524: 
                   4525: Wrap messages about completion of operation in box
                   4526: 
                   4527: =cut
                   4528: 
                   4529: sub confirmwrapper {
                   4530:     my ($message)=@_;
                   4531:     if ($message) {
                   4532:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4533:                .$message."\n"
                   4534:                .'</div>'."\n";
                   4535:     } else {
                   4536:         return $message;
                   4537:     }
                   4538: }
                   4539: 
1.62      www      4540: # ------------------------------------------------------------- Message Wrapper
                   4541: 
                   4542: sub messagewrapper {
1.369     www      4543:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4544:     return 
1.441     albertel 4545:         '<a href="/adm/email?compose=individual&amp;'.
                   4546:         'recname='.$username.'&amp;recdom='.$domain.
                   4547: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4548:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4549: }
1.802     bisitz   4550: 
1.74      www      4551: # --------------------------------------------------------------- Notes Wrapper
                   4552: 
                   4553: sub noteswrapper {
                   4554:     my ($link,$un,$do)=@_;
                   4555:     return 
1.896     amueller 4556: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4557: }
1.802     bisitz   4558: 
1.62      www      4559: # ------------------------------------------------------------- Aboutme Wrapper
                   4560: 
                   4561: sub aboutmewrapper {
1.1070    raeburn  4562:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4563:     if (!defined($username)  && !defined($domain)) {
                   4564:         return;
                   4565:     }
1.1096    raeburn  4566:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4567: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4568: }
                   4569: 
                   4570: # ------------------------------------------------------------ Syllabus Wrapper
                   4571: 
                   4572: sub syllabuswrapper {
1.707     bisitz   4573:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4574:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4575: }
1.14      harris41 4576: 
1.1397    raeburn  4577: # -----------------------------------------------------------------------------
                   4578: 
1.1396    raeburn  4579: sub aboutme_on {
                   4580:     my ($uname,$udom)=@_;
                   4581:     unless ($uname) { $uname=$env{'user.name'}; }
                   4582:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4583:     return if ($udom eq 'public' && $uname eq 'public');
                   4584:     my $hashkey=$uname.':'.$udom;
                   4585:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4586:     if ($cached) {
                   4587:         return $aboutme;
                   4588:     }
                   4589:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4590:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4591:     return $aboutme;
                   4592: }
                   4593: 
                   4594: sub devalidate_aboutme_cache {
                   4595:     my ($uname,$udom)=@_;
                   4596:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4597:     if (!$uname) { $uname=$env{'user.name'};   }
                   4598:     return if ($udom eq 'public' && $uname eq 'public');
                   4599:     my $id=$uname.':'.$udom;
                   4600:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4601: }
                   4602: 
1.208     matthew  4603: sub track_student_link {
1.887     raeburn  4604:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4605:     my $link ="/adm/trackstudent?";
1.208     matthew  4606:     my $title = 'View recent activity';
                   4607:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4608:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4609:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4610:         $title .= ' of this student';
1.268     albertel 4611:     } 
1.208     matthew  4612:     if (defined($target) && $target !~ /^\s*$/) {
                   4613:         $target = qq{target="$target"};
                   4614:     } else {
                   4615:         $target = '';
                   4616:     }
1.268     albertel 4617:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4618:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4619:     $title = &mt($title);
                   4620:     $linktext = &mt($linktext);
1.448     albertel 4621:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4622: 	&help_open_topic('View_recent_activity');
1.208     matthew  4623: }
                   4624: 
1.781     raeburn  4625: sub slot_reservations_link {
                   4626:     my ($linktext,$sname,$sdom,$target) = @_;
                   4627:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4628:     my $title = 'View slot reservation history';
                   4629:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4630:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4631:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4632:         $title .= ' of this student';
                   4633:     }
                   4634:     if (defined($target) && $target !~ /^\s*$/) {
                   4635:         $target = qq{target="$target"};
                   4636:     } else {
                   4637:         $target = '';
                   4638:     }
                   4639:     $title = &mt($title);
                   4640:     $linktext = &mt($linktext);
                   4641:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4642: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4643: 
                   4644: }
                   4645: 
1.508     www      4646: # ===================================================== Display a student photo
                   4647: 
                   4648: 
1.509     albertel 4649: sub student_image_tag {
1.508     www      4650:     my ($domain,$user)=@_;
                   4651:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4652:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4653: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4654:     } else {
                   4655: 	return '';
                   4656:     }
                   4657: }
                   4658: 
1.112     bowersj2 4659: =pod
                   4660: 
                   4661: =back
                   4662: 
                   4663: =head1 Access .tab File Data
                   4664: 
                   4665: =over 4
                   4666: 
1.648     raeburn  4667: =item * &languageids() 
1.112     bowersj2 4668: 
                   4669: returns list of all language ids
                   4670: 
                   4671: =cut
                   4672: 
1.14      harris41 4673: sub languageids {
1.16      harris41 4674:     return sort(keys(%language));
1.14      harris41 4675: }
                   4676: 
1.112     bowersj2 4677: =pod
                   4678: 
1.648     raeburn  4679: =item * &languagedescription() 
1.112     bowersj2 4680: 
                   4681: returns description of a specified language id
                   4682: 
                   4683: =cut
                   4684: 
1.14      harris41 4685: sub languagedescription {
1.125     www      4686:     my $code=shift;
                   4687:     return  ($supported_language{$code}?'* ':'').
                   4688:             $language{$code}.
1.126     www      4689: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4690: }
                   4691: 
1.1048    foxr     4692: =pod
                   4693: 
                   4694: =item * &plainlanguagedescription
                   4695: 
                   4696: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4697: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4698: 
                   4699: =cut
                   4700: 
1.145     www      4701: sub plainlanguagedescription {
                   4702:     my $code=shift;
                   4703:     return $language{$code};
                   4704: }
                   4705: 
1.1048    foxr     4706: =pod
                   4707: 
                   4708: =item * &supportedlanguagecode
                   4709: 
                   4710: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4711: code.
                   4712: 
                   4713: =cut
                   4714: 
1.145     www      4715: sub supportedlanguagecode {
                   4716:     my $code=shift;
                   4717:     return $supported_language{$code};
1.97      www      4718: }
                   4719: 
1.112     bowersj2 4720: =pod
                   4721: 
1.1048    foxr     4722: =item * &latexlanguage()
                   4723: 
                   4724: Given a language key code returns the correspondnig language to use
                   4725: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4726: is no supported hyphenation for the language code.
                   4727: 
                   4728: =cut
                   4729: 
                   4730: sub latexlanguage {
                   4731:     my $code = shift;
                   4732:     return $latex_language{$code};
                   4733: }
                   4734: 
                   4735: =pod
                   4736: 
                   4737: =item * &latexhyphenation()
                   4738: 
                   4739: Same as above but what's supplied is the language as it might be stored
                   4740: in the metadata.
                   4741: 
                   4742: =cut
                   4743: 
                   4744: sub latexhyphenation {
                   4745:     my $key = shift;
                   4746:     return $latex_language_bykey{$key};
                   4747: }
                   4748: 
                   4749: =pod
                   4750: 
1.648     raeburn  4751: =item * &copyrightids() 
1.112     bowersj2 4752: 
                   4753: returns list of all copyrights
                   4754: 
                   4755: =cut
                   4756: 
                   4757: sub copyrightids {
                   4758:     return sort(keys(%cprtag));
                   4759: }
                   4760: 
                   4761: =pod
                   4762: 
1.648     raeburn  4763: =item * &copyrightdescription() 
1.112     bowersj2 4764: 
                   4765: returns description of a specified copyright id
                   4766: 
                   4767: =cut
                   4768: 
                   4769: sub copyrightdescription {
1.166     www      4770:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4771: }
1.197     matthew  4772: 
                   4773: =pod
                   4774: 
1.648     raeburn  4775: =item * &source_copyrightids() 
1.192     taceyjo1 4776: 
                   4777: returns list of all source copyrights
                   4778: 
                   4779: =cut
                   4780: 
                   4781: sub source_copyrightids {
                   4782:     return sort(keys(%scprtag));
                   4783: }
                   4784: 
                   4785: =pod
                   4786: 
1.648     raeburn  4787: =item * &source_copyrightdescription() 
1.192     taceyjo1 4788: 
                   4789: returns description of a specified source copyright id
                   4790: 
                   4791: =cut
                   4792: 
                   4793: sub source_copyrightdescription {
                   4794:     return &mt($scprtag{shift(@_)});
                   4795: }
1.112     bowersj2 4796: 
                   4797: =pod
                   4798: 
1.648     raeburn  4799: =item * &filecategories() 
1.112     bowersj2 4800: 
                   4801: returns list of all file categories
                   4802: 
                   4803: =cut
                   4804: 
                   4805: sub filecategories {
                   4806:     return sort(keys(%category_extensions));
                   4807: }
                   4808: 
                   4809: =pod
                   4810: 
1.648     raeburn  4811: =item * &filecategorytypes() 
1.112     bowersj2 4812: 
                   4813: returns list of file types belonging to a given file
                   4814: category
                   4815: 
                   4816: =cut
                   4817: 
                   4818: sub filecategorytypes {
1.356     albertel 4819:     my ($cat) = @_;
1.1248    raeburn  4820:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4821:         return @{$category_extensions{lc($cat)}};
                   4822:     } else {
                   4823:         return ();
                   4824:     }
1.112     bowersj2 4825: }
                   4826: 
                   4827: =pod
                   4828: 
1.648     raeburn  4829: =item * &fileembstyle() 
1.112     bowersj2 4830: 
                   4831: returns embedding style for a specified file type
                   4832: 
                   4833: =cut
                   4834: 
                   4835: sub fileembstyle {
                   4836:     return $fe{lc(shift(@_))};
1.169     www      4837: }
                   4838: 
1.351     www      4839: sub filemimetype {
                   4840:     return $fm{lc(shift(@_))};
                   4841: }
                   4842: 
1.169     www      4843: 
                   4844: sub filecategoryselect {
                   4845:     my ($name,$value)=@_;
1.189     matthew  4846:     return &select_form($value,$name,
1.970     raeburn  4847:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4848: }
                   4849: 
                   4850: =pod
                   4851: 
1.648     raeburn  4852: =item * &filedescription() 
1.112     bowersj2 4853: 
                   4854: returns description for a specified file type
                   4855: 
                   4856: =cut
                   4857: 
                   4858: sub filedescription {
1.188     matthew  4859:     my $file_description = $fd{lc(shift())};
                   4860:     $file_description =~ s:([\[\]]):~$1:g;
                   4861:     return &mt($file_description);
1.112     bowersj2 4862: }
                   4863: 
                   4864: =pod
                   4865: 
1.648     raeburn  4866: =item * &filedescriptionex() 
1.112     bowersj2 4867: 
                   4868: returns description for a specified file type with
                   4869: extra formatting
                   4870: 
                   4871: =cut
                   4872: 
                   4873: sub filedescriptionex {
                   4874:     my $ex=shift;
1.188     matthew  4875:     my $file_description = $fd{lc($ex)};
                   4876:     $file_description =~ s:([\[\]]):~$1:g;
                   4877:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4878: }
                   4879: 
                   4880: # End of .tab access
                   4881: =pod
                   4882: 
                   4883: =back
                   4884: 
                   4885: =cut
                   4886: 
                   4887: # ------------------------------------------------------------------ File Types
                   4888: sub fileextensions {
                   4889:     return sort(keys(%fe));
                   4890: }
                   4891: 
1.97      www      4892: # ----------------------------------------------------------- Display Languages
                   4893: # returns a hash with all desired display languages
                   4894: #
                   4895: 
                   4896: sub display_languages {
                   4897:     my %languages=();
1.695     raeburn  4898:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4899: 	$languages{$lang}=1;
1.97      www      4900:     }
                   4901:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4902:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4903: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4904: 	    $languages{$lang}=1;
1.97      www      4905:         }
                   4906:     }
                   4907:     return %languages;
1.14      harris41 4908: }
                   4909: 
1.582     albertel 4910: sub languages {
                   4911:     my ($possible_langs) = @_;
1.695     raeburn  4912:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4913:     if (!ref($possible_langs)) {
                   4914: 	if( wantarray ) {
                   4915: 	    return @preferred_langs;
                   4916: 	} else {
                   4917: 	    return $preferred_langs[0];
                   4918: 	}
                   4919:     }
                   4920:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4921:     my @preferred_possibilities;
                   4922:     foreach my $preferred_lang (@preferred_langs) {
                   4923: 	if (exists($possibilities{$preferred_lang})) {
                   4924: 	    push(@preferred_possibilities, $preferred_lang);
                   4925: 	}
                   4926:     }
                   4927:     if( wantarray ) {
                   4928: 	return @preferred_possibilities;
                   4929:     }
                   4930:     return $preferred_possibilities[0];
                   4931: }
                   4932: 
1.742     raeburn  4933: sub user_lang {
                   4934:     my ($touname,$toudom,$fromcid) = @_;
                   4935:     my @userlangs;
                   4936:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4937:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4938:                     $env{'course.'.$fromcid.'.languages'}));
                   4939:     } else {
                   4940:         my %langhash = &getlangs($touname,$toudom);
                   4941:         if ($langhash{'languages'} ne '') {
                   4942:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4943:         } else {
                   4944:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4945:             if ($domdefs{'lang_def'} ne '') {
                   4946:                 @userlangs = ($domdefs{'lang_def'});
                   4947:             }
                   4948:         }
                   4949:     }
                   4950:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4951:     my $user_lh = Apache::localize->get_handle(@languages);
                   4952:     return $user_lh;
                   4953: }
                   4954: 
                   4955: 
1.112     bowersj2 4956: ###############################################################
                   4957: ##               Student Answer Attempts                     ##
                   4958: ###############################################################
                   4959: 
                   4960: =pod
                   4961: 
                   4962: =head1 Alternate Problem Views
                   4963: 
                   4964: =over 4
                   4965: 
1.648     raeburn  4966: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4967:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4968: 
                   4969: Return string with previous attempt on problem. Arguments:
                   4970: 
                   4971: =over 4
                   4972: 
                   4973: =item * $symb: Problem, including path
                   4974: 
                   4975: =item * $username: username of the desired student
                   4976: 
                   4977: =item * $domain: domain of the desired student
1.14      harris41 4978: 
1.112     bowersj2 4979: =item * $course: Course ID
1.14      harris41 4980: 
1.112     bowersj2 4981: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4982:     something
1.14      harris41 4983: 
1.112     bowersj2 4984: =item * $regexp: if string matches this regexp, the string will be
                   4985:     sent to $gradesub
1.14      harris41 4986: 
1.112     bowersj2 4987: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4988: 
1.1199    raeburn  4989: =item * $usec: section of the desired student
                   4990: 
                   4991: =item * $identifier: counter for student (multiple students one problem) or 
                   4992:     problem (one student; whole sequence).
                   4993: 
1.112     bowersj2 4994: =back
1.14      harris41 4995: 
1.112     bowersj2 4996: The output string is a table containing all desired attempts, if any.
1.16      harris41 4997: 
1.112     bowersj2 4998: =cut
1.1       albertel 4999: 
                   5000: sub get_previous_attempt {
1.1199    raeburn  5001:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 5002:   my $prevattempts='';
1.43      ng       5003:   no strict 'refs';
1.1       albertel 5004:   if ($symb) {
1.3       albertel 5005:     my (%returnhash)=
                   5006:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 5007:     if ($returnhash{'version'}) {
                   5008:       my %lasthash=();
                   5009:       my $version;
                   5010:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  5011:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   5012:             if ($key =~ /\.rawrndseed$/) {
                   5013:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   5014:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   5015:             } else {
                   5016:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   5017:             }
1.19      harris41 5018:         }
1.1       albertel 5019:       }
1.596     albertel 5020:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   5021:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  5022:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  5023:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 5024:       foreach my $key (sort(keys(%lasthash))) {
                   5025: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       5026: 	if ($#parts > 0) {
1.31      albertel 5027: 	  my $data=$parts[-1];
1.989     raeburn  5028:           next if ($data eq 'foilorder');
1.31      albertel 5029: 	  pop(@parts);
1.1010    www      5030:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  5031:           if ($data eq 'type') {
                   5032:               unless ($showsurv) {
                   5033:                   my $id = join(',',@parts);
                   5034:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  5035:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   5036:                       $lasthidden{$ign.'.'.$id} = 1;
                   5037:                   }
1.945     raeburn  5038:               }
1.1199    raeburn  5039:               if ($identifier ne '') {
                   5040:                   my $id = join(',',@parts);
                   5041:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   5042:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   5043:                       $hidestatus{$ign.'.'.$id} = 1;
                   5044:                   }
                   5045:               }
                   5046:           } elsif ($data eq 'regrader') {
                   5047:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  5048:                   my $id = join(',',@parts);
                   5049:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  5050:               }
1.1010    www      5051:           } 
1.31      albertel 5052: 	} else {
1.41      ng       5053: 	  if ($#parts == 0) {
                   5054: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   5055: 	  } else {
                   5056: 	    $prevattempts.='<th>'.$ign.'</th>';
                   5057: 	  }
1.31      albertel 5058: 	}
1.16      harris41 5059:       }
1.596     albertel 5060:       $prevattempts.=&end_data_table_header_row();
1.40      ng       5061:       if ($getattempt eq '') {
1.1199    raeburn  5062:         my (%solved,%resets,%probstatus);
1.1200    raeburn  5063:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   5064:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   5065:                 foreach my $id (keys(%regraded)) {
                   5066:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   5067:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   5068:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   5069:                         push(@{$resets{$id}},$version);
1.1199    raeburn  5070:                     }
                   5071:                 }
                   5072:             }
1.1200    raeburn  5073:         }
                   5074: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  5075:             my (@hidden,@unsolved);
1.945     raeburn  5076:             if (%typeparts) {
                   5077:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5078:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5079:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5080:                         push(@hidden,$id);
1.1199    raeburn  5081:                     } elsif ($identifier ne '') {
                   5082:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5083:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5084:                                 ($hidestatus{$id})) {
1.1200    raeburn  5085:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5086:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5087:                                 push(@{$solved{$id}},$version);
                   5088:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5089:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5090:                                 my $skip;
                   5091:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5092:                                     foreach my $reset (@{$resets{$id}}) {
                   5093:                                         if ($reset > $solved{$id}[-1]) {
                   5094:                                             $skip=1;
                   5095:                                             last;
                   5096:                                         }
                   5097:                                     }
                   5098:                                 }
                   5099:                                 unless ($skip) {
                   5100:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5101:                                     push(@unsolved,$partslist);
                   5102:                                 }
                   5103:                             }
                   5104:                         }
1.945     raeburn  5105:                     }
                   5106:                 }
                   5107:             }
                   5108:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5109:                            '<td>'.&mt('Transaction [_1]',$version);
                   5110:             if (@unsolved) {
                   5111:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5112:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5113:                                  &mt('Hide').'</label></span>';
                   5114:             }
                   5115:             $prevattempts .= '</td>';
1.945     raeburn  5116:             if (@hidden) {
                   5117:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5118:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5119:                     my $hide;
                   5120:                     foreach my $id (@hidden) {
                   5121:                         if ($key =~ /^\Q$id\E/) {
                   5122:                             $hide = 1;
                   5123:                             last;
                   5124:                         }
                   5125:                     }
                   5126:                     if ($hide) {
                   5127:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5128:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5129:                             my $value = &format_previous_attempt_value($key,
                   5130:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5131:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5132:                         } else {
                   5133:                             $prevattempts.='<td>&nbsp;</td>';
                   5134:                         }
                   5135:                     } else {
                   5136:                         if ($key =~ /\./) {
1.1212    raeburn  5137:                             my $value = $returnhash{$version.':'.$key};
                   5138:                             if ($key =~ /\.rndseed$/) {
                   5139:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5140:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5141:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5142:                                 }
                   5143:                             }
                   5144:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5145:                                            '&nbsp;</td>';
1.945     raeburn  5146:                         } else {
                   5147:                             $prevattempts.='<td>&nbsp;</td>';
                   5148:                         }
                   5149:                     }
                   5150:                 }
                   5151:             } else {
                   5152: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5153:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5154:                     my $value = $returnhash{$version.':'.$key};
                   5155:                     if ($key =~ /\.rndseed$/) {
                   5156:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5157:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5158:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5159:                         }
                   5160:                     }
                   5161:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5162:                                    '&nbsp;</td>';
1.945     raeburn  5163: 	        }
                   5164:             }
                   5165: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5166: 	 }
1.1       albertel 5167:       }
1.945     raeburn  5168:       my @currhidden = keys(%lasthidden);
1.596     albertel 5169:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5170:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5171:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5172:           if (%typeparts) {
                   5173:               my $hidden;
                   5174:               foreach my $id (@currhidden) {
                   5175:                   if ($key =~ /^\Q$id\E/) {
                   5176:                       $hidden = 1;
                   5177:                       last;
                   5178:                   }
                   5179:               }
                   5180:               if ($hidden) {
                   5181:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5182:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5183:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5184:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5185:                           $value = &$gradesub($value);
                   5186:                       }
1.1173    kruse    5187:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5188:                   } else {
                   5189:                       $prevattempts.='<td>&nbsp;</td>';
                   5190:                   }
                   5191:               } else {
                   5192:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5193:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5194:                       $value = &$gradesub($value);
                   5195:                   }
1.1173    kruse    5196:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5197:               }
                   5198:           } else {
                   5199: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5200: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5201:                   $value = &$gradesub($value);
                   5202:               }
1.1173    kruse    5203: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5204:           }
1.16      harris41 5205:       }
1.596     albertel 5206:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5207:     } else {
1.1305    raeburn  5208:       my $msg;
                   5209:       if ($symb =~ /ext\.tool$/) {
                   5210:           $msg = &mt('No grade passed back.');
                   5211:       } else {
                   5212:           $msg = &mt('Nothing submitted - no attempts.');
                   5213:       }
1.596     albertel 5214:       $prevattempts=
                   5215: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5216: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5217: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5218:     }
                   5219:   } else {
1.596     albertel 5220:     $prevattempts=
                   5221: 	  &start_data_table().&start_data_table_row().
                   5222: 	  '<td>'.&mt('No data.').'</td>'.
                   5223: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5224:   }
1.10      albertel 5225: }
                   5226: 
1.581     albertel 5227: sub format_previous_attempt_value {
                   5228:     my ($key,$value) = @_;
1.1011    www      5229:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5230:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5231:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5232:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5233:     } elsif ($key =~ /answerstring$/) {
                   5234:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5235:         my @answer = %answers;
                   5236:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5237:         my @anskeys = sort(keys(%answers));
                   5238:         if (@anskeys == 1) {
                   5239:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5240:             if ($answer =~ m{\0}) {
                   5241:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5242:             }
                   5243:             my $tag_internal_answer_name = 'INTERNAL';
                   5244:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5245:                 $value = $answer; 
                   5246:             } else {
                   5247:                 $value = $anskeys[0].'='.$answer;
                   5248:             }
                   5249:         } else {
                   5250:             foreach my $ans (@anskeys) {
                   5251:                 my $answer = $answers{$ans};
1.1001    raeburn  5252:                 if ($answer =~ m{\0}) {
                   5253:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5254:                 }
                   5255:                 $value .=  $ans.'='.$answer.'<br />';;
                   5256:             } 
                   5257:         }
1.581     albertel 5258:     } else {
1.1173    kruse    5259:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5260:     }
                   5261:     return $value;
                   5262: }
                   5263: 
                   5264: 
1.107     albertel 5265: sub relative_to_absolute {
                   5266:     my ($url,$output)=@_;
                   5267:     my $parser=HTML::TokeParser->new(\$output);
                   5268:     my $token;
                   5269:     my $thisdir=$url;
                   5270:     my @rlinks=();
                   5271:     while ($token=$parser->get_token) {
                   5272: 	if ($token->[0] eq 'S') {
                   5273: 	    if ($token->[1] eq 'a') {
                   5274: 		if ($token->[2]->{'href'}) {
                   5275: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5276: 		}
                   5277: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5278: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5279: 	    } elsif ($token->[1] eq 'base') {
                   5280: 		$thisdir=$token->[2]->{'href'};
                   5281: 	    }
                   5282: 	}
                   5283:     }
                   5284:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5285:     foreach my $link (@rlinks) {
1.726     raeburn  5286: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5287: 		($link=~/^\//) ||
                   5288: 		($link=~/^javascript:/i) ||
                   5289: 		($link=~/^mailto:/i) ||
                   5290: 		($link=~/^\#/)) {
                   5291: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5292: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5293: 	}
                   5294:     }
                   5295: # -------------------------------------------------- Deal with Applet codebases
                   5296:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5297:     return $output;
                   5298: }
                   5299: 
1.112     bowersj2 5300: =pod
                   5301: 
1.648     raeburn  5302: =item * &get_student_view()
1.112     bowersj2 5303: 
                   5304: show a snapshot of what student was looking at
                   5305: 
                   5306: =cut
                   5307: 
1.10      albertel 5308: sub get_student_view {
1.186     albertel 5309:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5310:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5311:   my (%form);
1.10      albertel 5312:   my @elements=('symb','courseid','domain','username');
                   5313:   foreach my $element (@elements) {
1.186     albertel 5314:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5315:   }
1.186     albertel 5316:   if (defined($moreenv)) {
                   5317:       %form=(%form,%{$moreenv});
                   5318:   }
1.236     albertel 5319:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5320:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5321:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5322:       $feedurl =~ s{^/adm/wrapper}{};
                   5323:   }
1.650     www      5324:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5325:   $userview=~s/\<body[^\>]*\>//gi;
                   5326:   $userview=~s/\<\/body\>//gi;
                   5327:   $userview=~s/\<html\>//gi;
                   5328:   $userview=~s/\<\/html\>//gi;
                   5329:   $userview=~s/\<head\>//gi;
                   5330:   $userview=~s/\<\/head\>//gi;
                   5331:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5332:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5333:   if (wantarray) {
                   5334:      return ($userview,$response);
                   5335:   } else {
                   5336:      return $userview;
                   5337:   }
                   5338: }
                   5339: 
                   5340: sub get_student_view_with_retries {
                   5341:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5342: 
                   5343:     my $ok = 0;                 # True if we got a good response.
                   5344:     my $content;
                   5345:     my $response;
                   5346: 
                   5347:     # Try to get the student_view done. within the retries count:
                   5348:     
                   5349:     do {
                   5350:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5351:          $ok      = $response->is_success;
                   5352:          if (!$ok) {
                   5353:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5354:          }
                   5355:          $retries--;
                   5356:     } while (!$ok && ($retries > 0));
                   5357:     
                   5358:     if (!$ok) {
                   5359:        $content = '';          # On error return an empty content.
                   5360:     }
1.651     www      5361:     if (wantarray) {
                   5362:        return ($content, $response);
                   5363:     } else {
                   5364:        return $content;
                   5365:     }
1.11      albertel 5366: }
                   5367: 
1.1349    raeburn  5368: sub css_links {
                   5369:     my ($currsymb,$level) = @_;
                   5370:     my ($links,@symbs,%cssrefs,%httpref);
                   5371:     if ($level eq 'map') {
                   5372:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5373:         if (ref($navmap)) {
                   5374:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5375:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5376:             foreach my $res (@resources) {
                   5377:                 if (ref($res) && $res->symb()) {
                   5378:                     push(@symbs,$res->symb());
                   5379:                 }
                   5380:             }
                   5381:         }
                   5382:     } else {
                   5383:         @symbs = ($currsymb);
                   5384:     }
                   5385:     foreach my $symb (@symbs) {
                   5386:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5387:         if ($css_href =~ /\S/) {
                   5388:             unless ($css_href =~ m{https?://}) {
                   5389:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5390:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5391:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5392:                 unless ($css_href =~ m{^/}) {
                   5393:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5394:                 }
                   5395:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5396:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5397:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5398:                         my $thisurl = $proburl;
                   5399:                         if ($env{'httpref.'.$proburl}) {
                   5400:                             $thisurl = $env{'httpref.'.$proburl};
                   5401:                         }
                   5402:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5403:                     }
                   5404:                 }
                   5405:             }
                   5406:             $cssrefs{$css_href} = 1;
                   5407:         }
                   5408:     }
                   5409:     if (keys(%httpref)) {
                   5410:         &Apache::lonnet::appenv(\%httpref);
                   5411:     }
                   5412:     if (keys(%cssrefs)) {
                   5413:         foreach my $css_href (keys(%cssrefs)) {
                   5414:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5415:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5416:         }
                   5417:     }
                   5418:     return $links;
                   5419: }
                   5420: 
1.112     bowersj2 5421: =pod
                   5422: 
1.648     raeburn  5423: =item * &get_student_answers() 
1.112     bowersj2 5424: 
                   5425: show a snapshot of how student was answering problem
                   5426: 
                   5427: =cut
                   5428: 
1.11      albertel 5429: sub get_student_answers {
1.100     sakharuk 5430:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5431:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5432:   my (%moreenv);
1.11      albertel 5433:   my @elements=('symb','courseid','domain','username');
                   5434:   foreach my $element (@elements) {
1.186     albertel 5435:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5436:   }
1.186     albertel 5437:   $moreenv{'grade_target'}='answer';
                   5438:   %moreenv=(%form,%moreenv);
1.497     raeburn  5439:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5440:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5441:   return $userview;
1.1       albertel 5442: }
1.116     albertel 5443: 
                   5444: =pod
                   5445: 
                   5446: =item * &submlink()
                   5447: 
1.242     albertel 5448: Inputs: $text $uname $udom $symb $target
1.116     albertel 5449: 
                   5450: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5451: 
                   5452: =cut
                   5453: 
                   5454: ###############################################
                   5455: sub submlink {
1.242     albertel 5456:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5457:     if (!($uname && $udom)) {
                   5458: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5459: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5460: 	if (!$symb) { $symb=$cursymb; }
                   5461:     }
1.254     matthew  5462:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5463:     $symb=&escape($symb);
1.960     bisitz   5464:     if ($target) { $target=" target=\"$target\""; }
                   5465:     return
                   5466:         '<a href="/adm/grades?command=submission'.
                   5467:         '&amp;symb='.$symb.
                   5468:         '&amp;student='.$uname.
                   5469:         '&amp;userdom='.$udom.'"'.
                   5470:         $target.'>'.$text.'</a>';
1.242     albertel 5471: }
                   5472: ##############################################
                   5473: 
                   5474: =pod
                   5475: 
                   5476: =item * &pgrdlink()
                   5477: 
                   5478: Inputs: $text $uname $udom $symb $target
                   5479: 
                   5480: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5481: 
                   5482: =cut
                   5483: 
                   5484: ###############################################
                   5485: sub pgrdlink {
                   5486:     my $link=&submlink(@_);
                   5487:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5488:     return $link;
                   5489: }
                   5490: ##############################################
                   5491: 
                   5492: =pod
                   5493: 
                   5494: =item * &pprmlink()
                   5495: 
                   5496: Inputs: $text $uname $udom $symb $target
                   5497: 
                   5498: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5499: student and a specific resource
1.242     albertel 5500: 
                   5501: =cut
                   5502: 
                   5503: ###############################################
                   5504: sub pprmlink {
                   5505:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5506:     if (!($uname && $udom)) {
                   5507: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5508: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5509: 	if (!$symb) { $symb=$cursymb; }
                   5510:     }
1.254     matthew  5511:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5512:     $symb=&escape($symb);
1.242     albertel 5513:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5514:     return '<a href="/adm/parmset?command=set&amp;'.
                   5515: 	'symb='.$symb.'&amp;uname='.$uname.
                   5516: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5517: }
                   5518: ##############################################
1.37      matthew  5519: 
1.112     bowersj2 5520: =pod
                   5521: 
                   5522: =back
                   5523: 
                   5524: =cut
                   5525: 
1.37      matthew  5526: ###############################################
1.51      www      5527: 
                   5528: 
                   5529: sub timehash {
1.687     raeburn  5530:     my ($thistime) = @_;
                   5531:     my $timezone = &Apache::lonlocal::gettimezone();
                   5532:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5533:                      ->set_time_zone($timezone);
                   5534:     my $wday = $dt->day_of_week();
                   5535:     if ($wday == 7) { $wday = 0; }
                   5536:     return ( 'second' => $dt->second(),
                   5537:              'minute' => $dt->minute(),
                   5538:              'hour'   => $dt->hour(),
                   5539:              'day'     => $dt->day_of_month(),
                   5540:              'month'   => $dt->month(),
                   5541:              'year'    => $dt->year(),
                   5542:              'weekday' => $wday,
                   5543:              'dayyear' => $dt->day_of_year(),
                   5544:              'dlsav'   => $dt->is_dst() );
1.51      www      5545: }
                   5546: 
1.370     www      5547: sub utc_string {
                   5548:     my ($date)=@_;
1.371     www      5549:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5550: }
                   5551: 
1.51      www      5552: sub maketime {
                   5553:     my %th=@_;
1.687     raeburn  5554:     my ($epoch_time,$timezone,$dt);
                   5555:     $timezone = &Apache::lonlocal::gettimezone();
                   5556:     eval {
                   5557:         $dt = DateTime->new( year   => $th{'year'},
                   5558:                              month  => $th{'month'},
                   5559:                              day    => $th{'day'},
                   5560:                              hour   => $th{'hour'},
                   5561:                              minute => $th{'minute'},
                   5562:                              second => $th{'second'},
                   5563:                              time_zone => $timezone,
                   5564:                          );
                   5565:     };
                   5566:     if (!$@) {
                   5567:         $epoch_time = $dt->epoch;
                   5568:         if ($epoch_time) {
                   5569:             return $epoch_time;
                   5570:         }
                   5571:     }
1.51      www      5572:     return POSIX::mktime(
                   5573:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5574:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5575: }
                   5576: 
                   5577: #########################################
1.51      www      5578: 
                   5579: sub findallcourses {
1.482     raeburn  5580:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5581:     my %roles;
                   5582:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5583:     my %courses;
1.51      www      5584:     my $now=time;
1.482     raeburn  5585:     if (!defined($uname)) {
                   5586:         $uname = $env{'user.name'};
                   5587:     }
                   5588:     if (!defined($udom)) {
                   5589:         $udom = $env{'user.domain'};
                   5590:     }
                   5591:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5592:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5593:         if (!%roles) {
                   5594:             %roles = (
                   5595:                        cc => 1,
1.907     raeburn  5596:                        co => 1,
1.482     raeburn  5597:                        in => 1,
                   5598:                        ep => 1,
                   5599:                        ta => 1,
                   5600:                        cr => 1,
                   5601:                        st => 1,
                   5602:              );
                   5603:         }
                   5604:         foreach my $entry (keys(%roleshash)) {
                   5605:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5606:             if ($trole =~ /^cr/) { 
                   5607:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5608:             } else {
                   5609:                 next if (!exists($roles{$trole}));
                   5610:             }
                   5611:             if ($tend) {
                   5612:                 next if ($tend < $now);
                   5613:             }
                   5614:             if ($tstart) {
                   5615:                 next if ($tstart > $now);
                   5616:             }
1.1058    raeburn  5617:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5618:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5619:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5620:             if ($secpart eq '') {
                   5621:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5622:                 $sec = 'none';
1.1058    raeburn  5623:                 $value .= $cnum.'/';
1.482     raeburn  5624:             } else {
                   5625:                 $cnum = $cnumpart;
                   5626:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5627:                 $value .= $cnum.'/'.$sec;
                   5628:             }
                   5629:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5630:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5631:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5632:                 }
                   5633:             } else {
                   5634:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5635:             }
1.482     raeburn  5636:         }
                   5637:     } else {
                   5638:         foreach my $key (keys(%env)) {
1.483     albertel 5639: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5640:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5641: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5642: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5643: 	        next if (%roles && !exists($roles{$role}));
                   5644: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5645:                 my $active=1;
                   5646:                 if ($starttime) {
                   5647: 		    if ($now<$starttime) { $active=0; }
                   5648:                 }
                   5649:                 if ($endtime) {
                   5650:                     if ($now>$endtime) { $active=0; }
                   5651:                 }
                   5652:                 if ($active) {
1.1058    raeburn  5653:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5654:                     if ($sec eq '') {
                   5655:                         $sec = 'none';
1.1058    raeburn  5656:                     } else {
                   5657:                         $value .= $sec;
                   5658:                     }
                   5659:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5660:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5661:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5662:                         }
                   5663:                     } else {
                   5664:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5665:                     }
1.474     raeburn  5666:                 }
                   5667:             }
1.51      www      5668:         }
                   5669:     }
1.474     raeburn  5670:     return %courses;
1.51      www      5671: }
1.37      matthew  5672: 
1.54      www      5673: ###############################################
1.474     raeburn  5674: 
                   5675: sub blockcheck {
1.1372    raeburn  5676:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5677:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5678:         my ($has_evb,$check_ipaccess);
                   5679:         my $dom = $env{'user.domain'};
                   5680:         if ($env{'request.course.id'}) {
                   5681:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5682:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5683:             my $checkrole = "cm./$cdom/$cnum";
                   5684:             my $sec = $env{'request.course.sec'};
                   5685:             if ($sec ne '') {
                   5686:                 $checkrole .= "/$sec";
                   5687:             }
                   5688:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5689:                 ($env{'request.role'} !~ /^st/)) {
                   5690:                 $has_evb = 1;
                   5691:             }
                   5692:             unless ($has_evb) {
                   5693:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
1.1444    raeburn  5694:                     ($activity eq 'index') || ($activity eq 'boards') || ($activity eq 'groups') || 
                   5695:                     ($activity eq 'chat')) {
1.1372    raeburn  5696:                     if ($udom eq $cdom) {
                   5697:                         $check_ipaccess = 1;
                   5698:                     }
                   5699:                 }
                   5700:             }
1.1375    raeburn  5701:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5702:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5703:             my $checkrole;
                   5704:             if ($env{'request.role.domain'} eq '') {
                   5705:                 $checkrole = "cm./$env{'user.domain'}/";
                   5706:             } else {
                   5707:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5708:             }
                   5709:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5710:                 $has_evb = 1;
                   5711:             }
1.1372    raeburn  5712:         }
                   5713:         unless ($has_evb || $check_ipaccess) {
                   5714:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5715:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5716:                 $dom = $udom;
                   5717:             }
                   5718:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5719:                 $check_ipaccess = 1;
                   5720:             } else {
                   5721:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5722:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5723:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5724:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5725:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5726:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5727:                         $check_ipaccess = 1;
                   5728:                     }
                   5729:                 }
                   5730:             }
                   5731:         }
                   5732:         if ($check_ipaccess) {
                   5733:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5734:             unless (defined($cached)) {
                   5735:                 my %domconfig =
                   5736:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5737:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5738:             }
                   5739:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5740:                 foreach my $id (keys(%{$ipaccessref})) {
                   5741:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5742:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5743:                         if ($range) {
                   5744:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5745:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5746:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5747:                                         return ('','','',$id,$dom);
                   5748:                                         last;
                   5749:                                     }
                   5750:                                 }
                   5751:                             }
                   5752:                         }
                   5753:                     }
                   5754:                 }
                   5755:             }
                   5756:         }
1.1373    raeburn  5757:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5758:             return ();
                   5759:         }
1.1372    raeburn  5760:     }
1.1189    raeburn  5761:     if (defined($udom) && defined($uname)) {
                   5762:         # If uname and udom are for a course, check for blocks in the course.
                   5763:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5764:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5765:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5766:             return ($startblock,$endblock,$triggerblock);
                   5767:         }
                   5768:     } else {
1.490     raeburn  5769:         $udom = $env{'user.domain'};
                   5770:         $uname = $env{'user.name'};
                   5771:     }
                   5772: 
1.502     raeburn  5773:     my $startblock = 0;
                   5774:     my $endblock = 0;
1.1062    raeburn  5775:     my $triggerblock = '';
1.1373    raeburn  5776:     my %live_courses;
                   5777:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5778:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5779:     }
1.474     raeburn  5780: 
1.490     raeburn  5781:     # If uname is for a user, and activity is course-specific, i.e.,
                   5782:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5783: 
1.490     raeburn  5784:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5785:          $activity eq 'groups' || $activity eq 'printout' ||
1.1444    raeburn  5786:          $activity eq 'search' || $activity eq 'index' ||
                   5787:          $activity eq 'reinit' || $activity eq 'alert') &&
1.1189    raeburn  5788:         ($env{'request.course.id'})) {
1.490     raeburn  5789:         foreach my $key (keys(%live_courses)) {
                   5790:             if ($key ne $env{'request.course.id'}) {
                   5791:                 delete($live_courses{$key});
                   5792:             }
                   5793:         }
                   5794:     }
                   5795: 
                   5796:     my $otheruser = 0;
                   5797:     my %own_courses;
                   5798:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5799:         # Resource belongs to user other than current user.
                   5800:         $otheruser = 1;
                   5801:         # Gather courses for current user
                   5802:         %own_courses = 
                   5803:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5804:     }
                   5805: 
                   5806:     # Gather active course roles - course coordinator, instructor, 
                   5807:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5808: 
                   5809:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5810:         my ($cdom,$cnum);
                   5811:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5812:             $cdom = $env{'course.'.$course.'.domain'};
                   5813:             $cnum = $env{'course.'.$course.'.num'};
                   5814:         } else {
1.490     raeburn  5815:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5816:         }
                   5817:         my $no_ownblock = 0;
                   5818:         my $no_userblock = 0;
1.533     raeburn  5819:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5820:             # Check if current user has 'evb' priv for this
                   5821:             if (defined($own_courses{$course})) {
                   5822:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5823:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5824:                     if ($sec ne 'none') {
                   5825:                         $checkrole .= '/'.$sec;
                   5826:                     }
                   5827:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5828:                         $no_ownblock = 1;
                   5829:                         last;
                   5830:                     }
                   5831:                 }
                   5832:             }
                   5833:             # if they have 'evb' priv and are currently not playing student
                   5834:             next if (($no_ownblock) &&
                   5835:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5836:         }
1.474     raeburn  5837:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5838:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5839:             if ($sec ne 'none') {
1.482     raeburn  5840:                 $checkrole .= '/'.$sec;
1.474     raeburn  5841:             }
1.490     raeburn  5842:             if ($otheruser) {
                   5843:                 # Resource belongs to user other than current user.
                   5844:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5845:                 my (%allroles,%userroles);
                   5846:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5847:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5848:                         my ($trole,$tdom,$tnum,$tsec);
                   5849:                         if ($entry =~ /^cr/) {
                   5850:                             ($trole,$tdom,$tnum,$tsec) = 
                   5851:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5852:                         } else {
                   5853:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5854:                         }
                   5855:                         my ($spec,$area,$trest);
                   5856:                         $area = '/'.$tdom.'/'.$tnum;
                   5857:                         $trest = $tnum;
                   5858:                         if ($tsec ne '') {
                   5859:                             $area .= '/'.$tsec;
                   5860:                             $trest .= '/'.$tsec;
                   5861:                         }
                   5862:                         $spec = $trole.'.'.$area;
                   5863:                         if ($trole =~ /^cr/) {
                   5864:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5865:                                                               $tdom,$spec,$trest,$area);
                   5866:                         } else {
                   5867:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5868:                                                                 $tdom,$spec,$trest,$area);
                   5869:                         }
                   5870:                     }
1.1276    raeburn  5871:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5872:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5873:                         if ($1) {
                   5874:                             $no_userblock = 1;
                   5875:                             last;
                   5876:                         }
1.486     raeburn  5877:                     }
                   5878:                 }
1.490     raeburn  5879:             } else {
                   5880:                 # Resource belongs to current user
                   5881:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5882:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5883:                     $no_ownblock = 1;
                   5884:                     last;
                   5885:                 }
1.474     raeburn  5886:             }
                   5887:         }
                   5888:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5889:         next if (($no_ownblock) &&
1.491     albertel 5890:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5891:         next if ($no_userblock);
1.474     raeburn  5892: 
1.1303    raeburn  5893:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5894:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5895: 
1.1062    raeburn  5896:         my ($start,$end,$trigger) = 
1.1347    raeburn  5897:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5898:         if (($start != 0) && 
                   5899:             (($startblock == 0) || ($startblock > $start))) {
                   5900:             $startblock = $start;
1.1062    raeburn  5901:             if ($trigger ne '') {
                   5902:                 $triggerblock = $trigger;
                   5903:             }
1.502     raeburn  5904:         }
                   5905:         if (($end != 0)  &&
                   5906:             (($endblock == 0) || ($endblock < $end))) {
                   5907:             $endblock = $end;
1.1062    raeburn  5908:             if ($trigger ne '') {
                   5909:                 $triggerblock = $trigger;
                   5910:             }
1.502     raeburn  5911:         }
1.490     raeburn  5912:     }
1.1062    raeburn  5913:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5914: }
                   5915: 
                   5916: sub get_blocks {
1.1347    raeburn  5917:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5918:     my $startblock = 0;
                   5919:     my $endblock = 0;
1.1062    raeburn  5920:     my $triggerblock = '';
1.490     raeburn  5921:     my $course = $cdom.'_'.$cnum;
                   5922:     $setters->{$course} = {};
                   5923:     $setters->{$course}{'staff'} = [];
                   5924:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5925:     $setters->{$course}{'triggers'} = [];
                   5926:     my (@blockers,%triggered);
                   5927:     my $now = time;
                   5928:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5929:     if ($activity eq 'docs') {
1.1348    raeburn  5930:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5931:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5932:             $blocked = 1;
                   5933:             $nosymbcache = 1;
1.1348    raeburn  5934:             $noenccheck = 1;
1.1347    raeburn  5935:         }
1.1348    raeburn  5936:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5937:         foreach my $block (@blockers) {
                   5938:             if ($block =~ /^firstaccess____(.+)$/) {
                   5939:                 my $item = $1;
                   5940:                 my $type = 'map';
                   5941:                 my $timersymb = $item;
                   5942:                 if ($item eq 'course') {
                   5943:                     $type = 'course';
                   5944:                 } elsif ($item =~ /___\d+___/) {
                   5945:                     $type = 'resource';
                   5946:                 } else {
                   5947:                     $timersymb = &Apache::lonnet::symbread($item);
                   5948:                 }
                   5949:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5950:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5951:                 $triggered{$block} = {
                   5952:                                        start => $start,
                   5953:                                        end   => $end,
                   5954:                                        type  => $type,
                   5955:                                      };
                   5956:             }
                   5957:         }
                   5958:     } else {
                   5959:         foreach my $block (keys(%commblocks)) {
                   5960:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5961:                 my ($start,$end) = ($1,$2);
                   5962:                 if ($start <= time && $end >= time) {
                   5963:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5964:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5965:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5966:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5967:                                     push(@blockers,$block);
                   5968:                                 }
                   5969:                             }
                   5970:                         }
                   5971:                     }
                   5972:                 }
                   5973:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5974:                 my $item = $1;
                   5975:                 my $timersymb = $item; 
                   5976:                 my $type = 'map';
                   5977:                 if ($item eq 'course') {
                   5978:                     $type = 'course';
                   5979:                 } elsif ($item =~ /___\d+___/) {
                   5980:                     $type = 'resource';
                   5981:                 } else {
                   5982:                     $timersymb = &Apache::lonnet::symbread($item);
                   5983:                 }
                   5984:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5985:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5986:                 if ($start && $end) {
                   5987:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5988:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5989:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5990:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5991:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5992:                                         push(@blockers,$block);
                   5993:                                         $triggered{$block} = {
                   5994:                                                                start => $start,
                   5995:                                                                end   => $end,
                   5996:                                                                type  => $type,
                   5997:                                                              };
                   5998:                                     }
                   5999:                                 }
                   6000:                             }
1.1062    raeburn  6001:                         }
                   6002:                     }
1.490     raeburn  6003:                 }
1.1062    raeburn  6004:             }
                   6005:         }
                   6006:     }
                   6007:     foreach my $blocker (@blockers) {
                   6008:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6009:             &parse_block_record($commblocks{$blocker});
                   6010:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6011:         my ($start,$end,$triggertype);
                   6012:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6013:             ($start,$end) = ($1,$2);
                   6014:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6015:             $start = $triggered{$blocker}{'start'};
                   6016:             $end = $triggered{$blocker}{'end'};
                   6017:             $triggertype = $triggered{$blocker}{'type'};
                   6018:         }
                   6019:         if ($start) {
                   6020:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6021:             if ($triggertype) {
                   6022:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6023:             } else {
                   6024:                 push(@{$$setters{$course}{'triggers'}},0);
                   6025:             }
                   6026:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6027:                 $startblock = $start;
                   6028:                 if ($triggertype) {
                   6029:                     $triggerblock = $blocker;
1.474     raeburn  6030:                 }
                   6031:             }
1.1062    raeburn  6032:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6033:                $endblock = $end;
                   6034:                if ($triggertype) {
                   6035:                    $triggerblock = $blocker;
                   6036:                }
                   6037:             }
1.474     raeburn  6038:         }
                   6039:     }
1.1062    raeburn  6040:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6041: }
                   6042: 
                   6043: sub parse_block_record {
                   6044:     my ($record) = @_;
                   6045:     my ($setuname,$setudom,$title,$blocks);
                   6046:     if (ref($record) eq 'HASH') {
                   6047:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6048:         $title = &unescape($record->{'event'});
                   6049:         $blocks = $record->{'blocks'};
                   6050:     } else {
                   6051:         my @data = split(/:/,$record,3);
                   6052:         if (scalar(@data) eq 2) {
                   6053:             $title = $data[1];
                   6054:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6055:         } else {
                   6056:             ($setuname,$setudom,$title) = @data;
                   6057:         }
                   6058:         $blocks = { 'com' => 'on' };
                   6059:     }
                   6060:     return ($setuname,$setudom,$title,$blocks);
                   6061: }
                   6062: 
1.854     kalberla 6063: sub blocking_status {
1.1372    raeburn  6064:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6065:     my %setters;
1.890     droeschl 6066: 
1.1061    raeburn  6067: # check for active blocking
1.1372    raeburn  6068:     if ($clientip eq '') {
                   6069:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6070:     }
                   6071:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6072:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6073:     my $blocked = 0;
1.1372    raeburn  6074:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6075:         $blocked = 1;
                   6076:     }
1.890     droeschl 6077: 
1.1061    raeburn  6078: # caller just wants to know whether a block is active
                   6079:     if (!wantarray) { return $blocked; }
                   6080: 
                   6081: # build a link to a popup window containing the details
                   6082:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6083: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6084:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6085:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6086:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6087:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6088:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6089:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6090:         if ($symb) {
                   6091:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6092:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6093:         }
1.1062    raeburn  6094:     }
1.1061    raeburn  6095: 
                   6096:     my $output .= <<'END_MYBLOCK';
                   6097: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6098:     var options = "width=" + w + ",height=" + h + ",";
                   6099:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6100:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6101:     var newWin = window.open(url, wdwName, options);
                   6102:     newWin.focus();
                   6103: }
1.890     droeschl 6104: END_MYBLOCK
1.854     kalberla 6105: 
1.1061    raeburn  6106:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6107:   
1.1061    raeburn  6108:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6109:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6110:     my $class = 'LC_comblock';
1.1062    raeburn  6111:     if ($activity eq 'docs') {
                   6112:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6113:         $class = '';
1.1063    raeburn  6114:     } elsif ($activity eq 'printout') {
                   6115:         $text = &mt('Printing Blocked');
1.1232    raeburn  6116:     } elsif ($activity eq 'passwd') {
                   6117:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6118:     } elsif ($activity eq 'grades') {
                   6119:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6120:     } elsif ($activity eq 'search') {
                   6121:         $text = &mt('Search Blocked');
1.1444    raeburn  6122:     } elsif ($activity eq 'index') {
                   6123:         $text = &mt('Content Index Blocked');
1.1282    raeburn  6124:     } elsif ($activity eq 'alert') {
                   6125:         $text = &mt('Checking Critical Messages Blocked');
                   6126:     } elsif ($activity eq 'reinit') {
                   6127:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6128:     } elsif ($activity eq 'about') {
                   6129:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6130:     } elsif ($activity eq 'wishlist') {
                   6131:         $text = &mt('Access to Stored Links Blocked');
                   6132:     } elsif ($activity eq 'annotate') {
                   6133:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6134:     }
1.1061    raeburn  6135:     $output .= <<"END_BLOCK";
1.1217    raeburn  6136: <div class='$class'>
1.869     kalberla 6137:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6138:   title='$text'>
                   6139:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6140:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6141:   title='$text'>$text</a>
1.867     kalberla 6142: </div>
                   6143: 
                   6144: END_BLOCK
1.474     raeburn  6145: 
1.1061    raeburn  6146:     return ($blocked, $output);
1.854     kalberla 6147: }
1.490     raeburn  6148: 
1.60      matthew  6149: ###############################################
                   6150: 
1.682     raeburn  6151: sub check_ip_acc {
1.1201    raeburn  6152:     my ($acc,$clientip)=@_;
1.682     raeburn  6153:     &Apache::lonxml::debug("acc is $acc");
                   6154:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6155:         return 1;
                   6156:     }
1.1339    raeburn  6157:     my ($ip,$allowed);
                   6158:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6159:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6160:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6161:     } else {
1.1350    raeburn  6162:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6163:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6164:     }
1.682     raeburn  6165: 
                   6166:     my $name;
1.1219    raeburn  6167:     my %access = (
                   6168:                      allowfrom => 1,
                   6169:                      denyfrom  => 0,
                   6170:                  );
                   6171:     my @allows;
                   6172:     my @denies;
                   6173:     foreach my $item (split(',',$acc)) {
                   6174:         $item =~ s/^\s*//;
                   6175:         $item =~ s/\s*$//;
                   6176:         my $pattern;
                   6177:         if ($item =~ /^\!(.+)$/) {
                   6178:             push(@denies,$1);
                   6179:         } else {
                   6180:             push(@allows,$item);
                   6181:         }
                   6182:    }
                   6183:    my $numdenies = scalar(@denies);
                   6184:    my $numallows = scalar(@allows);
                   6185:    my $count = 0;
                   6186:    foreach my $pattern (@denies,@allows) {
                   6187:         $count ++; 
                   6188:         my $acctype = 'allowfrom';
                   6189:         if ($count <= $numdenies) {
                   6190:             $acctype = 'denyfrom';
                   6191:         }
1.682     raeburn  6192:         if ($pattern =~ /\*$/) {
                   6193:             #35.8.*
                   6194:             $pattern=~s/\*//;
1.1219    raeburn  6195:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6196:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6197:             #35.8.3.[34-56]
                   6198:             my $low=$2;
                   6199:             my $high=$3;
                   6200:             $pattern=$1;
                   6201:             if ($ip =~ /^\Q$pattern\E/) {
                   6202:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6203:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6204:             }
                   6205:         } elsif ($pattern =~ /^\*/) {
                   6206:             #*.msu.edu
                   6207:             $pattern=~s/\*//;
                   6208:             if (!defined($name)) {
                   6209:                 use Socket;
                   6210:                 my $netaddr=inet_aton($ip);
                   6211:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6212:             }
1.1219    raeburn  6213:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6214:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6215:             #127.0.0.1
1.1219    raeburn  6216:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6217:         } else {
                   6218:             #some.name.com
                   6219:             if (!defined($name)) {
                   6220:                 use Socket;
                   6221:                 my $netaddr=inet_aton($ip);
                   6222:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6223:             }
1.1219    raeburn  6224:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6225:         }
                   6226:         if ($allowed =~ /^(0|1)$/) { last; }
                   6227:     }
                   6228:     if ($allowed eq '') {
                   6229:         if ($numdenies && !$numallows) {
                   6230:             $allowed = 1;
                   6231:         } else {
                   6232:             $allowed = 0;
1.682     raeburn  6233:         }
                   6234:     }
                   6235:     return $allowed;
                   6236: }
                   6237: 
                   6238: ###############################################
                   6239: 
1.60      matthew  6240: =pod
                   6241: 
1.112     bowersj2 6242: =head1 Domain Template Functions
                   6243: 
                   6244: =over 4
                   6245: 
                   6246: =item * &determinedomain()
1.60      matthew  6247: 
                   6248: Inputs: $domain (usually will be undef)
                   6249: 
1.63      www      6250: Returns: Determines which domain should be used for designs
1.60      matthew  6251: 
                   6252: =cut
1.54      www      6253: 
1.60      matthew  6254: ###############################################
1.63      www      6255: sub determinedomain {
                   6256:     my $domain=shift;
1.531     albertel 6257:     if (! $domain) {
1.60      matthew  6258:         # Determine domain if we have not been given one
1.893     raeburn  6259:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6260:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6261:         if ($env{'request.role.domain'}) { 
                   6262:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6263:         }
                   6264:     }
1.63      www      6265:     return $domain;
                   6266: }
                   6267: ###############################################
1.517     raeburn  6268: 
1.518     albertel 6269: sub devalidate_domconfig_cache {
                   6270:     my ($udom)=@_;
                   6271:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6272: }
                   6273: 
                   6274: # ---------------------- Get domain configuration for a domain
                   6275: sub get_domainconf {
                   6276:     my ($udom) = @_;
                   6277:     my $cachetime=1800;
                   6278:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6279:     if (defined($cached)) { return %{$result}; }
                   6280: 
                   6281:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6282: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6283:     my (%designhash,%legacy);
1.518     albertel 6284:     if (keys(%domconfig) > 0) {
                   6285:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6286:             if (keys(%{$domconfig{'login'}})) {
                   6287:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6288:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6289:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6290:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6291:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6292:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6293:                                         if ($key eq 'loginvia') {
                   6294:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6295:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6296:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6297:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6298: 
                   6299:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6300:                                                 } else {
                   6301:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6302:                                                 }
1.948     raeburn  6303:                                             }
1.1208    raeburn  6304:                                         } elsif ($key eq 'headtag') {
                   6305:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6306:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6307:                                             }
1.946     raeburn  6308:                                         }
1.1208    raeburn  6309:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6310:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6311:                                         }
1.946     raeburn  6312:                                     }
                   6313:                                 }
                   6314:                             }
1.1366    raeburn  6315:                         } elsif ($key eq 'saml') {
                   6316:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6317:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6318:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6319:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6320:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6321:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6322:                                         }
                   6323:                                     }
                   6324:                                 }
                   6325:                             }
1.946     raeburn  6326:                         } else {
                   6327:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6328:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6329:                                     $domconfig{'login'}{$key}{$img};
                   6330:                             }
1.699     raeburn  6331:                         }
                   6332:                     } else {
                   6333:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6334:                     }
1.632     raeburn  6335:                 }
                   6336:             } else {
                   6337:                 $legacy{'login'} = 1;
1.518     albertel 6338:             }
1.632     raeburn  6339:         } else {
                   6340:             $legacy{'login'} = 1;
1.518     albertel 6341:         }
                   6342:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6343:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6344:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6345:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6346:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6347:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6348:                         }
1.518     albertel 6349:                     }
                   6350:                 }
1.632     raeburn  6351:             } else {
                   6352:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6353:             }
1.632     raeburn  6354:         } else {
                   6355:             $legacy{'rolecolors'} = 1;
1.518     albertel 6356:         }
1.948     raeburn  6357:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6358:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6359:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6360:             }
                   6361:         }
1.632     raeburn  6362:         if (keys(%legacy) > 0) {
                   6363:             my %legacyhash = &get_legacy_domconf($udom);
                   6364:             foreach my $item (keys(%legacyhash)) {
                   6365:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6366:                     if ($legacy{'login'}) { 
                   6367:                         $designhash{$item} = $legacyhash{$item};
                   6368:                     }
                   6369:                 } else {
                   6370:                     if ($legacy{'rolecolors'}) {
                   6371:                         $designhash{$item} = $legacyhash{$item};
                   6372:                     }
1.518     albertel 6373:                 }
                   6374:             }
                   6375:         }
1.632     raeburn  6376:     } else {
                   6377:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6378:     }
                   6379:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6380: 				  $cachetime);
                   6381:     return %designhash;
                   6382: }
                   6383: 
1.632     raeburn  6384: sub get_legacy_domconf {
                   6385:     my ($udom) = @_;
                   6386:     my %legacyhash;
                   6387:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6388:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6389:     if (-e $designfile) {
1.1317    raeburn  6390:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6391:             while (my $line = <$fh>) {
                   6392:                 next if ($line =~ /^\#/);
                   6393:                 chomp($line);
                   6394:                 my ($key,$val)=(split(/\=/,$line));
                   6395:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6396:             }
                   6397:             close($fh);
                   6398:         }
                   6399:     }
1.1026    raeburn  6400:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6401:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6402:     }
                   6403:     return %legacyhash;
                   6404: }
                   6405: 
1.63      www      6406: =pod
                   6407: 
1.112     bowersj2 6408: =item * &domainlogo()
1.63      www      6409: 
                   6410: Inputs: $domain (usually will be undef)
                   6411: 
                   6412: Returns: A link to a domain logo, if the domain logo exists.
                   6413: If the domain logo does not exist, a description of the domain.
                   6414: 
                   6415: =cut
1.112     bowersj2 6416: 
1.63      www      6417: ###############################################
                   6418: sub domainlogo {
1.517     raeburn  6419:     my $domain = &determinedomain(shift);
1.518     albertel 6420:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6421:     # See if there is a logo
                   6422:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6423:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6424:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6425: 	    if ($imgsrc =~ m{^/res/}) {
                   6426: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6427: 		&Apache::lonnet::repcopy($local_name);
                   6428: 	    }
                   6429: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6430:         }
                   6431:         my $alttext = $domain;
                   6432:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6433:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6434:         }
                   6435:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6436:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6437:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6438:     } else {
1.60      matthew  6439:         return '';
1.59      www      6440:     }
                   6441: }
1.63      www      6442: ##############################################
                   6443: 
                   6444: =pod
                   6445: 
1.112     bowersj2 6446: =item * &designparm()
1.63      www      6447: 
                   6448: Inputs: $which parameter; $domain (usually will be undef)
                   6449: 
                   6450: Returns: value of designparamter $which
                   6451: 
                   6452: =cut
1.112     bowersj2 6453: 
1.397     albertel 6454: 
1.400     albertel 6455: ##############################################
1.397     albertel 6456: sub designparm {
                   6457:     my ($which,$domain)=@_;
                   6458:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6459:         return $env{'environment.color.'.$which};
1.96      www      6460:     }
1.63      www      6461:     $domain=&determinedomain($domain);
1.1016    raeburn  6462:     my %domdesign;
                   6463:     unless ($domain eq 'public') {
                   6464:         %domdesign = &get_domainconf($domain);
                   6465:     }
1.520     raeburn  6466:     my $output;
1.517     raeburn  6467:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6468:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6469:     } else {
1.520     raeburn  6470:         $output = $defaultdesign{$which};
                   6471:     }
                   6472:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6473:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6474:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6475:             if ($output =~ m{^/res/}) {
                   6476:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6477:                 &Apache::lonnet::repcopy($local_name);
                   6478:             }
1.520     raeburn  6479:             $output = &lonhttpdurl($output);
                   6480:         }
1.63      www      6481:     }
1.520     raeburn  6482:     return $output;
1.63      www      6483: }
1.59      www      6484: 
1.822     bisitz   6485: ##############################################
                   6486: =pod
                   6487: 
1.832     bisitz   6488: =item * &authorspace()
                   6489: 
1.1028    raeburn  6490: Inputs: $url (usually will be undef).
1.832     bisitz   6491: 
1.1132    raeburn  6492: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6493:          directory being viewed (or for which action is being taken). 
                   6494:          If $url is provided, and begins /priv/<domain>/<uname>
                   6495:          the path will be that portion of the $context argument.
                   6496:          Otherwise the path will be for the author space of the current
                   6497:          user when the current role is author, or for that of the 
                   6498:          co-author/assistant co-author space when the current role 
                   6499:          is co-author or assistant co-author.
1.832     bisitz   6500: 
                   6501: =cut
                   6502: 
                   6503: sub authorspace {
1.1028    raeburn  6504:     my ($url) = @_;
                   6505:     if ($url ne '') {
                   6506:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6507:            return $1;
                   6508:         }
                   6509:     }
1.832     bisitz   6510:     my $caname = '';
1.1024    www      6511:     my $cadom = '';
1.1028    raeburn  6512:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6513:         ($cadom,$caname) =
1.832     bisitz   6514:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6515:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6516:         $caname = $env{'user.name'};
1.1024    www      6517:         $cadom = $env{'user.domain'};
1.832     bisitz   6518:     }
1.1028    raeburn  6519:     if (($caname ne '') && ($cadom ne '')) {
                   6520:         return "/priv/$cadom/$caname/";
                   6521:     }
                   6522:     return;
1.832     bisitz   6523: }
                   6524: 
                   6525: ##############################################
                   6526: =pod
                   6527: 
1.822     bisitz   6528: =item * &head_subbox()
                   6529: 
                   6530: Inputs: $content (contains HTML code with page functions, etc.)
                   6531: 
                   6532: Returns: HTML div with $content
                   6533:          To be included in page header
                   6534: 
                   6535: =cut
                   6536: 
                   6537: sub head_subbox {
                   6538:     my ($content)=@_;
                   6539:     my $output =
1.993     raeburn  6540:         '<div class="LC_head_subbox">'
1.822     bisitz   6541:        .$content
                   6542:        .'</div>'
                   6543: }
                   6544: 
                   6545: ##############################################
                   6546: =pod
                   6547: 
                   6548: =item * &CSTR_pageheader()
                   6549: 
1.1026    raeburn  6550: Input: (optional) filename from which breadcrumb trail is built.
                   6551:        In most cases no input as needed, as $env{'request.filename'}
                   6552:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6553:        frameset flag
                   6554:        If page header is being requested for use in a frameset, then
                   6555:        the second (option) argument -- frameset will be true, and
                   6556:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6557:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6558:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6559: 
                   6560: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6561:          To be included on Authoring Space pages
1.822     bisitz   6562: 
                   6563: =cut
                   6564: 
                   6565: sub CSTR_pageheader {
1.1407    raeburn  6566:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6567:     if ($trailfile eq '') {
                   6568:         $trailfile = $env{'request.filename'};
                   6569:     }
                   6570: 
                   6571: # this is for resources; directories have customtitle, and crumbs
                   6572: # and select recent are created in lonpubdir.pm
                   6573: 
                   6574:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6575:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6576:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6577:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6578:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6579: 
                   6580:     my $parentpath = '';
                   6581:     my $lastitem = '';
                   6582:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6583:         $parentpath = $1;
                   6584:         $lastitem = $2;
                   6585:     } else {
                   6586:         $lastitem = $thisdisfn;
                   6587:     }
1.921     bisitz   6588: 
1.1406    raeburn  6589:     my $crsauthor;
1.1246    raeburn  6590:     if (($env{'request.course.id'}) &&
                   6591:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6592:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6593:         $crsauthor = 1;
1.1406    raeburn  6594:         if ($title eq '') {
                   6595:             $title = &mt('Course Authoring Space');
                   6596:         }
                   6597:     } elsif ($title eq '') {
1.1246    raeburn  6598:         $title = &mt('Authoring Space');
                   6599:     }
                   6600: 
1.1379    raeburn  6601:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6602:     if ($frameset) {
                   6603:         $target = ' target="_parent"';
                   6604:         $crumbtarget = '_parent';
                   6605:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6606:         $target = '';
                   6607:         $crumbtarget = '';
1.1379    raeburn  6608:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6609:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6610:         $crumbtarget = $env{'request.deeplink.target'};
                   6611:     }
1.1313    raeburn  6612: 
1.921     bisitz   6613:     my $output =
1.1407    raeburn  6614:          '<div>'
1.822     bisitz   6615:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6616:         .'<b>'.$title.'</b> '
1.1314    raeburn  6617:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6618:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6619: 
                   6620:     if ($lastitem) {
                   6621:         $output .=
                   6622:              '<span class="LC_filename">'
                   6623:             .$lastitem
                   6624:             .'</span>';
                   6625:     }
1.1245    raeburn  6626: 
1.1246    raeburn  6627:     if ($crsauthor) {
1.1379    raeburn  6628:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6629:     } else {
                   6630:         $output .=
                   6631:              '<br />'
1.1314    raeburn  6632:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6633:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6634:             .'</form>'
1.1379    raeburn  6635:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6636:     }
1.1407    raeburn  6637:     $output .= '</div>';
1.921     bisitz   6638: 
                   6639:     return $output;
1.822     bisitz   6640: }
                   6641: 
1.1419    raeburn  6642: ##############################################
                   6643: =pod
                   6644: 
                   6645: =item * &nocodemirror()
                   6646: 
                   6647: Input: None
                   6648: 
                   6649: Returns: 1 if CodeMirror is deactivated based on
                   6650:          user's preference, or domain default,
                   6651:          if user indicated use of default.
                   6652: 
                   6653: =cut
                   6654: 
1.1416    raeburn  6655: sub nocodemirror {
                   6656:     my $nocodem = $env{'environment.nocodemirror'};
                   6657:     unless ($nocodem) {
                   6658:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6659:         if ($domdefs{'nocodemirror'}) {
                   6660:             $nocodem = 'yes';
                   6661:         }
                   6662:     }
1.1417    raeburn  6663:     if ($nocodem eq 'yes') {
                   6664:         return 1;
                   6665:     }
                   6666:     return;
1.1416    raeburn  6667: }
                   6668: 
1.1419    raeburn  6669: ##############################################
                   6670: =pod
                   6671: 
                   6672: =item * &permitted_editors()
                   6673: 
1.1422    raeburn  6674: Input: $uri (optional)
1.1419    raeburn  6675: 
                   6676: Returns: %editors hash in which keys are editors
1.1429    raeburn  6677:          permitted in current Authoring Space,
                   6678:          or in current course for web pages
                   6679:          created in a course.
                   6680: 
1.1419    raeburn  6681:          Value for each key is 1. Possible keys
1.1429    raeburn  6682:          are: edit, xml, and daxe.
                   6683: 
                   6684:          For a regular Authoring Space, if no specific
1.1419    raeburn  6685:          set of editors has been set for the Author
                   6686:          who owns the Authoring Space, then the
                   6687:          domain default will be used.  If no domain
                   6688:          default has been set, then the keys will be
                   6689:          edit and xml.
                   6690: 
1.1429    raeburn  6691:          For a course author, or for web pages created
                   6692:          in a course, if no specific set of editors has
                   6693:          been set for the course, then the domain
                   6694:          course default will be used. If no domain
                   6695:          course default has been set, then the keys
                   6696:          will be edit and xml.
                   6697: 
1.1419    raeburn  6698: =cut
                   6699: 
1.1418    raeburn  6700: sub permitted_editors {
1.1422    raeburn  6701:     my ($uri) = @_;
1.1429    raeburn  6702:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6703:     if ($env{'request.role'} =~ m{^au\./}) {
                   6704:         $is_author = 1;
                   6705:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6706:         ($audom,$auname) = ($1,$2);
                   6707:         if (($audom ne '') && ($auname ne '')) {
                   6708:             if (($env{'user.domain'} eq $audom) &&
                   6709:                 ($env{'user.name'} eq $auname)) {
                   6710:                 $is_author = 1;
                   6711:             } else {
                   6712:                 $is_coauthor = 1;
                   6713:             }
                   6714:         }
                   6715:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6716:         my ($cdom,$cnum);
                   6717:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6718:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6719:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6720:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6721:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6722:             $is_course = 1;
                   6723:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6724:             ($audom,$auname) = ($1,$2);
                   6725:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6726:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6727:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6728:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6729:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6730:             $is_course = 1;
                   6731:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6732:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6733:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6734:         }
1.1429    raeburn  6735:         unless ($is_course) {
                   6736:             if (($audom ne '') && ($auname ne '')) {
                   6737:                 if (($env{'user.domain'} eq $audom) &&
                   6738:                     ($env{'user.name'} eq $auname)) {
                   6739:                     $is_author = 1;
                   6740:                 } else {
                   6741:                     $is_coauthor = 1;
                   6742:                 }
1.1418    raeburn  6743:             }
                   6744:         }
                   6745:     }
                   6746:     if ($is_author) {
                   6747:         if (exists($env{'environment.editors'})) {
                   6748:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6749:         } else {
                   6750:             %editors = ( edit => 1,
                   6751:                          xml => 1,
                   6752:                        );
                   6753:         }
                   6754:     } elsif ($is_coauthor) {
                   6755:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6756:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6757:         } else {
                   6758:             %editors = ( edit => 1,
                   6759:                          xml => 1,
                   6760:                        );
                   6761:         }
1.1429    raeburn  6762:     } elsif ($is_course) {
                   6763:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6764:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6765:         } else {
                   6766:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6767:             if (exists($domdefaults{'crseditors'})) {
                   6768:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6769:             } else {
                   6770:                 %editors = ( edit => 1,
                   6771:                              xml => 1,
                   6772:                            );
                   6773:             }
                   6774:         }
1.1418    raeburn  6775:     } else {
                   6776:         %editors = ( edit => 1,
                   6777:                      xml => 1,
                   6778:                    );
                   6779:     }
                   6780:     return %editors;
                   6781: }
                   6782: 
1.60      matthew  6783: ###############################################
                   6784: ###############################################
                   6785: 
                   6786: =pod
                   6787: 
1.112     bowersj2 6788: =back
                   6789: 
1.549     albertel 6790: =head1 HTML Helpers
1.112     bowersj2 6791: 
                   6792: =over 4
                   6793: 
                   6794: =item * &bodytag()
1.60      matthew  6795: 
                   6796: Returns a uniform header for LON-CAPA web pages.
                   6797: 
                   6798: Inputs: 
                   6799: 
1.112     bowersj2 6800: =over 4
                   6801: 
                   6802: =item * $title, A title to be displayed on the page.
                   6803: 
                   6804: =item * $function, the current role (can be undef).
                   6805: 
                   6806: =item * $addentries, extra parameters for the <body> tag.
                   6807: 
                   6808: =item * $bodyonly, if defined, only return the <body> tag.
                   6809: 
                   6810: =item * $domain, if defined, force a given domain.
                   6811: 
                   6812: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6813:             text interface only)
1.60      matthew  6814: 
1.814     bisitz   6815: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6816:                      navigational links
1.317     albertel 6817: 
1.338     albertel 6818: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6819: 
1.460     albertel 6820: =item * $args, optional argument valid values are
                   6821:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6822:             use_absolute     -> for external resource or syllabus, this will
                   6823:                                 contain https://<hostname> if server uses
                   6824:                                 https (as per hosts.tab), but request is for http
                   6825:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6826: 
1.1096    raeburn  6827: =item * $advtoolsref, optional argument, ref to an array containing
                   6828:             inlineremote items to be added in "Functions" menu below
                   6829:             breadcrumbs.
                   6830: 
1.1316    raeburn  6831: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6832:             course, if LON-CAPA is in LTI Provider context. Value is
                   6833:             the scope of use, i.e., launch was for access to a single, a map
                   6834:             or the entire course.
                   6835: 
                   6836: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6837:             context, this will contain the URL for the landing item in
                   6838:             the course, after launch from an LTI Consumer
                   6839: 
1.1318    raeburn  6840: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6841:             context, this will contain a reference to hash of items
                   6842:             to be included in the page header and/or inline menu.
                   6843: 
1.1385    raeburn  6844: =item * $menucoll, optional argument, if specific menu collection is in
                   6845:             effect, either set as the default for the course, or set for
                   6846:             the deeplink paramater for $env{'request.deeplink.login'}
                   6847:             then $menucoll will be the number of that collection. 
                   6848: 
                   6849: =item * $menuref, optional argument, reference to a hash, containing the
                   6850:             menu options included for the menu in effect, based on the
                   6851:             configuration for the numbered menu collection in use.  
                   6852: 
                   6853: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6854:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6855:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6856:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6857:             being called a second time.
                   6858: 
1.112     bowersj2 6859: =back
                   6860: 
1.60      matthew  6861: Returns: A uniform header for LON-CAPA web pages.  
                   6862: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6863: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6864: other decorations will be returned.
                   6865: 
                   6866: =cut
                   6867: 
1.54      www      6868: sub bodytag {
1.831     bisitz   6869:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6870:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6871:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6872: 
1.954     raeburn  6873:     my $public;
                   6874:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6875:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6876:         $public = 1;
                   6877:     }
1.460     albertel 6878:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6879:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6880:     my $hostname = $args->{'hostname'};
1.339     albertel 6881: 
1.183     matthew  6882:     $function = &get_users_function() if (!$function);
1.339     albertel 6883:     my $font =   &designparm($function.'.font',$domain);
                   6884:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6885: 
1.803     bisitz   6886:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6887: 		   'bgcolor' => $pgbg,
1.339     albertel 6888: 		   'text'    => $font,
                   6889:                    'alink'   => &designparm($function.'.alink',$domain),
                   6890: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6891: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6892:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6893: 
1.63      www      6894:  # role and realm
1.1178    raeburn  6895:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6896:     if ($realm) {
                   6897:         $realm = '/'.$realm;
                   6898:     }
1.1357    raeburn  6899:     if ($role eq 'ca') {
1.479     albertel 6900:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6901:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6902:     } 
1.55      www      6903: # realm
1.1357    raeburn  6904:     my ($cid,$sec);
1.258     albertel 6905:     if ($env{'request.course.id'}) {
1.1357    raeburn  6906:         $cid = $env{'request.course.id'};
                   6907:         if ($env{'request.course.sec'}) {
                   6908:             $sec = $env{'request.course.sec'};
                   6909:         }
                   6910:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6911:         if (&Apache::lonnet::is_course($1,$2)) {
                   6912:             $cid = $1.'_'.$2;
                   6913:             $sec = $3;
                   6914:         }
                   6915:     }
                   6916:     if ($cid) {
1.378     raeburn  6917:         if ($env{'request.role'} !~ /^cr/) {
                   6918:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6919:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6920:             if ($env{'request.role.desc'}) {
                   6921:                 $role = $env{'request.role.desc'};
                   6922:             } else {
                   6923:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6924:             }
1.1257    raeburn  6925:         } else {
                   6926:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6927:         }
1.1357    raeburn  6928:         if ($sec) {
                   6929:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6930:         }   
1.1357    raeburn  6931: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6932:     } else {
                   6933:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6934:     }
1.433     albertel 6935: 
1.359     albertel 6936:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6937: 
1.438     albertel 6938:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6939: 
1.101     www      6940: # construct main body tag
1.359     albertel 6941:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6942: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6943: 
1.1131    raeburn  6944:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6945: 
1.1130    raeburn  6946:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6947:         return $bodytag;
1.1130    raeburn  6948:     }
1.359     albertel 6949: 
1.954     raeburn  6950:     if ($public) {
1.433     albertel 6951: 	undef($role);
                   6952:     }
1.1318    raeburn  6953: 
1.1359    raeburn  6954:     my $showcrstitle = 1;
1.1357    raeburn  6955:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6956:         if (ref($ltimenu) eq 'HASH') {
                   6957:             unless ($ltimenu->{'role'}) {
                   6958:                 undef($role);
                   6959:             }
                   6960:             unless ($ltimenu->{'coursetitle'}) {
                   6961:                 $realm='&nbsp;';
1.1359    raeburn  6962:                 $showcrstitle = 0;
                   6963:             }
                   6964:         }
                   6965:     } elsif (($cid) && ($menucoll)) {
                   6966:         if (ref($menuref) eq 'HASH') {
                   6967:             unless ($menuref->{'role'}) {
                   6968:                 undef($role);
                   6969:             }
                   6970:             unless ($menuref->{'crs'}) {
                   6971:                 $realm='&nbsp;';
                   6972:                 $showcrstitle = 0;
1.1318    raeburn  6973:             }
                   6974:         }
                   6975:     }
                   6976: 
1.762     bisitz   6977:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6978:     #
                   6979:     # Extra info if you are the DC
                   6980:     my $dc_info = '';
1.1359    raeburn  6981:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6982:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6983:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6984:         $dc_info =~ s/\s+$//;
1.359     albertel 6985:     }
                   6986: 
1.1237    raeburn  6987:     my $crstype;
1.1357    raeburn  6988:     if ($cid) {
                   6989:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6990:     } elsif ($args->{'crstype'}) {
                   6991:         $crstype = $args->{'crstype'};
                   6992:     }
                   6993:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6994:         undef($role);
                   6995:     } else {
1.1242    raeburn  6996:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6997:     }
1.853     droeschl 6998: 
1.903     droeschl 6999:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   7000: 
                   7001:         #    if ($env{'request.state'} eq 'construct') {
                   7002:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7003:         #    }
                   7004: 
1.1440    raeburn  7005:         my $need_endlcint;
                   7006:         unless ($args->{'switchserver'}) {
                   7007:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7008:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7009:             $need_endlcint = 1;
                   7010:         }
1.359     albertel 7011: 
1.1427    raeburn  7012:         my $collapsible;
1.1423    raeburn  7013:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7014:             $collapsible = 1;
                   7015:             my ($menustate,$tiptext,$divclass);
                   7016:             if ($args->{'start_collapsed'}) {
                   7017:                 $menustate = 'collapsed';
                   7018:                 $tiptext = 'display';
                   7019:                 $divclass = 'hidden';
                   7020:             } else {
                   7021:                 $menustate = 'expanded';
                   7022:                 $tiptext = 'hide';
                   7023:                 $divclass = 'shown';
                   7024:             }
                   7025:             my $alttext = &mt('menu state: '.$menustate);
                   7026:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7027:             $bodytag .= <<"END";
                   7028: <div id="LC_expandingContainer" style="display:inline;">
                   7029: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7030: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/$menustate.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   7031: <div class="LC_menus_content $divclass">
1.1421    raeburn  7032: END
                   7033:         }
1.1318    raeburn  7034:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7035:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7036:                                                               $args->{'links_disabled'},
1.1421    raeburn  7037:                                                               $args->{'links_target'},
1.1427    raeburn  7038:                                                               $collapsible);
1.359     albertel 7039: 
1.1318    raeburn  7040:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7041:                 if ($dc_info) {
                   7042:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7043:                 }
                   7044:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   7045:                                <em>$realm</em> $dc_info</div>|;
1.1440    raeburn  7046:                 if ($need_endlcint) {
                   7047:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7048:                 }
1.1318    raeburn  7049:                 return $bodytag;
                   7050:             }
1.894     droeschl 7051: 
1.1318    raeburn  7052:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7053:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7054:             }
1.916     droeschl 7055: 
1.1318    raeburn  7056:             $bodytag .= $right;
1.852     droeschl 7057: 
1.1318    raeburn  7058:             if ($dc_info) {
                   7059:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7060:             }
                   7061:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  7062:         }
1.916     droeschl 7063: 
1.1169    raeburn  7064:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7065:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7066:             if ($need_endlcint) {
                   7067:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7068:             }
1.1168    raeburn  7069:             return $bodytag;
                   7070:         }
1.1169    raeburn  7071:         #don't show menus for public users
1.954     raeburn  7072:         if (!$public){
1.1318    raeburn  7073:             unless ($args->{'no_inline_menu'}) {
                   7074:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7075:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7076:                                                             $menucoll,$menuref,
1.1380    raeburn  7077:                                                             $args->{'links_disabled'},
                   7078:                                                             $args->{'links_target'});
1.1318    raeburn  7079:             }
1.903     droeschl 7080:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7081:             if ($need_endlcint) {
                   7082:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7083:             }
1.920     raeburn  7084:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7085:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7086:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7087:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7088:             } elsif ($forcereg) {
                   7089:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7090:                                 $args->{'group'},$args->{'hide_buttons'},
                   7091:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7092:             } else {
                   7093:                 $bodytag .= 
                   7094:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7095:                                                         $forcereg,$args->{'group'},
                   7096:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7097:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7098:             }
1.1440    raeburn  7099:         } else {
                   7100:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7101:             # menu. Especially needed for publicly accessible resources.
1.903     droeschl 7102:             $bodytag .= '<hr style="clear:both" />';
1.1440    raeburn  7103:             if ($need_endlcint) {
                   7104:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7105:             }
1.235     raeburn  7106:         }
1.1423    raeburn  7107:         if ($args->{'collapsible_header'} ne '') {
                   7108:             $bodytag .= $args->{'collapsible_header'}.
                   7109:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7110:                         '</div></div>';
                   7111:         }
1.235     raeburn  7112:         return $bodytag;
1.182     matthew  7113: }
                   7114: 
1.917     raeburn  7115: sub dc_courseid_toggle {
                   7116:     my ($dc_info) = @_;
1.980     raeburn  7117:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7118:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7119:            &mt('(More ...)').'</a></span>'.
                   7120:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7121: }
                   7122: 
1.330     albertel 7123: sub make_attr_string {
                   7124:     my ($register,$attr_ref) = @_;
                   7125: 
                   7126:     if ($attr_ref && !ref($attr_ref)) {
                   7127: 	die("addentries Must be a hash ref ".
                   7128: 	    join(':',caller(1))." ".
                   7129: 	    join(':',caller(0))." ");
                   7130:     }
                   7131: 
                   7132:     if ($register) {
1.339     albertel 7133: 	my ($on_load,$on_unload);
                   7134: 	foreach my $key (keys(%{$attr_ref})) {
                   7135: 	    if      (lc($key) eq 'onload') {
                   7136: 		$on_load.=$attr_ref->{$key}.';';
                   7137: 		delete($attr_ref->{$key});
                   7138: 
                   7139: 	    } elsif (lc($key) eq 'onunload') {
                   7140: 		$on_unload.=$attr_ref->{$key}.';';
                   7141: 		delete($attr_ref->{$key});
                   7142: 	    }
                   7143: 	}
1.953     droeschl 7144: 	$attr_ref->{'onload'}  = $on_load;
                   7145: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7146:     }
1.339     albertel 7147: 
1.330     albertel 7148:     my $attr_string;
1.1159    raeburn  7149:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7150: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7151:     }
                   7152:     return $attr_string;
                   7153: }
                   7154: 
                   7155: 
1.182     matthew  7156: ###############################################
1.251     albertel 7157: ###############################################
                   7158: 
                   7159: =pod
                   7160: 
                   7161: =item * &endbodytag()
                   7162: 
                   7163: Returns a uniform footer for LON-CAPA web pages.
                   7164: 
1.635     raeburn  7165: Inputs: 1 - optional reference to an args hash
                   7166: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7167: a 'Continue' link is not displayed if the page contains an
                   7168: internal redirect in the <head></head> section,
                   7169: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7170: 
                   7171: =cut
                   7172: 
                   7173: sub endbodytag {
1.635     raeburn  7174:     my ($args) = @_;
1.1080    raeburn  7175:     my $endbodytag;
                   7176:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7177:         $endbodytag='</body>';
                   7178:     }
1.315     albertel 7179:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7180:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7181:             my ($endbodyjs,$idattr);
                   7182:             if ($env{'internal.head.to_opener'}) {
                   7183:                 my $linkid = 'LC_continue_link';
                   7184:                 $idattr = ' id="'.$linkid.'"';
                   7185:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7186:                 $endbodyjs=<<ENDJS;
                   7187: <script type="text/javascript">
                   7188: // <![CDATA[
                   7189: function ebFunction(evt) {
                   7190:     evt.preventDefault();
                   7191:     var dest = '$redirect_for_js';
                   7192:     if (window.opener != null && !window.opener.closed) {
                   7193:         window.opener.location.href=dest;
                   7194:         window.close();
                   7195:     } else {
                   7196:         window.location.href=dest;
                   7197:     }
                   7198:     return false;
                   7199: }
                   7200: 
                   7201: \$(document).ready(function () {
                   7202:   if (document.getElementById('$linkid')) {
                   7203:     var clickelem = document.getElementById('$linkid');
                   7204:     clickelem.addEventListener('click',ebFunction,false);
                   7205:   }
                   7206: });
                   7207: // ]]>
                   7208: </script>
                   7209: ENDJS
                   7210:             }
1.635     raeburn  7211: 	    $endbodytag=
1.1386    raeburn  7212: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7213: 	        &mt('Continue').'</a>'.
                   7214: 	        $endbodytag;
                   7215:         }
1.315     albertel 7216:     }
1.1411    raeburn  7217:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7218:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7219:     }
1.251     albertel 7220:     return $endbodytag;
                   7221: }
                   7222: 
1.352     albertel 7223: =pod
                   7224: 
                   7225: =item * &standard_css()
                   7226: 
                   7227: Returns a style sheet
                   7228: 
                   7229: Inputs: (all optional)
                   7230:             domain         -> force to color decorate a page for a specific
                   7231:                                domain
                   7232:             function       -> force usage of a specific rolish color scheme
                   7233:             bgcolor        -> override the default page bgcolor
                   7234: 
                   7235: =cut
                   7236: 
1.343     albertel 7237: sub standard_css {
1.345     albertel 7238:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7239:     $function  = &get_users_function() if (!$function);
                   7240:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7241:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7242:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7243: #second colour for later usage
1.345     albertel 7244:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7245:     my $pgbg_or_bgcolor =
                   7246: 	         $bgcolor ||
1.352     albertel 7247: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7248:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7249:     my $alink  = &designparm($function.'.alink', $domain);
                   7250:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7251:     my $link   = &designparm($function.'.link',  $domain);
                   7252: 
1.602     albertel 7253:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7254:     my $mono                 = 'monospace';
1.850     bisitz   7255:     my $data_table_head      = $sidebg;
                   7256:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7257:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7258:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7259:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7260:     my $mail_new             = '#FFBB77';
                   7261:     my $mail_new_hover       = '#DD9955';
                   7262:     my $mail_read            = '#BBBB77';
                   7263:     my $mail_read_hover      = '#999944';
                   7264:     my $mail_replied         = '#AAAA88';
                   7265:     my $mail_replied_hover   = '#888855';
                   7266:     my $mail_other           = '#99BBBB';
                   7267:     my $mail_other_hover     = '#669999';
1.391     albertel 7268:     my $table_header         = '#DDDDDD';
1.489     raeburn  7269:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7270:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7271:     my $button_hover         = '#BF2317';
1.392     albertel 7272: 
1.608     albertel 7273:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7274:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7275:                                              : '0 3px 0 4px';
1.448     albertel 7276: 
1.523     albertel 7277: 
1.343     albertel 7278:     return <<END;
1.947     droeschl 7279: 
                   7280: /* needed for iframe to allow 100% height in FF */
                   7281: body, html { 
                   7282:     margin: 0;
                   7283:     padding: 0 0.5%;
                   7284:     height: 99%; /* to avoid scrollbars */
                   7285: }
                   7286: 
1.795     www      7287: body {
1.911     bisitz   7288:   font-family: $sans;
                   7289:   line-height:130%;
                   7290:   font-size:0.83em;
                   7291:   color:$font;
1.1436    raeburn  7292:   background-color: $pgbg_or_bgcolor;
1.795     www      7293: }
                   7294: 
1.959     onken    7295: a:focus,
                   7296: a:focus img {
1.795     www      7297:   color: red;
                   7298: }
1.698     harmsja  7299: 
1.911     bisitz   7300: form, .inline {
                   7301:   display: inline;
1.795     www      7302: }
1.721     harmsja  7303: 
1.1443    raeburn  7304: .LC_visually_hidden:not(:focus):not(:active) {
                   7305:     clip-path: inset(50%);
                   7306:     height: 1px;
                   7307:     overflow: hidden;
                   7308:     position: absolute;
                   7309:     white-space: nowrap;
                   7310:     width: 1px;
                   7311:     display: inline;
                   7312: }
                   7313: 
1.1421    raeburn  7314: .LC_menus_content.shown{
1.1428    raeburn  7315:   display: block;
1.1421    raeburn  7316: }
                   7317: 
                   7318: .LC_menus_content.hidden {
                   7319:   display: none;
                   7320: }
                   7321: 
1.795     www      7322: .LC_right {
1.911     bisitz   7323:   text-align:right;
1.795     www      7324: }
                   7325: 
1.1449  ! raeburn  7326: .LC_center {
        !          7327:   text-align:center;
        !          7328: }
        !          7329: 
1.795     www      7330: .LC_middle {
1.911     bisitz   7331:   vertical-align:middle;
1.795     www      7332: }
1.721     harmsja  7333: 
1.1130    raeburn  7334: .LC_floatleft {
                   7335:   float: left;
                   7336: }
                   7337: 
                   7338: .LC_floatright {
                   7339:   float: right;
                   7340: }
                   7341: 
1.911     bisitz   7342: .LC_400Box {
                   7343:   width:400px;
                   7344: }
1.721     harmsja  7345: 
1.1421    raeburn  7346: #LC_collapsible_separator {
                   7347:     border: 1px solid black;
                   7348:     width: 99.9%;
                   7349:     height: 0px;
                   7350: }
                   7351: 
1.947     droeschl 7352: .LC_iframecontainer {
                   7353:     width: 98%;
                   7354:     margin: 0;
                   7355:     position: fixed;
                   7356:     top: 8.5em;
                   7357:     bottom: 0;
                   7358: }
                   7359: 
                   7360: .LC_iframecontainer iframe{
                   7361:     border: none;
                   7362:     width: 100%;
                   7363:     height: 100%;
                   7364: }
                   7365: 
1.778     bisitz   7366: .LC_filename {
                   7367:   font-family: $mono;
                   7368:   white-space:pre;
1.921     bisitz   7369:   font-size: 120%;
1.778     bisitz   7370: }
                   7371: 
                   7372: .LC_fileicon {
                   7373:   border: none;
                   7374:   height: 1.3em;
                   7375:   vertical-align: text-bottom;
                   7376:   margin-right: 0.3em;
                   7377:   text-decoration:none;
                   7378: }
                   7379: 
1.1008    www      7380: .LC_setting {
                   7381:   text-decoration:underline;
                   7382: }
                   7383: 
1.350     albertel 7384: .LC_error {
                   7385:   color: red;
                   7386: }
1.795     www      7387: 
1.1097    bisitz   7388: .LC_warning {
                   7389:   color: darkorange;
                   7390: }
                   7391: 
1.457     albertel 7392: .LC_diff_removed {
1.733     bisitz   7393:   color: red;
1.394     albertel 7394: }
1.532     albertel 7395: 
                   7396: .LC_info,
1.457     albertel 7397: .LC_success,
                   7398: .LC_diff_added {
1.350     albertel 7399:   color: green;
                   7400: }
1.795     www      7401: 
1.802     bisitz   7402: div.LC_confirm_box {
                   7403:   background-color: #FAFAFA;
                   7404:   border: 1px solid $lg_border_color;
                   7405:   margin-right: 0;
                   7406:   padding: 5px;
                   7407: }
                   7408: 
                   7409: div.LC_confirm_box .LC_error img,
                   7410: div.LC_confirm_box .LC_success img {
                   7411:   vertical-align: middle;
                   7412: }
                   7413: 
1.1242    raeburn  7414: .LC_maxwidth {
                   7415:   max-width: 100%;
                   7416:   height: auto;
                   7417: }
                   7418: 
1.1243    raeburn  7419: .LC_textsize_mobile {
                   7420:   \@media only screen and (max-device-width: 480px) {
                   7421:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7422:   }
                   7423: }
                   7424: 
1.440     albertel 7425: .LC_icon {
1.771     droeschl 7426:   border: none;
1.790     droeschl 7427:   vertical-align: middle;
1.771     droeschl 7428: }
                   7429: 
1.543     albertel 7430: .LC_docs_spacer {
                   7431:   width: 25px;
                   7432:   height: 1px;
1.771     droeschl 7433:   border: none;
1.543     albertel 7434: }
1.346     albertel 7435: 
1.532     albertel 7436: .LC_internal_info {
1.735     bisitz   7437:   color: #999999;
1.532     albertel 7438: }
                   7439: 
1.794     www      7440: .LC_discussion {
1.1050    www      7441:   background: $data_table_dark;
1.911     bisitz   7442:   border: 1px solid black;
                   7443:   margin: 2px;
1.794     www      7444: }
                   7445: 
                   7446: .LC_disc_action_left {
1.1050    www      7447:   background: $sidebg;
1.911     bisitz   7448:   text-align: left;
1.1050    www      7449:   padding: 4px;
                   7450:   margin: 2px;
1.794     www      7451: }
                   7452: 
                   7453: .LC_disc_action_right {
1.1050    www      7454:   background: $sidebg;
1.911     bisitz   7455:   text-align: right;
1.1050    www      7456:   padding: 4px;
                   7457:   margin: 2px;
1.794     www      7458: }
                   7459: 
                   7460: .LC_disc_new_item {
1.911     bisitz   7461:   background: white;
                   7462:   border: 2px solid red;
1.1050    www      7463:   margin: 4px;
                   7464:   padding: 4px;
1.794     www      7465: }
                   7466: 
                   7467: .LC_disc_old_item {
1.911     bisitz   7468:   background: white;
1.1050    www      7469:   margin: 4px;
                   7470:   padding: 4px;
1.794     www      7471: }
                   7472: 
1.458     albertel 7473: table.LC_pastsubmission {
                   7474:   border: 1px solid black;
                   7475:   margin: 2px;
                   7476: }
                   7477: 
1.924     bisitz   7478: table#LC_menubuttons {
1.345     albertel 7479:   width: 100%;
                   7480:   background: $pgbg;
1.392     albertel 7481:   border: 2px;
1.402     albertel 7482:   border-collapse: separate;
1.803     bisitz   7483:   padding: 0;
1.345     albertel 7484: }
1.392     albertel 7485: 
1.801     tempelho 7486: table#LC_title_bar a {
                   7487:   color: $fontmenu;
                   7488: }
1.836     bisitz   7489: 
1.807     droeschl 7490: table#LC_title_bar {
1.819     tempelho 7491:   clear: both;
1.836     bisitz   7492:   display: none;
1.807     droeschl 7493: }
                   7494: 
1.795     www      7495: table#LC_title_bar,
1.933     droeschl 7496: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7497: table#LC_title_bar.LC_with_remote {
1.359     albertel 7498:   width: 100%;
1.392     albertel 7499:   border-color: $pgbg;
                   7500:   border-style: solid;
                   7501:   border-width: $border;
1.379     albertel 7502:   background: $pgbg;
1.801     tempelho 7503:   color: $fontmenu;
1.392     albertel 7504:   border-collapse: collapse;
1.803     bisitz   7505:   padding: 0;
1.819     tempelho 7506:   margin: 0;
1.359     albertel 7507: }
1.795     www      7508: 
1.933     droeschl 7509: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7510:     margin: 0;
                   7511:     padding: 0;
1.933     droeschl 7512:     position: relative;
                   7513:     list-style: none;
1.913     droeschl 7514: }
1.933     droeschl 7515: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7516:     display: inline;
                   7517: }
1.933     droeschl 7518: 
                   7519: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7520:     padding: 0;
1.933     droeschl 7521:     margin: 0;
                   7522:     float: left;
1.913     droeschl 7523: }
1.933     droeschl 7524: .LC_breadcrumb_tools_tools {
                   7525:     padding: 0;
                   7526:     margin: 0;
1.913     droeschl 7527:     float: right;
                   7528: }
                   7529: 
1.1240    raeburn  7530: .LC_placement_prog {
                   7531:     padding-right: 20px;
                   7532:     font-weight: bold;
                   7533:     font-size: 90%;
                   7534: }
                   7535: 
1.359     albertel 7536: table#LC_title_bar td {
                   7537:   background: $tabbg;
                   7538: }
1.795     www      7539: 
1.911     bisitz   7540: table#LC_menubuttons img {
1.803     bisitz   7541:   border: none;
1.346     albertel 7542: }
1.795     www      7543: 
1.842     droeschl 7544: .LC_breadcrumbs_component {
1.911     bisitz   7545:   float: right;
                   7546:   margin: 0 1em;
1.357     albertel 7547: }
1.842     droeschl 7548: .LC_breadcrumbs_component img {
1.911     bisitz   7549:   vertical-align: middle;
1.777     tempelho 7550: }
1.795     www      7551: 
1.1243    raeburn  7552: .LC_breadcrumbs_hoverable {
                   7553:   background: $sidebg;
                   7554: }
                   7555: 
1.383     albertel 7556: td.LC_table_cell_checkbox {
                   7557:   text-align: center;
                   7558: }
1.795     www      7559: 
                   7560: .LC_fontsize_small {
1.911     bisitz   7561:   font-size: 70%;
1.705     tempelho 7562: }
                   7563: 
1.844     bisitz   7564: #LC_breadcrumbs {
1.911     bisitz   7565:   clear:both;
                   7566:   background: $sidebg;
                   7567:   border-bottom: 1px solid $lg_border_color;
                   7568:   line-height: 2.5em;
1.933     droeschl 7569:   overflow: hidden;
1.911     bisitz   7570:   margin: 0;
                   7571:   padding: 0;
1.995     raeburn  7572:   text-align: left;
1.819     tempelho 7573: }
1.862     bisitz   7574: 
1.1098    bisitz   7575: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7576:   clear:both;
                   7577:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7578:   border: 1px solid $sidebg;
1.1098    bisitz   7579:   margin: 0 0 10px 0;
1.966     bisitz   7580:   padding: 3px;
1.995     raeburn  7581:   text-align: left;
1.822     bisitz   7582: }
                   7583: 
1.795     www      7584: .LC_fontsize_medium {
1.911     bisitz   7585:   font-size: 85%;
1.705     tempelho 7586: }
                   7587: 
1.795     www      7588: .LC_fontsize_large {
1.911     bisitz   7589:   font-size: 120%;
1.705     tempelho 7590: }
                   7591: 
1.346     albertel 7592: .LC_menubuttons_inline_text {
                   7593:   color: $font;
1.698     harmsja  7594:   font-size: 90%;
1.701     harmsja  7595:   padding-left:3px;
1.346     albertel 7596: }
                   7597: 
1.934     droeschl 7598: .LC_menubuttons_inline_text img{
                   7599:   vertical-align: middle;
                   7600: }
                   7601: 
1.1051    www      7602: li.LC_menubuttons_inline_text img {
1.951     onken    7603:   cursor:pointer;
1.1002    droeschl 7604:   text-decoration: none;
1.951     onken    7605: }
                   7606: 
1.526     www      7607: .LC_menubuttons_link {
                   7608:   text-decoration: none;
                   7609: }
1.795     www      7610: 
1.522     albertel 7611: .LC_menubuttons_category {
1.521     www      7612:   color: $font;
1.526     www      7613:   background: $pgbg;
1.521     www      7614:   font-size: larger;
                   7615:   font-weight: bold;
                   7616: }
                   7617: 
1.346     albertel 7618: td.LC_menubuttons_text {
1.911     bisitz   7619:   color: $font;
1.346     albertel 7620: }
1.706     harmsja  7621: 
1.346     albertel 7622: .LC_current_location {
                   7623:   background: $tabbg;
                   7624: }
1.795     www      7625: 
1.1286    raeburn  7626: td.LC_zero_height {
                   7627:   line-height: 0; 
                   7628:   cellpadding: 0;
                   7629: }
                   7630: 
1.938     bisitz   7631: table.LC_data_table {
1.347     albertel 7632:   border: 1px solid #000000;
1.402     albertel 7633:   border-collapse: separate;
1.426     albertel 7634:   border-spacing: 1px;
1.610     albertel 7635:   background: $pgbg;
1.347     albertel 7636: }
1.795     www      7637: 
1.422     albertel 7638: .LC_data_table_dense {
                   7639:   font-size: small;
                   7640: }
1.795     www      7641: 
1.507     raeburn  7642: table.LC_nested_outer {
                   7643:   border: 1px solid #000000;
1.589     raeburn  7644:   border-collapse: collapse;
1.803     bisitz   7645:   border-spacing: 0;
1.507     raeburn  7646:   width: 100%;
                   7647: }
1.795     www      7648: 
1.879     raeburn  7649: table.LC_innerpickbox,
1.507     raeburn  7650: table.LC_nested {
1.803     bisitz   7651:   border: none;
1.589     raeburn  7652:   border-collapse: collapse;
1.803     bisitz   7653:   border-spacing: 0;
1.507     raeburn  7654:   width: 100%;
                   7655: }
1.795     www      7656: 
1.911     bisitz   7657: table.LC_data_table tr th,
                   7658: table.LC_calendar tr th,
1.879     raeburn  7659: table.LC_prior_tries tr th,
                   7660: table.LC_innerpickbox tr th {
1.349     albertel 7661:   font-weight: bold;
                   7662:   background-color: $data_table_head;
1.801     tempelho 7663:   color:$fontmenu;
1.701     harmsja  7664:   font-size:90%;
1.347     albertel 7665: }
1.795     www      7666: 
1.879     raeburn  7667: table.LC_innerpickbox tr th,
                   7668: table.LC_innerpickbox tr td {
                   7669:   vertical-align: top;
                   7670: }
                   7671: 
1.711     raeburn  7672: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7673:   background-color: #CCCCCC;
1.711     raeburn  7674:   font-weight: bold;
                   7675:   text-align: left;
                   7676: }
1.795     www      7677: 
1.912     bisitz   7678: table.LC_data_table tr.LC_odd_row > td {
                   7679:   background-color: $data_table_light;
                   7680:   padding: 2px;
                   7681:   vertical-align: top;
                   7682: }
                   7683: 
1.809     bisitz   7684: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7685:   background-color: $data_table_light;
1.912     bisitz   7686:   vertical-align: top;
                   7687: }
                   7688: 
                   7689: table.LC_data_table tr.LC_even_row > td {
                   7690:   background-color: $data_table_dark;
1.425     albertel 7691:   padding: 2px;
1.900     bisitz   7692:   vertical-align: top;
1.347     albertel 7693: }
1.795     www      7694: 
1.809     bisitz   7695: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7696:   background-color: $data_table_dark;
1.900     bisitz   7697:   vertical-align: top;
1.347     albertel 7698: }
1.795     www      7699: 
1.425     albertel 7700: table.LC_data_table tr.LC_data_table_highlight td {
                   7701:   background-color: $data_table_darker;
                   7702: }
1.795     www      7703: 
1.639     raeburn  7704: table.LC_data_table tr td.LC_leftcol_header {
                   7705:   background-color: $data_table_head;
                   7706:   font-weight: bold;
                   7707: }
1.795     www      7708: 
1.451     albertel 7709: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7710: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7711:   font-weight: bold;
                   7712:   font-style: italic;
                   7713:   text-align: center;
                   7714:   padding: 8px;
1.347     albertel 7715: }
1.795     www      7716: 
1.1114    raeburn  7717: table.LC_data_table tr.LC_empty_row td,
                   7718: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7719:   background-color: $sidebg;
                   7720: }
                   7721: 
                   7722: table.LC_nested tr.LC_empty_row td {
                   7723:   background-color: #FFFFFF;
                   7724: }
                   7725: 
1.890     droeschl 7726: table.LC_caption {
                   7727: }
                   7728: 
1.507     raeburn  7729: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7730:   padding: 4ex
                   7731: }
1.795     www      7732: 
1.507     raeburn  7733: table.LC_nested_outer tr th {
                   7734:   font-weight: bold;
1.801     tempelho 7735:   color:$fontmenu;
1.507     raeburn  7736:   background-color: $data_table_head;
1.701     harmsja  7737:   font-size: small;
1.507     raeburn  7738:   border-bottom: 1px solid #000000;
                   7739: }
1.795     www      7740: 
1.507     raeburn  7741: table.LC_nested_outer tr td.LC_subheader {
                   7742:   background-color: $data_table_head;
                   7743:   font-weight: bold;
                   7744:   font-size: small;
                   7745:   border-bottom: 1px solid #000000;
                   7746:   text-align: right;
1.451     albertel 7747: }
1.795     www      7748: 
1.507     raeburn  7749: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7750:   background-color: #CCCCCC;
1.451     albertel 7751:   font-weight: bold;
                   7752:   font-size: small;
1.507     raeburn  7753:   text-align: center;
                   7754: }
1.795     www      7755: 
1.589     raeburn  7756: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7757: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7758:   text-align: left;
1.451     albertel 7759: }
1.795     www      7760: 
1.507     raeburn  7761: table.LC_nested td {
1.735     bisitz   7762:   background-color: #FFFFFF;
1.451     albertel 7763:   font-size: small;
1.507     raeburn  7764: }
1.795     www      7765: 
1.507     raeburn  7766: table.LC_nested_outer tr th.LC_right_item,
                   7767: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7768: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7769: table.LC_nested tr td.LC_right_item {
1.451     albertel 7770:   text-align: right;
                   7771: }
                   7772: 
1.507     raeburn  7773: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7774:   background-color: #EEEEEE;
1.451     albertel 7775: }
                   7776: 
1.473     raeburn  7777: table.LC_createuser {
                   7778: }
                   7779: 
                   7780: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7781:   font-size: small;
1.473     raeburn  7782: }
                   7783: 
                   7784: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7785:   background-color: #CCCCCC;
1.473     raeburn  7786:   font-weight: bold;
                   7787:   text-align: center;
                   7788: }
                   7789: 
1.349     albertel 7790: table.LC_calendar {
                   7791:   border: 1px solid #000000;
                   7792:   border-collapse: collapse;
1.917     raeburn  7793:   width: 98%;
1.349     albertel 7794: }
1.795     www      7795: 
1.349     albertel 7796: table.LC_calendar_pickdate {
                   7797:   font-size: xx-small;
                   7798: }
1.795     www      7799: 
1.349     albertel 7800: table.LC_calendar tr td {
                   7801:   border: 1px solid #000000;
                   7802:   vertical-align: top;
1.917     raeburn  7803:   width: 14%;
1.349     albertel 7804: }
1.795     www      7805: 
1.349     albertel 7806: table.LC_calendar tr td.LC_calendar_day_empty {
                   7807:   background-color: $data_table_dark;
                   7808: }
1.795     www      7809: 
1.779     bisitz   7810: table.LC_calendar tr td.LC_calendar_day_current {
                   7811:   background-color: $data_table_highlight;
1.777     tempelho 7812: }
1.795     www      7813: 
1.938     bisitz   7814: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7815:   background-color: $mail_new;
                   7816: }
1.795     www      7817: 
1.938     bisitz   7818: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7819:   background-color: $mail_new_hover;
                   7820: }
1.795     www      7821: 
1.938     bisitz   7822: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7823:   background-color: $mail_read;
                   7824: }
1.795     www      7825: 
1.938     bisitz   7826: /*
                   7827: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7828:   background-color: $mail_read_hover;
                   7829: }
1.938     bisitz   7830: */
1.795     www      7831: 
1.938     bisitz   7832: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7833:   background-color: $mail_replied;
                   7834: }
1.795     www      7835: 
1.938     bisitz   7836: /*
                   7837: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7838:   background-color: $mail_replied_hover;
                   7839: }
1.938     bisitz   7840: */
1.795     www      7841: 
1.938     bisitz   7842: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7843:   background-color: $mail_other;
                   7844: }
1.795     www      7845: 
1.938     bisitz   7846: /*
                   7847: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7848:   background-color: $mail_other_hover;
                   7849: }
1.938     bisitz   7850: */
1.494     raeburn  7851: 
1.777     tempelho 7852: table.LC_data_table tr > td.LC_browser_file,
                   7853: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7854:   background: #AAEE77;
1.389     albertel 7855: }
1.795     www      7856: 
1.777     tempelho 7857: table.LC_data_table tr > td.LC_browser_file_locked,
                   7858: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7859:   background: #FFAA99;
1.387     albertel 7860: }
1.795     www      7861: 
1.777     tempelho 7862: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7863:   background: #888888;
1.779     bisitz   7864: }
1.795     www      7865: 
1.777     tempelho 7866: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7867: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7868:   background: #F8F866;
1.777     tempelho 7869: }
1.795     www      7870: 
1.696     bisitz   7871: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7872:   background: #E0E8FF;
1.387     albertel 7873: }
1.696     bisitz   7874: 
1.707     bisitz   7875: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7876:   /* background: #77FF77; */
1.707     bisitz   7877: }
1.795     www      7878: 
1.707     bisitz   7879: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7880:   border-right: 8px solid #FFFF77;
1.707     bisitz   7881: }
1.795     www      7882: 
1.707     bisitz   7883: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7884:   border-right: 8px solid #FFAA77;
1.707     bisitz   7885: }
1.795     www      7886: 
1.707     bisitz   7887: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7888:   border-right: 8px solid #FF7777;
1.707     bisitz   7889: }
1.795     www      7890: 
1.707     bisitz   7891: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7892:   border-right: 8px solid #AAFF77;
1.707     bisitz   7893: }
1.795     www      7894: 
1.707     bisitz   7895: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7896:   border-right: 8px solid #11CC55;
1.707     bisitz   7897: }
                   7898: 
1.388     albertel 7899: span.LC_current_location {
1.701     harmsja  7900:   font-size:larger;
1.388     albertel 7901:   background: $pgbg;
                   7902: }
1.387     albertel 7903: 
1.1029    www      7904: span.LC_current_nav_location {
                   7905:   font-weight:bold;
                   7906:   background: $sidebg;
                   7907: }
                   7908: 
1.395     albertel 7909: span.LC_parm_menu_item {
                   7910:   font-size: larger;
                   7911: }
1.795     www      7912: 
1.395     albertel 7913: span.LC_parm_scope_all {
                   7914:   color: red;
                   7915: }
1.795     www      7916: 
1.395     albertel 7917: span.LC_parm_scope_folder {
                   7918:   color: green;
                   7919: }
1.795     www      7920: 
1.395     albertel 7921: span.LC_parm_scope_resource {
                   7922:   color: orange;
                   7923: }
1.795     www      7924: 
1.395     albertel 7925: span.LC_parm_part {
                   7926:   color: blue;
                   7927: }
1.795     www      7928: 
1.911     bisitz   7929: span.LC_parm_folder,
                   7930: span.LC_parm_symb {
1.395     albertel 7931:   font-size: x-small;
                   7932:   font-family: $mono;
                   7933:   color: #AAAAAA;
                   7934: }
                   7935: 
1.977     bisitz   7936: ul.LC_parm_parmlist li {
                   7937:   display: inline-block;
                   7938:   padding: 0.3em 0.8em;
                   7939:   vertical-align: top;
                   7940:   width: 150px;
                   7941:   border-top:1px solid $lg_border_color;
                   7942: }
                   7943: 
1.795     www      7944: td.LC_parm_overview_level_menu,
                   7945: td.LC_parm_overview_map_menu,
                   7946: td.LC_parm_overview_parm_selectors,
                   7947: td.LC_parm_overview_restrictions  {
1.396     albertel 7948:   border: 1px solid black;
                   7949:   border-collapse: collapse;
                   7950: }
1.795     www      7951: 
1.1285    raeburn  7952: span.LC_parm_recursive,
                   7953: td.LC_parm_recursive {
                   7954:   font-weight: bold;
                   7955:   font-size: smaller;
                   7956: }
                   7957: 
1.396     albertel 7958: table.LC_parm_overview_restrictions td {
                   7959:   border-width: 1px 4px 1px 4px;
                   7960:   border-style: solid;
                   7961:   border-color: $pgbg;
                   7962:   text-align: center;
                   7963: }
1.795     www      7964: 
1.396     albertel 7965: table.LC_parm_overview_restrictions th {
                   7966:   background: $tabbg;
                   7967:   border-width: 1px 4px 1px 4px;
                   7968:   border-style: solid;
                   7969:   border-color: $pgbg;
                   7970: }
1.795     www      7971: 
1.398     albertel 7972: table#LC_helpmenu {
1.803     bisitz   7973:   border: none;
1.398     albertel 7974:   height: 55px;
1.803     bisitz   7975:   border-spacing: 0;
1.398     albertel 7976: }
                   7977: 
                   7978: table#LC_helpmenu fieldset legend {
                   7979:   font-size: larger;
                   7980: }
1.795     www      7981: 
1.397     albertel 7982: table#LC_helpmenu_links {
                   7983:   width: 100%;
                   7984:   border: 1px solid black;
                   7985:   background: $pgbg;
1.803     bisitz   7986:   padding: 0;
1.397     albertel 7987:   border-spacing: 1px;
                   7988: }
1.795     www      7989: 
1.397     albertel 7990: table#LC_helpmenu_links tr td {
                   7991:   padding: 1px;
                   7992:   background: $tabbg;
1.399     albertel 7993:   text-align: center;
                   7994:   font-weight: bold;
1.397     albertel 7995: }
1.396     albertel 7996: 
1.795     www      7997: table#LC_helpmenu_links a:link,
                   7998: table#LC_helpmenu_links a:visited,
1.397     albertel 7999: table#LC_helpmenu_links a:active {
                   8000:   text-decoration: none;
                   8001:   color: $font;
                   8002: }
1.795     www      8003: 
1.397     albertel 8004: table#LC_helpmenu_links a:hover {
                   8005:   text-decoration: underline;
                   8006:   color: $vlink;
                   8007: }
1.396     albertel 8008: 
1.417     albertel 8009: .LC_chrt_popup_exists {
                   8010:   border: 1px solid #339933;
                   8011:   margin: -1px;
                   8012: }
1.795     www      8013: 
1.417     albertel 8014: .LC_chrt_popup_up {
                   8015:   border: 1px solid yellow;
                   8016:   margin: -1px;
                   8017: }
1.795     www      8018: 
1.417     albertel 8019: .LC_chrt_popup {
                   8020:   border: 1px solid #8888FF;
                   8021:   background: #CCCCFF;
                   8022: }
1.795     www      8023: 
1.421     albertel 8024: table.LC_pick_box {
                   8025:   border-collapse: separate;
                   8026:   background: white;
                   8027:   border: 1px solid black;
                   8028:   border-spacing: 1px;
                   8029: }
1.795     www      8030: 
1.421     albertel 8031: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   8032:   background: $sidebg;
1.421     albertel 8033:   font-weight: bold;
1.900     bisitz   8034:   text-align: left;
1.740     bisitz   8035:   vertical-align: top;
1.421     albertel 8036:   width: 184px;
                   8037:   padding: 8px;
                   8038: }
1.795     www      8039: 
1.579     raeburn  8040: table.LC_pick_box td.LC_pick_box_value {
                   8041:   text-align: left;
                   8042:   padding: 8px;
                   8043: }
1.795     www      8044: 
1.579     raeburn  8045: table.LC_pick_box td.LC_pick_box_select {
                   8046:   text-align: left;
                   8047:   padding: 8px;
                   8048: }
1.795     www      8049: 
1.424     albertel 8050: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8051:   padding: 0;
1.421     albertel 8052:   height: 1px;
                   8053:   background: black;
                   8054: }
1.795     www      8055: 
1.421     albertel 8056: table.LC_pick_box td.LC_pick_box_submit {
                   8057:   text-align: right;
                   8058: }
1.795     www      8059: 
1.579     raeburn  8060: table.LC_pick_box td.LC_evenrow_value {
                   8061:   text-align: left;
                   8062:   padding: 8px;
                   8063:   background-color: $data_table_light;
                   8064: }
1.795     www      8065: 
1.579     raeburn  8066: table.LC_pick_box td.LC_oddrow_value {
                   8067:   text-align: left;
                   8068:   padding: 8px;
                   8069:   background-color: $data_table_light;
                   8070: }
1.795     www      8071: 
1.579     raeburn  8072: span.LC_helpform_receipt_cat {
                   8073:   font-weight: bold;
                   8074: }
1.795     www      8075: 
1.424     albertel 8076: table.LC_group_priv_box {
                   8077:   background: white;
                   8078:   border: 1px solid black;
                   8079:   border-spacing: 1px;
                   8080: }
1.795     www      8081: 
1.424     albertel 8082: table.LC_group_priv_box td.LC_pick_box_title {
                   8083:   background: $tabbg;
                   8084:   font-weight: bold;
                   8085:   text-align: right;
                   8086:   width: 184px;
                   8087: }
1.795     www      8088: 
1.424     albertel 8089: table.LC_group_priv_box td.LC_groups_fixed {
                   8090:   background: $data_table_light;
                   8091:   text-align: center;
                   8092: }
1.795     www      8093: 
1.424     albertel 8094: table.LC_group_priv_box td.LC_groups_optional {
                   8095:   background: $data_table_dark;
                   8096:   text-align: center;
                   8097: }
1.795     www      8098: 
1.424     albertel 8099: table.LC_group_priv_box td.LC_groups_functionality {
                   8100:   background: $data_table_darker;
                   8101:   text-align: center;
                   8102:   font-weight: bold;
                   8103: }
1.795     www      8104: 
1.424     albertel 8105: table.LC_group_priv td {
                   8106:   text-align: left;
1.803     bisitz   8107:   padding: 0;
1.424     albertel 8108: }
                   8109: 
                   8110: .LC_navbuttons {
                   8111:   margin: 2ex 0ex 2ex 0ex;
                   8112: }
1.795     www      8113: 
1.423     albertel 8114: .LC_topic_bar {
                   8115:   font-weight: bold;
                   8116:   background: $tabbg;
1.918     wenzelju 8117:   margin: 1em 0em 1em 2em;
1.805     bisitz   8118:   padding: 3px;
1.918     wenzelju 8119:   font-size: 1.2em;
1.423     albertel 8120: }
1.795     www      8121: 
1.423     albertel 8122: .LC_topic_bar span {
1.918     wenzelju 8123:   left: 0.5em;
                   8124:   position: absolute;
1.423     albertel 8125:   vertical-align: middle;
1.918     wenzelju 8126:   font-size: 1.2em;
1.423     albertel 8127: }
1.795     www      8128: 
1.423     albertel 8129: table.LC_course_group_status {
                   8130:   margin: 20px;
                   8131: }
1.795     www      8132: 
1.423     albertel 8133: table.LC_status_selector td {
                   8134:   vertical-align: top;
                   8135:   text-align: center;
1.424     albertel 8136:   padding: 4px;
                   8137: }
1.795     www      8138: 
1.599     albertel 8139: div.LC_feedback_link {
1.616     albertel 8140:   clear: both;
1.829     kalberla 8141:   background: $sidebg;
1.779     bisitz   8142:   width: 100%;
1.829     kalberla 8143:   padding-bottom: 10px;
                   8144:   border: 1px $tabbg solid;
1.833     kalberla 8145:   height: 22px;
                   8146:   line-height: 22px;
                   8147:   padding-top: 5px;
                   8148: }
                   8149: 
                   8150: div.LC_feedback_link img {
                   8151:   height: 22px;
1.867     kalberla 8152:   vertical-align:middle;
1.829     kalberla 8153: }
                   8154: 
1.911     bisitz   8155: div.LC_feedback_link a {
1.829     kalberla 8156:   text-decoration: none;
1.489     raeburn  8157: }
1.795     www      8158: 
1.867     kalberla 8159: div.LC_comblock {
1.911     bisitz   8160:   display:inline;
1.867     kalberla 8161:   color:$font;
                   8162:   font-size:90%;
                   8163: }
                   8164: 
                   8165: div.LC_feedback_link div.LC_comblock {
                   8166:   padding-left:5px;
                   8167: }
                   8168: 
                   8169: div.LC_feedback_link div.LC_comblock a {
                   8170:   color:$font;
                   8171: }
                   8172: 
1.489     raeburn  8173: span.LC_feedback_link {
1.858     bisitz   8174:   /* background: $feedback_link_bg; */
1.599     albertel 8175:   font-size: larger;
                   8176: }
1.795     www      8177: 
1.599     albertel 8178: span.LC_message_link {
1.858     bisitz   8179:   /* background: $feedback_link_bg; */
1.599     albertel 8180:   font-size: larger;
                   8181:   position: absolute;
                   8182:   right: 1em;
1.489     raeburn  8183: }
1.421     albertel 8184: 
1.515     albertel 8185: table.LC_prior_tries {
1.524     albertel 8186:   border: 1px solid #000000;
                   8187:   border-collapse: separate;
                   8188:   border-spacing: 1px;
1.515     albertel 8189: }
1.523     albertel 8190: 
1.515     albertel 8191: table.LC_prior_tries td {
1.524     albertel 8192:   padding: 2px;
1.515     albertel 8193: }
1.523     albertel 8194: 
                   8195: .LC_answer_correct {
1.795     www      8196:   background: lightgreen;
                   8197:   color: darkgreen;
                   8198:   padding: 6px;
1.523     albertel 8199: }
1.795     www      8200: 
1.523     albertel 8201: .LC_answer_charged_try {
1.797     www      8202:   background: #FFAAAA;
1.795     www      8203:   color: darkred;
                   8204:   padding: 6px;
1.523     albertel 8205: }
1.795     www      8206: 
1.779     bisitz   8207: .LC_answer_not_charged_try,
1.523     albertel 8208: .LC_answer_no_grade,
                   8209: .LC_answer_late {
1.795     www      8210:   background: lightyellow;
1.523     albertel 8211:   color: black;
1.795     www      8212:   padding: 6px;
1.523     albertel 8213: }
1.795     www      8214: 
1.523     albertel 8215: .LC_answer_previous {
1.795     www      8216:   background: lightblue;
                   8217:   color: darkblue;
                   8218:   padding: 6px;
1.523     albertel 8219: }
1.795     www      8220: 
1.779     bisitz   8221: .LC_answer_no_message {
1.777     tempelho 8222:   background: #FFFFFF;
                   8223:   color: black;
1.795     www      8224:   padding: 6px;
1.779     bisitz   8225: }
1.795     www      8226: 
1.1334    raeburn  8227: .LC_answer_unknown,
                   8228: .LC_answer_warning {
1.779     bisitz   8229:   background: orange;
                   8230:   color: black;
1.795     www      8231:   padding: 6px;
1.777     tempelho 8232: }
1.795     www      8233: 
1.1446    raeburn  8234: .LC_prob_status {
1.1447    raeburn  8235:   margin-top: 5px;
1.1446    raeburn  8236:   padding-top: 0;
                   8237:   padding-left: 0;
                   8238:   padding-bottom: 0;
                   8239:   padding-right: 5px;
                   8240: }
                   8241: 
1.1448    raeburn  8242: .LC_mail_actions {
                   8243:   float: left;
                   8244:   padding: 0;
                   8245:   margin: 6px;
                   8246: }
                   8247: 
                   8248: .LC_vertical_line {
                   8249:   width: 1px;
                   8250:   background-color: black;
                   8251:   height: 4em;
                   8252:   float: left;
                   8253:   margin: 0;
                   8254:   padding: 0;
                   8255: }
                   8256: 
1.529     albertel 8257: span.LC_prior_numerical,
                   8258: span.LC_prior_string,
                   8259: span.LC_prior_custom,
                   8260: span.LC_prior_reaction,
                   8261: span.LC_prior_math {
1.925     bisitz   8262:   font-family: $mono;
1.523     albertel 8263:   white-space: pre;
                   8264: }
                   8265: 
1.525     albertel 8266: span.LC_prior_string {
1.925     bisitz   8267:   font-family: $mono;
1.525     albertel 8268:   white-space: pre;
                   8269: }
                   8270: 
1.523     albertel 8271: table.LC_prior_option {
                   8272:   width: 100%;
                   8273:   border-collapse: collapse;
                   8274: }
1.795     www      8275: 
1.911     bisitz   8276: table.LC_prior_rank,
1.795     www      8277: table.LC_prior_match {
1.528     albertel 8278:   border-collapse: collapse;
                   8279: }
1.795     www      8280: 
1.528     albertel 8281: table.LC_prior_option tr td,
                   8282: table.LC_prior_rank tr td,
                   8283: table.LC_prior_match tr td {
1.524     albertel 8284:   border: 1px solid #000000;
1.515     albertel 8285: }
                   8286: 
1.855     bisitz   8287: .LC_nobreak {
1.544     albertel 8288:   white-space: nowrap;
1.519     raeburn  8289: }
                   8290: 
1.576     raeburn  8291: span.LC_cusr_emph {
                   8292:   font-style: italic;
                   8293: }
                   8294: 
1.633     raeburn  8295: span.LC_cusr_subheading {
                   8296:   font-weight: normal;
                   8297:   font-size: 85%;
                   8298: }
                   8299: 
1.861     bisitz   8300: div.LC_docs_entry_move {
1.859     bisitz   8301:   border: 1px solid #BBBBBB;
1.545     albertel 8302:   background: #DDDDDD;
1.861     bisitz   8303:   width: 22px;
1.859     bisitz   8304:   padding: 1px;
                   8305:   margin: 0;
1.545     albertel 8306: }
                   8307: 
1.861     bisitz   8308: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8309: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8310:   font-size: x-small;
                   8311: }
1.795     www      8312: 
1.861     bisitz   8313: .LC_docs_entry_parameter {
                   8314:   white-space: nowrap;
                   8315: }
                   8316: 
1.544     albertel 8317: .LC_docs_copy {
1.545     albertel 8318:   color: #000099;
1.544     albertel 8319: }
1.795     www      8320: 
1.544     albertel 8321: .LC_docs_cut {
1.545     albertel 8322:   color: #550044;
1.544     albertel 8323: }
1.795     www      8324: 
1.544     albertel 8325: .LC_docs_rename {
1.545     albertel 8326:   color: #009900;
1.544     albertel 8327: }
1.795     www      8328: 
1.544     albertel 8329: .LC_docs_remove {
1.545     albertel 8330:   color: #990000;
                   8331: }
                   8332: 
1.1284    raeburn  8333: .LC_docs_alias {
                   8334:   color: #440055;  
                   8335: }
                   8336: 
1.1286    raeburn  8337: .LC_domprefs_email,
1.1284    raeburn  8338: .LC_docs_alias_name,
1.547     albertel 8339: .LC_docs_reinit_warn,
                   8340: .LC_docs_ext_edit {
                   8341:   font-size: x-small;
                   8342: }
                   8343: 
1.545     albertel 8344: table.LC_docs_adddocs td,
                   8345: table.LC_docs_adddocs th {
                   8346:   border: 1px solid #BBBBBB;
                   8347:   padding: 4px;
                   8348:   background: #DDDDDD;
1.543     albertel 8349: }
                   8350: 
1.584     albertel 8351: table.LC_sty_begin {
                   8352:   background: #BBFFBB;
                   8353: }
1.795     www      8354: 
1.584     albertel 8355: table.LC_sty_end {
                   8356:   background: #FFBBBB;
                   8357: }
                   8358: 
1.589     raeburn  8359: table.LC_double_column {
1.803     bisitz   8360:   border-width: 0;
1.589     raeburn  8361:   border-collapse: collapse;
                   8362:   width: 100%;
                   8363:   padding: 2px;
                   8364: }
                   8365: 
                   8366: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8367:   top: 2px;
1.589     raeburn  8368:   left: 2px;
                   8369:   width: 47%;
                   8370:   vertical-align: top;
                   8371: }
                   8372: 
                   8373: table.LC_double_column tr td.LC_right_col {
                   8374:   top: 2px;
1.779     bisitz   8375:   right: 2px;
1.589     raeburn  8376:   width: 47%;
                   8377:   vertical-align: top;
                   8378: }
                   8379: 
1.591     raeburn  8380: div.LC_left_float {
                   8381:   float: left;
                   8382:   padding-right: 5%;
1.597     albertel 8383:   padding-bottom: 4px;
1.591     raeburn  8384: }
                   8385: 
                   8386: div.LC_clear_float_header {
1.597     albertel 8387:   padding-bottom: 2px;
1.591     raeburn  8388: }
                   8389: 
                   8390: div.LC_clear_float_footer {
1.597     albertel 8391:   padding-top: 10px;
1.591     raeburn  8392:   clear: both;
                   8393: }
                   8394: 
1.597     albertel 8395: div.LC_grade_show_user {
1.941     bisitz   8396: /*  border-left: 5px solid $sidebg; */
                   8397:   border-top: 5px solid #000000;
                   8398:   margin: 50px 0 0 0;
1.936     bisitz   8399:   padding: 15px 0 5px 10px;
1.597     albertel 8400: }
1.795     www      8401: 
1.936     bisitz   8402: div.LC_grade_show_user_odd_row {
1.941     bisitz   8403: /*  border-left: 5px solid #000000; */
                   8404: }
                   8405: 
                   8406: div.LC_grade_show_user div.LC_Box {
                   8407:   margin-right: 50px;
1.597     albertel 8408: }
                   8409: 
                   8410: div.LC_grade_submissions,
                   8411: div.LC_grade_message_center,
1.936     bisitz   8412: div.LC_grade_info_links {
1.597     albertel 8413:   margin: 5px;
                   8414:   width: 99%;
                   8415:   background: #FFFFFF;
                   8416: }
1.795     www      8417: 
1.597     albertel 8418: div.LC_grade_submissions_header,
1.936     bisitz   8419: div.LC_grade_message_center_header {
1.705     tempelho 8420:   font-weight: bold;
                   8421:   font-size: large;
1.597     albertel 8422: }
1.795     www      8423: 
1.597     albertel 8424: div.LC_grade_submissions_body,
1.936     bisitz   8425: div.LC_grade_message_center_body {
1.597     albertel 8426:   border: 1px solid black;
                   8427:   width: 99%;
                   8428:   background: #FFFFFF;
                   8429: }
1.795     www      8430: 
1.613     albertel 8431: table.LC_scantron_action {
                   8432:   width: 100%;
                   8433: }
1.795     www      8434: 
1.613     albertel 8435: table.LC_scantron_action tr th {
1.698     harmsja  8436:   font-weight:bold;
                   8437:   font-style:normal;
1.613     albertel 8438: }
1.795     www      8439: 
1.779     bisitz   8440: .LC_edit_problem_header,
1.614     albertel 8441: div.LC_edit_problem_footer {
1.705     tempelho 8442:   font-weight: normal;
                   8443:   font-size:  medium;
1.602     albertel 8444:   margin: 2px;
1.1060    bisitz   8445:   background-color: $sidebg;
1.600     albertel 8446: }
1.795     www      8447: 
1.600     albertel 8448: div.LC_edit_problem_header,
1.602     albertel 8449: div.LC_edit_problem_header div,
1.614     albertel 8450: div.LC_edit_problem_footer,
                   8451: div.LC_edit_problem_footer div,
1.602     albertel 8452: div.LC_edit_problem_editxml_header,
                   8453: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8454:   z-index: 100;
1.600     albertel 8455: }
1.795     www      8456: 
1.600     albertel 8457: div.LC_edit_problem_header_title {
1.705     tempelho 8458:   font-weight: bold;
                   8459:   font-size: larger;
1.602     albertel 8460:   background: $tabbg;
                   8461:   padding: 3px;
1.1060    bisitz   8462:   margin: 0 0 5px 0;
1.602     albertel 8463: }
1.795     www      8464: 
1.602     albertel 8465: table.LC_edit_problem_header_title {
                   8466:   width: 100%;
1.600     albertel 8467:   background: $tabbg;
1.602     albertel 8468: }
                   8469: 
1.1205    golterma 8470: div.LC_edit_actionbar {
                   8471:     background-color: $sidebg;
1.1218    droeschl 8472:     margin: 0;
                   8473:     padding: 0;
                   8474:     line-height: 200%;
1.602     albertel 8475: }
1.795     www      8476: 
1.1218    droeschl 8477: div.LC_edit_actionbar div{
                   8478:     padding: 0;
                   8479:     margin: 0;
                   8480:     display: inline-block;
1.600     albertel 8481: }
1.795     www      8482: 
1.1124    bisitz   8483: .LC_edit_opt {
                   8484:   padding-left: 1em;
                   8485:   white-space: nowrap;
                   8486: }
                   8487: 
1.1152    golterma 8488: .LC_edit_problem_latexhelper{
                   8489:     text-align: right;
                   8490: }
                   8491: 
                   8492: #LC_edit_problem_colorful div{
                   8493:     margin-left: 40px;
                   8494: }
                   8495: 
1.1205    golterma 8496: #LC_edit_problem_codemirror div{
                   8497:     margin-left: 0px;
                   8498: }
                   8499: 
1.911     bisitz   8500: img.stift {
1.803     bisitz   8501:   border-width: 0;
                   8502:   vertical-align: middle;
1.677     riegler  8503: }
1.680     riegler  8504: 
1.923     bisitz   8505: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8506:   vertical-align: top;
1.777     tempelho 8507: }
1.795     www      8508: 
1.716     raeburn  8509: div.LC_createcourse {
1.911     bisitz   8510:   margin: 10px 10px 10px 10px;
1.716     raeburn  8511: }
                   8512: 
1.917     raeburn  8513: .LC_dccid {
1.1130    raeburn  8514:   float: right;
1.917     raeburn  8515:   margin: 0.2em 0 0 0;
                   8516:   padding: 0;
                   8517:   font-size: 90%;
                   8518:   display:none;
                   8519: }
                   8520: 
1.897     wenzelju 8521: ol.LC_primary_menu a:hover,
1.721     harmsja  8522: ol#LC_MenuBreadcrumbs a:hover,
                   8523: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8524: ul#LC_secondary_menu a:hover,
1.721     harmsja  8525: .LC_FormSectionClearButton input:hover
1.795     www      8526: ul.LC_TabContent   li:hover a {
1.952     onken    8527:   color:$button_hover;
1.911     bisitz   8528:   text-decoration:none;
1.693     droeschl 8529: }
                   8530: 
1.779     bisitz   8531: h1 {
1.911     bisitz   8532:   padding: 0;
                   8533:   line-height:130%;
1.693     droeschl 8534: }
1.698     harmsja  8535: 
1.911     bisitz   8536: h2,
                   8537: h3,
                   8538: h4,
                   8539: h5,
                   8540: h6 {
                   8541:   margin: 5px 0 5px 0;
                   8542:   padding: 0;
                   8543:   line-height:130%;
1.693     droeschl 8544: }
1.795     www      8545: 
                   8546: .LC_hcell {
1.911     bisitz   8547:   padding:3px 15px 3px 15px;
                   8548:   margin: 0;
                   8549:   background-color:$tabbg;
                   8550:   color:$fontmenu;
                   8551:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8552: }
1.795     www      8553: 
1.840     bisitz   8554: .LC_Box > .LC_hcell {
1.911     bisitz   8555:   margin: 0 -10px 10px -10px;
1.835     bisitz   8556: }
                   8557: 
1.721     harmsja  8558: .LC_noBorder {
1.911     bisitz   8559:   border: 0;
1.698     harmsja  8560: }
1.693     droeschl 8561: 
1.721     harmsja  8562: .LC_FormSectionClearButton input {
1.911     bisitz   8563:   background-color:transparent;
                   8564:   border: none;
                   8565:   cursor:pointer;
                   8566:   text-decoration:underline;
1.693     droeschl 8567: }
1.763     bisitz   8568: 
                   8569: .LC_help_open_topic {
1.911     bisitz   8570:   color: #FFFFFF;
                   8571:   background-color: #EEEEFF;
                   8572:   margin: 1px;
                   8573:   padding: 4px;
                   8574:   border: 1px solid #000033;
                   8575:   white-space: nowrap;
                   8576:   /* vertical-align: middle; */
1.759     neumanie 8577: }
1.693     droeschl 8578: 
1.911     bisitz   8579: dl,
                   8580: ul,
                   8581: div,
                   8582: fieldset {
                   8583:   margin: 10px 10px 10px 0;
                   8584:   /* overflow: hidden; */
1.693     droeschl 8585: }
1.795     www      8586: 
1.1404    raeburn  8587: fieldset#LC_selectuser {
                   8588:     margin: 0;
                   8589:     padding: 0;
                   8590: }
                   8591: 
1.1211    raeburn  8592: article.geogebraweb div {
                   8593:     margin: 0;
                   8594: }
                   8595: 
1.838     bisitz   8596: fieldset > legend {
1.911     bisitz   8597:   font-weight: bold;
                   8598:   padding: 0 5px 0 5px;
1.838     bisitz   8599: }
                   8600: 
1.813     bisitz   8601: #LC_nav_bar {
1.911     bisitz   8602:   float: left;
1.995     raeburn  8603:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8604:   margin: 0 0 2px 0;
1.807     droeschl 8605: }
                   8606: 
1.916     droeschl 8607: #LC_realm {
                   8608:   margin: 0.2em 0 0 0;
                   8609:   padding: 0;
                   8610:   font-weight: bold;
                   8611:   text-align: center;
1.995     raeburn  8612:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8613: }
                   8614: 
1.911     bisitz   8615: #LC_nav_bar em {
                   8616:   font-weight: bold;
                   8617:   font-style: normal;
1.807     droeschl 8618: }
                   8619: 
1.897     wenzelju 8620: ol.LC_primary_menu {
1.934     droeschl 8621:   margin: 0;
1.1076    raeburn  8622:   padding: 0;
1.807     droeschl 8623: }
                   8624: 
1.852     droeschl 8625: ol#LC_PathBreadcrumbs {
1.911     bisitz   8626:   margin: 0;
1.693     droeschl 8627: }
                   8628: 
1.897     wenzelju 8629: ol.LC_primary_menu li {
1.1076    raeburn  8630:   color: RGB(80, 80, 80);
                   8631:   vertical-align: middle;
                   8632:   text-align: left;
                   8633:   list-style: none;
1.1205    golterma 8634:   position: relative;
1.1076    raeburn  8635:   float: left;
1.1205    golterma 8636:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8637:   line-height: 1.5em;
1.1076    raeburn  8638: }
                   8639: 
1.1205    golterma 8640: ol.LC_primary_menu li a,
                   8641: ol.LC_primary_menu li p {
1.1076    raeburn  8642:   display: block;
                   8643:   margin: 0;
                   8644:   padding: 0 5px 0 10px;
                   8645:   text-decoration: none;
                   8646: }
                   8647: 
1.1205    golterma 8648: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8649:   display: inline-block;
                   8650:   width: 95%;
                   8651:   text-align: left;
                   8652: }
                   8653: 
                   8654: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8655:   display: inline-block;	
                   8656:   width: 5%;
                   8657:   float: right;
                   8658:   text-align: right;
                   8659:   font-size: 70%;
                   8660: }
                   8661: 
                   8662: ol.LC_primary_menu ul {
1.1076    raeburn  8663:   display: none;
1.1205    golterma 8664:   width: 15em;
1.1076    raeburn  8665:   background-color: $data_table_light;
1.1205    golterma 8666:   position: absolute;
                   8667:   top: 100%;
1.1076    raeburn  8668: }
                   8669: 
1.1205    golterma 8670: ol.LC_primary_menu ul ul {
                   8671:   left: 100%;
                   8672:   top: 0;
                   8673: }
                   8674: 
                   8675: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8676:   display: block;
                   8677:   position: absolute;
                   8678:   margin: 0;
                   8679:   padding: 0;
1.1078    raeburn  8680:   z-index: 2;
1.1076    raeburn  8681: }
                   8682: 
                   8683: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8684: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8685:   font-size: 90%;
1.911     bisitz   8686:   vertical-align: top;
1.1076    raeburn  8687:   float: none;
1.1079    raeburn  8688:   border-left: 1px solid black;
                   8689:   border-right: 1px solid black;
1.1205    golterma 8690: /* A dark bottom border to visualize different menu options; 
                   8691: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8692:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8693: }
                   8694: 
1.1205    golterma 8695: ol.LC_primary_menu li li p:hover {
                   8696:   color:$button_hover;
                   8697:   text-decoration:none;
                   8698:   background-color:$data_table_dark;
1.1076    raeburn  8699: }
                   8700: 
                   8701: ol.LC_primary_menu li li a:hover {
                   8702:    color:$button_hover;
                   8703:    background-color:$data_table_dark;
1.693     droeschl 8704: }
                   8705: 
1.1205    golterma 8706: /* Font-size equal to the size of the predecessors*/
                   8707: ol.LC_primary_menu li:hover li li {
                   8708:   font-size: 100%;
                   8709: }
                   8710: 
1.897     wenzelju 8711: ol.LC_primary_menu li img {
1.911     bisitz   8712:   vertical-align: bottom;
1.934     droeschl 8713:   height: 1.1em;
1.1077    raeburn  8714:   margin: 0.2em 0 0 0;
1.693     droeschl 8715: }
                   8716: 
1.897     wenzelju 8717: ol.LC_primary_menu a {
1.911     bisitz   8718:   color: RGB(80, 80, 80);
                   8719:   text-decoration: none;
1.693     droeschl 8720: }
1.795     www      8721: 
1.949     droeschl 8722: ol.LC_primary_menu a.LC_new_message {
                   8723:   font-weight:bold;
                   8724:   color: darkred;
                   8725: }
                   8726: 
1.975     raeburn  8727: ol.LC_docs_parameters {
                   8728:   margin-left: 0;
                   8729:   padding: 0;
                   8730:   list-style: none;
                   8731: }
                   8732: 
                   8733: ol.LC_docs_parameters li {
                   8734:   margin: 0;
                   8735:   padding-right: 20px;
                   8736:   display: inline;
                   8737: }
                   8738: 
1.976     raeburn  8739: ol.LC_docs_parameters li:before {
                   8740:   content: "\\002022 \\0020";
                   8741: }
                   8742: 
                   8743: li.LC_docs_parameters_title {
                   8744:   font-weight: bold;
                   8745: }
                   8746: 
                   8747: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8748:   content: "";
                   8749: }
                   8750: 
1.897     wenzelju 8751: ul#LC_secondary_menu {
1.1107    raeburn  8752:   clear: right;
1.911     bisitz   8753:   color: $fontmenu;
                   8754:   background: $tabbg;
                   8755:   list-style: none;
                   8756:   padding: 0;
                   8757:   margin: 0;
                   8758:   width: 100%;
1.995     raeburn  8759:   text-align: left;
1.1107    raeburn  8760:   float: left;
1.808     droeschl 8761: }
                   8762: 
1.897     wenzelju 8763: ul#LC_secondary_menu li {
1.911     bisitz   8764:   font-weight: bold;
                   8765:   line-height: 1.8em;
1.1107    raeburn  8766:   border-right: 1px solid black;
                   8767:   float: left;
                   8768: }
                   8769: 
                   8770: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8771:   background-color: $data_table_light;
                   8772: }
                   8773: 
                   8774: ul#LC_secondary_menu li a {
1.911     bisitz   8775:   padding: 0 0.8em;
1.1107    raeburn  8776: }
                   8777: 
                   8778: ul#LC_secondary_menu li ul {
                   8779:   display: none;
                   8780: }
                   8781: 
                   8782: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8783:   display: block;
                   8784:   position: absolute;
                   8785:   margin: 0;
                   8786:   padding: 0;
                   8787:   list-style:none;
                   8788:   float: none;
                   8789:   background-color: $data_table_light;
                   8790:   z-index: 2;
                   8791:   margin-left: -1px;
                   8792: }
                   8793: 
                   8794: ul#LC_secondary_menu li ul li {
                   8795:   font-size: 90%;
                   8796:   vertical-align: top;
                   8797:   border-left: 1px solid black;
1.911     bisitz   8798:   border-right: 1px solid black;
1.1119    raeburn  8799:   background-color: $data_table_light;
1.1107    raeburn  8800:   list-style:none;
                   8801:   float: none;
                   8802: }
                   8803: 
                   8804: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8805:   background-color: $data_table_dark;
1.807     droeschl 8806: }
                   8807: 
1.847     tempelho 8808: ul.LC_TabContent {
1.911     bisitz   8809:   display:block;
                   8810:   background: $sidebg;
                   8811:   border-bottom: solid 1px $lg_border_color;
                   8812:   list-style:none;
1.1020    raeburn  8813:   margin: -1px -10px 0 -10px;
1.911     bisitz   8814:   padding: 0;
1.693     droeschl 8815: }
                   8816: 
1.795     www      8817: ul.LC_TabContent li,
                   8818: ul.LC_TabContentBigger li {
1.911     bisitz   8819:   float:left;
1.741     harmsja  8820: }
1.795     www      8821: 
1.897     wenzelju 8822: ul#LC_secondary_menu li a {
1.911     bisitz   8823:   color: $fontmenu;
                   8824:   text-decoration: none;
1.693     droeschl 8825: }
1.795     www      8826: 
1.721     harmsja  8827: ul.LC_TabContent {
1.952     onken    8828:   min-height:20px;
1.721     harmsja  8829: }
1.795     www      8830: 
                   8831: ul.LC_TabContent li {
1.911     bisitz   8832:   vertical-align:middle;
1.959     onken    8833:   padding: 0 16px 0 10px;
1.911     bisitz   8834:   background-color:$tabbg;
                   8835:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8836:   border-left: solid 1px $font;
1.721     harmsja  8837: }
1.795     www      8838: 
1.847     tempelho 8839: ul.LC_TabContent .right {
1.911     bisitz   8840:   float:right;
1.847     tempelho 8841: }
                   8842: 
1.911     bisitz   8843: ul.LC_TabContent li a,
                   8844: ul.LC_TabContent li {
                   8845:   color:rgb(47,47,47);
                   8846:   text-decoration:none;
                   8847:   font-size:95%;
                   8848:   font-weight:bold;
1.952     onken    8849:   min-height:20px;
                   8850: }
                   8851: 
1.959     onken    8852: ul.LC_TabContent li a:hover,
                   8853: ul.LC_TabContent li a:focus {
1.952     onken    8854:   color: $button_hover;
1.959     onken    8855:   background:none;
                   8856:   outline:none;
1.952     onken    8857: }
                   8858: 
                   8859: ul.LC_TabContent li:hover {
                   8860:   color: $button_hover;
                   8861:   cursor:pointer;
1.721     harmsja  8862: }
1.795     www      8863: 
1.911     bisitz   8864: ul.LC_TabContent li.active {
1.952     onken    8865:   color: $font;
1.911     bisitz   8866:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8867:   border-bottom:solid 1px #FFFFFF;
                   8868:   cursor: default;
1.744     ehlerst  8869: }
1.795     www      8870: 
1.959     onken    8871: ul.LC_TabContent li.active a {
                   8872:   color:$font;
                   8873:   background:#FFFFFF;
                   8874:   outline: none;
                   8875: }
1.1047    raeburn  8876: 
                   8877: ul.LC_TabContent li.goback {
                   8878:   float: left;
                   8879:   border-left: none;
                   8880: }
                   8881: 
1.870     tempelho 8882: #maincoursedoc {
1.911     bisitz   8883:   clear:both;
1.870     tempelho 8884: }
                   8885: 
                   8886: ul.LC_TabContentBigger {
1.911     bisitz   8887:   display:block;
                   8888:   list-style:none;
                   8889:   padding: 0;
1.870     tempelho 8890: }
                   8891: 
1.795     www      8892: ul.LC_TabContentBigger li {
1.911     bisitz   8893:   vertical-align:bottom;
                   8894:   height: 30px;
                   8895:   font-size:110%;
                   8896:   font-weight:bold;
                   8897:   color: #737373;
1.841     tempelho 8898: }
                   8899: 
1.957     onken    8900: ul.LC_TabContentBigger li.active {
                   8901:   position: relative;
                   8902:   top: 1px;
                   8903: }
                   8904: 
1.870     tempelho 8905: ul.LC_TabContentBigger li a {
1.911     bisitz   8906:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8907:   height: 30px;
                   8908:   line-height: 30px;
                   8909:   text-align: center;
                   8910:   display: block;
                   8911:   text-decoration: none;
1.958     onken    8912:   outline: none;  
1.741     harmsja  8913: }
1.795     www      8914: 
1.870     tempelho 8915: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8916:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8917:   color:$font;
1.744     ehlerst  8918: }
1.795     www      8919: 
1.870     tempelho 8920: ul.LC_TabContentBigger li b {
1.911     bisitz   8921:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8922:   display: block;
                   8923:   float: left;
                   8924:   padding: 0 30px;
1.957     onken    8925:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8926: }
                   8927: 
1.956     onken    8928: ul.LC_TabContentBigger li:hover b {
                   8929:   color:$button_hover;
                   8930: }
                   8931: 
1.870     tempelho 8932: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8933:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8934:   color:$font;
1.957     onken    8935:   border: 0;
1.741     harmsja  8936: }
1.693     droeschl 8937: 
1.870     tempelho 8938: 
1.862     bisitz   8939: ul.LC_CourseBreadcrumbs {
                   8940:   background: $sidebg;
1.1020    raeburn  8941:   height: 2em;
1.862     bisitz   8942:   padding-left: 10px;
1.1020    raeburn  8943:   margin: 0;
1.862     bisitz   8944:   list-style-position: inside;
                   8945: }
                   8946: 
1.911     bisitz   8947: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8948: ol#LC_PathBreadcrumbs {
1.911     bisitz   8949:   padding-left: 10px;
                   8950:   margin: 0;
1.933     droeschl 8951:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8952: }
                   8953: 
1.911     bisitz   8954: ol#LC_MenuBreadcrumbs li,
                   8955: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8956: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8957:   display: inline;
1.933     droeschl 8958:   white-space: normal;  
1.693     droeschl 8959: }
                   8960: 
1.823     bisitz   8961: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8962: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8963:   text-decoration: none;
                   8964:   font-size:90%;
1.693     droeschl 8965: }
1.795     www      8966: 
1.969     droeschl 8967: ol#LC_MenuBreadcrumbs h1 {
                   8968:   display: inline;
                   8969:   font-size: 90%;
                   8970:   line-height: 2.5em;
                   8971:   margin: 0;
                   8972:   padding: 0;
                   8973: }
                   8974: 
1.795     www      8975: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8976:   text-decoration:none;
                   8977:   font-size:100%;
                   8978:   font-weight:bold;
1.693     droeschl 8979: }
1.795     www      8980: 
1.840     bisitz   8981: .LC_Box {
1.911     bisitz   8982:   border: solid 1px $lg_border_color;
                   8983:   padding: 0 10px 10px 10px;
1.746     neumanie 8984: }
1.795     www      8985: 
1.1020    raeburn  8986: .LC_DocsBox {
                   8987:   border: solid 1px $lg_border_color;
                   8988:   padding: 0 0 10px 10px;
                   8989: }
                   8990: 
1.795     www      8991: .LC_AboutMe_Image {
1.911     bisitz   8992:   float:left;
                   8993:   margin-right:10px;
1.747     neumanie 8994: }
1.795     www      8995: 
                   8996: .LC_Clear_AboutMe_Image {
1.911     bisitz   8997:   clear:left;
1.747     neumanie 8998: }
1.795     www      8999: 
1.721     harmsja  9000: dl.LC_ListStyleClean dt {
1.911     bisitz   9001:   padding-right: 5px;
                   9002:   display: table-header-group;
1.693     droeschl 9003: }
                   9004: 
1.721     harmsja  9005: dl.LC_ListStyleClean dd {
1.911     bisitz   9006:   display: table-row;
1.693     droeschl 9007: }
                   9008: 
1.721     harmsja  9009: .LC_ListStyleClean,
                   9010: .LC_ListStyleSimple,
                   9011: .LC_ListStyleNormal,
1.795     www      9012: .LC_ListStyleSpecial {
1.911     bisitz   9013:   /* display:block; */
                   9014:   list-style-position: inside;
                   9015:   list-style-type: none;
                   9016:   overflow: hidden;
                   9017:   padding: 0;
1.693     droeschl 9018: }
                   9019: 
1.721     harmsja  9020: .LC_ListStyleSimple li,
                   9021: .LC_ListStyleSimple dd,
                   9022: .LC_ListStyleNormal li,
                   9023: .LC_ListStyleNormal dd,
                   9024: .LC_ListStyleSpecial li,
1.795     www      9025: .LC_ListStyleSpecial dd {
1.911     bisitz   9026:   margin: 0;
                   9027:   padding: 5px 5px 5px 10px;
                   9028:   clear: both;
1.693     droeschl 9029: }
                   9030: 
1.721     harmsja  9031: .LC_ListStyleClean li,
                   9032: .LC_ListStyleClean dd {
1.911     bisitz   9033:   padding-top: 0;
                   9034:   padding-bottom: 0;
1.693     droeschl 9035: }
                   9036: 
1.721     harmsja  9037: .LC_ListStyleSimple dd,
1.795     www      9038: .LC_ListStyleSimple li {
1.911     bisitz   9039:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9040: }
                   9041: 
1.721     harmsja  9042: .LC_ListStyleSpecial li,
                   9043: .LC_ListStyleSpecial dd {
1.911     bisitz   9044:   list-style-type: none;
                   9045:   background-color: RGB(220, 220, 220);
                   9046:   margin-bottom: 4px;
1.693     droeschl 9047: }
                   9048: 
1.721     harmsja  9049: table.LC_SimpleTable {
1.911     bisitz   9050:   margin:5px;
                   9051:   border:solid 1px $lg_border_color;
1.795     www      9052: }
1.693     droeschl 9053: 
1.721     harmsja  9054: table.LC_SimpleTable tr {
1.911     bisitz   9055:   padding: 0;
                   9056:   border:solid 1px $lg_border_color;
1.693     droeschl 9057: }
1.795     www      9058: 
                   9059: table.LC_SimpleTable thead {
1.911     bisitz   9060:   background:rgb(220,220,220);
1.693     droeschl 9061: }
                   9062: 
1.721     harmsja  9063: div.LC_columnSection {
1.911     bisitz   9064:   display: block;
                   9065:   clear: both;
                   9066:   overflow: hidden;
                   9067:   margin: 0;
1.693     droeschl 9068: }
                   9069: 
1.721     harmsja  9070: div.LC_columnSection>* {
1.911     bisitz   9071:   float: left;
                   9072:   margin: 10px 20px 10px 0;
                   9073:   overflow:hidden;
1.693     droeschl 9074: }
1.721     harmsja  9075: 
1.795     www      9076: table em {
1.911     bisitz   9077:   font-weight: bold;
                   9078:   font-style: normal;
1.748     schulted 9079: }
1.795     www      9080: 
1.779     bisitz   9081: table.LC_tableBrowseRes,
1.795     www      9082: table.LC_tableOfContent {
1.911     bisitz   9083:   border:none;
                   9084:   border-spacing: 1px;
                   9085:   padding: 3px;
                   9086:   background-color: #FFFFFF;
                   9087:   font-size: 90%;
1.753     droeschl 9088: }
1.789     droeschl 9089: 
1.911     bisitz   9090: table.LC_tableOfContent {
                   9091:   border-collapse: collapse;
1.789     droeschl 9092: }
                   9093: 
1.771     droeschl 9094: table.LC_tableBrowseRes a,
1.768     schulted 9095: table.LC_tableOfContent a {
1.911     bisitz   9096:   background-color: transparent;
                   9097:   text-decoration: none;
1.753     droeschl 9098: }
                   9099: 
1.795     www      9100: table.LC_tableOfContent img {
1.911     bisitz   9101:   border: none;
                   9102:   height: 1.3em;
                   9103:   vertical-align: text-bottom;
                   9104:   margin-right: 0.3em;
1.753     droeschl 9105: }
1.757     schulted 9106: 
1.795     www      9107: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9108:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9109: }
                   9110: 
1.795     www      9111: a#LC_content_toolbar_everything {
1.911     bisitz   9112:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9113: }
                   9114: 
1.795     www      9115: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9116:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9117: }
                   9118: 
1.795     www      9119: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9120:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9121: }
                   9122: 
1.795     www      9123: a#LC_content_toolbar_changefolder {
1.911     bisitz   9124:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9125: }
                   9126: 
1.795     www      9127: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9128:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9129: }
                   9130: 
1.1043    raeburn  9131: a#LC_content_toolbar_edittoplevel {
                   9132:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9133: }
                   9134: 
1.1384    raeburn  9135: a#LC_content_toolbar_printout {
                   9136:   background-image:url(/res/adm/pages/printout.gif);
                   9137: }
                   9138: 
1.795     www      9139: ul#LC_toolbar li a:hover {
1.911     bisitz   9140:   background-position: bottom center;
1.757     schulted 9141: }
                   9142: 
1.795     www      9143: ul#LC_toolbar {
1.911     bisitz   9144:   padding: 0;
                   9145:   margin: 2px;
                   9146:   list-style:none;
1.1449  ! raeburn  9147:   display:inline;
1.911     bisitz   9148:   background-color:white;
1.1082    raeburn  9149:   overflow: auto;
1.757     schulted 9150: }
                   9151: 
1.795     www      9152: ul#LC_toolbar li {
1.911     bisitz   9153:   border:1px solid white;
                   9154:   padding: 0;
                   9155:   margin: 0;
                   9156:   float: left;
                   9157:   display:inline;
                   9158:   vertical-align:middle;
1.1082    raeburn  9159:   white-space: nowrap;
1.911     bisitz   9160: }
1.757     schulted 9161: 
1.783     amueller 9162: 
1.795     www      9163: a.LC_toolbarItem {
1.911     bisitz   9164:   display:block;
                   9165:   padding: 0;
                   9166:   margin: 0;
                   9167:   height: 32px;
                   9168:   width: 32px;
                   9169:   color:white;
                   9170:   border: none;
                   9171:   background-repeat:no-repeat;
                   9172:   background-color:transparent;
1.757     schulted 9173: }
                   9174: 
1.1449  ! raeburn  9175: .LC_navtools {
        !          9176:   display: inline-block;
        !          9177:   padding: 0;
        !          9178:   margin: 2px;
        !          9179:   vertical-align: middle;
        !          9180: }
        !          9181: 
1.915     droeschl 9182: ul.LC_funclist {
                   9183:     margin: 0;
                   9184:     padding: 0.5em 1em 0.5em 0;
                   9185: }
                   9186: 
1.933     droeschl 9187: ul.LC_funclist > li:first-child {
                   9188:     font-weight:bold; 
                   9189:     margin-left:0.8em;
                   9190: }
                   9191: 
1.915     droeschl 9192: ul.LC_funclist + ul.LC_funclist {
                   9193:     /* 
                   9194:        left border as a seperator if we have more than
                   9195:        one list 
                   9196:     */
                   9197:     border-left: 1px solid $sidebg;
                   9198:     /* 
                   9199:        this hides the left border behind the border of the 
                   9200:        outer box if element is wrapped to the next 'line' 
                   9201:     */
                   9202:     margin-left: -1px;
                   9203: }
                   9204: 
1.843     bisitz   9205: ul.LC_funclist li {
1.915     droeschl 9206:   display: inline;
1.782     bisitz   9207:   white-space: nowrap;
1.915     droeschl 9208:   margin: 0 0 0 25px;
                   9209:   line-height: 150%;
1.782     bisitz   9210: }
                   9211: 
1.974     wenzelju 9212: .LC_hidden {
                   9213:   display: none;
                   9214: }
                   9215: 
1.1030    www      9216: .LCmodal-overlay {
                   9217: 		position:fixed;
                   9218: 		top:0;
                   9219: 		right:0;
                   9220: 		bottom:0;
                   9221: 		left:0;
                   9222: 		height:100%;
                   9223: 		width:100%;
                   9224: 		margin:0;
                   9225: 		padding:0;
                   9226: 		background:#999;
                   9227: 		opacity:.75;
                   9228: 		filter: alpha(opacity=75);
                   9229: 		-moz-opacity: 0.75;
                   9230: 		z-index:101;
                   9231: }
                   9232: 
                   9233: * html .LCmodal-overlay {   
                   9234: 		position: absolute;
                   9235: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9236: }
                   9237: 
                   9238: .LCmodal-window {
                   9239: 		position:fixed;
                   9240: 		top:50%;
                   9241: 		left:50%;
                   9242: 		margin:0;
                   9243: 		padding:0;
                   9244: 		z-index:102;
                   9245: 	}
                   9246: 
                   9247: * html .LCmodal-window {
                   9248: 		position:absolute;
                   9249: }
                   9250: 
                   9251: .LCclose-window {
                   9252: 		position:absolute;
                   9253: 		width:32px;
                   9254: 		height:32px;
                   9255: 		right:8px;
                   9256: 		top:8px;
                   9257: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9258: 		text-indent:-99999px;
                   9259: 		overflow:hidden;
                   9260: 		cursor:pointer;
                   9261: }
                   9262: 
1.1369    raeburn  9263: .LCisDisabled {
                   9264:   cursor: not-allowed;
                   9265:   opacity: 0.5;
                   9266: }
                   9267: 
                   9268: a[aria-disabled="true"] {
                   9269:   color: currentColor;
                   9270:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9271:   pointer-events: none;
                   9272:   text-decoration: none;
                   9273: }
                   9274: 
1.1335    raeburn  9275: pre.LC_wordwrap {
                   9276:   white-space: pre-wrap;
                   9277:   white-space: -moz-pre-wrap;
                   9278:   white-space: -pre-wrap;
                   9279:   white-space: -o-pre-wrap;
                   9280:   word-wrap: break-word;
                   9281: }
                   9282: 
1.1100    raeburn  9283: /*
1.1231    damieng  9284:   styles used for response display
                   9285: */
                   9286: div.LC_radiofoil, div.LC_rankfoil {
                   9287:   margin: .5em 0em .5em 0em;
                   9288: }
                   9289: table.LC_itemgroup {
                   9290:   margin-top: 1em;
                   9291: }
                   9292: 
                   9293: /*
1.1100    raeburn  9294:   styles used by TTH when "Default set of options to pass to tth/m
                   9295:   when converting TeX" in course settings has been set
                   9296: 
                   9297:   option passed: -t
                   9298: 
                   9299: */
                   9300: 
                   9301: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9302: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9303: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9304: td div.norm {line-height:normal;}
                   9305: 
                   9306: /*
                   9307:   option passed -y3
                   9308: */
                   9309: 
                   9310: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9311: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9312: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9313: 
1.1230    damieng  9314: /*
                   9315:   sections with roles, for content only
                   9316: */
                   9317: section[class^="role-"] {
                   9318:   padding-left: 10px;
                   9319:   padding-right: 5px;
                   9320:   margin-top: 8px;
                   9321:   margin-bottom: 8px;
                   9322:   border: 1px solid #2A4;
                   9323:   border-radius: 5px;
                   9324:   box-shadow: 0px 1px 1px #BBB;
                   9325: }
                   9326: section[class^="role-"]>h1 {
                   9327:   position: relative;
                   9328:   margin: 0px;
                   9329:   padding-top: 10px;
                   9330:   padding-left: 40px;
                   9331: }
                   9332: section[class^="role-"]>h1:before {
                   9333:   position: absolute;
                   9334:   left: -5px;
                   9335:   top: 5px;
                   9336: }
                   9337: section.role-activity>h1:before {
                   9338:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9339: }
                   9340: section.role-advice>h1:before {
                   9341:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9342: }
                   9343: section.role-bibliography>h1:before {
                   9344:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9345: }
                   9346: section.role-citation>h1:before {
                   9347:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9348: }
                   9349: section.role-conclusion>h1:before {
                   9350:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9351: }
                   9352: section.role-definition>h1:before {
                   9353:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9354: }
                   9355: section.role-demonstration>h1:before {
                   9356:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9357: }
                   9358: section.role-example>h1:before {
                   9359:   content:url('/adm/daxe/images/section_icons/example.png');
                   9360: }
                   9361: section.role-explanation>h1:before {
                   9362:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9363: }
                   9364: section.role-introduction>h1:before {
                   9365:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9366: }
                   9367: section.role-method>h1:before {
                   9368:   content:url('/adm/daxe/images/section_icons/method.png');
                   9369: }
                   9370: section.role-more_information>h1:before {
                   9371:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9372: }
                   9373: section.role-objectives>h1:before {
                   9374:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9375: }
                   9376: section.role-prerequisites>h1:before {
                   9377:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9378: }
                   9379: section.role-remark>h1:before {
                   9380:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9381: }
                   9382: section.role-reminder>h1:before {
                   9383:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9384: }
                   9385: section.role-summary>h1:before {
                   9386:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9387: }
                   9388: section.role-syntax>h1:before {
                   9389:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9390: }
                   9391: section.role-warning>h1:before {
                   9392:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9393: }
                   9394: 
1.1269    raeburn  9395: #LC_minitab_header {
                   9396:   float:left;
                   9397:   width:100%;
                   9398:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9399:   font-size:93%;
                   9400:   line-height:normal;
                   9401:   margin: 0.5em 0 0.5em 0;
                   9402: }
                   9403: #LC_minitab_header ul {
                   9404:   margin:0;
                   9405:   padding:10px 10px 0;
                   9406:   list-style:none;
                   9407: }
                   9408: #LC_minitab_header li {
                   9409:   float:left;
                   9410:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9411:   margin:0;
                   9412:   padding:0 0 0 9px;
                   9413: }
                   9414: #LC_minitab_header a {
                   9415:   display:block;
                   9416:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9417:   padding:5px 15px 4px 6px;
                   9418: }
                   9419: #LC_minitab_header #LC_current_minitab {
                   9420:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9421: }
                   9422: #LC_minitab_header #LC_current_minitab a {
                   9423:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9424:   padding-bottom:5px;
                   9425: }
                   9426: 
                   9427: 
1.343     albertel 9428: END
                   9429: }
                   9430: 
1.306     albertel 9431: =pod
                   9432: 
                   9433: =item * &headtag()
                   9434: 
                   9435: Returns a uniform footer for LON-CAPA web pages.
                   9436: 
1.307     albertel 9437: Inputs: $title - optional title for the head
                   9438:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9439:         $args - optional arguments
1.319     albertel 9440:             force_register - if is true call registerurl so the remote is 
                   9441:                              informed
1.415     albertel 9442:             redirect       -> array ref of
                   9443:                                    1- seconds before redirect occurs
                   9444:                                    2- url to redirect to
                   9445:                                    3- whether the side effect should occur
1.315     albertel 9446:                            (side effect of setting 
                   9447:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9448:                                redirected to)
                   9449:                                    4- whether the redirect target should be
                   9450:                                       the opener of the current (pop-up)
                   9451:                                       window (side effect of setting
                   9452:                                       $env{'internal.head.to_opener'} to
                   9453:                                       1, if true.
1.1388    raeburn  9454:                                    5- whether encrypt check should be skipped
1.352     albertel 9455:             domain         -> force to color decorate a page for a specific
                   9456:                                domain
                   9457:             function       -> force usage of a specific rolish color scheme
                   9458:             bgcolor        -> override the default page bgcolor
1.460     albertel 9459:             no_auto_mt_title
                   9460:                            -> prevent &mt()ing the title arg
1.464     albertel 9461: 
1.306     albertel 9462: =cut
                   9463: 
                   9464: sub headtag {
1.313     albertel 9465:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9466:     
1.363     albertel 9467:     my $function = $args->{'function'} || &get_users_function();
                   9468:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9469:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9470:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9471:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9472: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9473: 		   #time(),
1.418     albertel 9474: 		   $env{'environment.color.timestamp'},
1.363     albertel 9475: 		   $function,$domain,$bgcolor);
                   9476: 
1.369     www      9477:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9478: 
1.308     albertel 9479:     my $result =
                   9480: 	'<head>'.
1.1160    raeburn  9481: 	&font_settings($args);
1.319     albertel 9482: 
1.1188    raeburn  9483:     my $inhibitprint;
                   9484:     if ($args->{'print_suppress'}) {
                   9485:         $inhibitprint = &print_suppression();
                   9486:     }
1.1064    raeburn  9487: 
1.1439    raeburn  9488:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9489: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9490:     }
1.962     droeschl 9491:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9492:         $result .= Apache::lonxml::display_title();
1.319     albertel 9493:     }
1.436     albertel 9494:     if (!$args->{'no_nav_bar'} 
                   9495: 	&& !$args->{'only_body'}
1.1438    raeburn  9496: 	&& !$args->{'frameset'}
                   9497: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9498: 	$result .= &help_menu_js($httphost);
1.1032    www      9499:         $result.=&modal_window();
1.1038    www      9500:         $result.=&togglebox_script();
1.1034    www      9501:         $result.=&wishlist_window();
1.1041    www      9502:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9503:     } else {
                   9504:         if ($args->{'add_modal'}) {
                   9505:            $result.=&modal_window();
                   9506:         }
                   9507:         if ($args->{'add_wishlist'}) {
                   9508:            $result.=&wishlist_window();
                   9509:         }
1.1038    www      9510:         if ($args->{'add_togglebox'}) {
                   9511:            $result.=&togglebox_script();
                   9512:         }
1.1041    www      9513:         if ($args->{'add_progressbar'}) {
                   9514:            $result.=&LCprogressbarUpdate_script();
                   9515:         }
1.436     albertel 9516:     }
1.314     albertel 9517:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9518: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9519:         if (!$skip_enc_check) {
                   9520:             $url = &Apache::lonenc::check_encrypt($url);
                   9521:         }
1.414     albertel 9522: 	if (!$inhibit_continue) {
                   9523: 	    $env{'internal.head.redirect'} = $url;
                   9524: 	}
1.1386    raeburn  9525: 	$result.=<<"ADDMETA";
1.313     albertel 9526: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9527: ADDMETA
                   9528:         if ($to_opener) {
                   9529:             $env{'internal.head.to_opener'} = 1;
                   9530:             my $dest = &js_escape($url);
                   9531:             my $timeout = int($time * 1000);
                   9532:             $result .=<<"ENDJS";
                   9533: <script type="text/javascript">
                   9534: // <![CDATA[
                   9535: function LC_To_Opener() {
                   9536:     var dest = '$dest';
                   9537:     if (dest != '') {
                   9538:         if (window.opener != null && !window.opener.closed) {
                   9539:             window.opener.location.href=dest;
                   9540:             window.close();
                   9541:         } else {
                   9542:             window.location.href=dest;
                   9543:         }
                   9544:     }
                   9545: }
                   9546: \$(document).ready(function () {
                   9547:     setTimeout('LC_To_Opener()',$timeout);
                   9548: });
                   9549: // ]]>
                   9550: </script>
                   9551: ENDJS
                   9552:         } else {
                   9553:             $result.=<<"ADDMETA";
1.344     albertel 9554: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9555: ADDMETA
1.1386    raeburn  9556:         }
1.1210    raeburn  9557:     } else {
                   9558:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9559:             my $requrl = $env{'request.uri'};
                   9560:             if ($requrl eq '') {
                   9561:                 $requrl = $ENV{'REQUEST_URI'};
                   9562:                 $requrl =~ s/\?.+$//;
                   9563:             }
                   9564:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9565:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9566:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9567:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9568:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9569:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9570:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9571:                     my ($offload,$offloadoth);
1.1210    raeburn  9572:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9573:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9574:                             $offload = 1;
1.1353    raeburn  9575:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9576:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9577:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9578:                                     $offloadoth = 1;
                   9579:                                     $dom_in_use = $env{'user.domain'};
                   9580:                                 }
                   9581:                             }
1.1340    raeburn  9582:                         }
                   9583:                     }
                   9584:                     unless ($offload) {
                   9585:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9586:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9587:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9588:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9589:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9590:                                         $offload = 1;
1.1352    raeburn  9591:                                         $offloadoth = 1;
1.1340    raeburn  9592:                                         $dom_in_use = $env{'user.domain'};
                   9593:                                     }
1.1210    raeburn  9594:                                 }
1.1340    raeburn  9595:                             }
                   9596:                         }
                   9597:                     }
                   9598:                     if ($offload) {
1.1358    raeburn  9599:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9600:                         if (($newserver eq '') && ($offloadoth)) {
                   9601:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9602:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9603:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9604:                             }
                   9605:                         }
1.1340    raeburn  9606:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9607:                             my $numsec = 5;
                   9608:                             my $timeout = $numsec * 1000;
                   9609:                             my ($newurl,$locknum,%locks,$msg);
                   9610:                             if ($env{'request.role.adv'}) {
                   9611:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9612:                             }
                   9613:                             my $disable_submit = 0;
                   9614:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9615:                                 $disable_submit = 1;
                   9616:                             }
                   9617:                             if ($locknum) {
                   9618:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9619:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9620:                                        join(", ",sort(values(%locks)))."\n";
                   9621:                                 if (&show_course()) {
                   9622:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9623:                                 } else {
                   9624:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9625:                                 }
1.1340    raeburn  9626:                             } else {
                   9627:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9628:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9629:                                 }
                   9630:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9631:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9632:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9633:                                     $newurl .= '&role='.$env{'request.role'};
                   9634:                                 }
                   9635:                                 if ($env{'request.symb'}) {
                   9636:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9637:                                     if ($shownsymb =~ m{^/enc/}) {
                   9638:                                         my $reqdmajor = 2;
                   9639:                                         my $reqdminor = 11;
                   9640:                                         my $reqdsubminor = 3;
                   9641:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9642:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9643:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9644:                                         if (($major eq '' && $minor eq '') ||
                   9645:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9646:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9647:                                              ($reqdsubminor > $subminor))))) {
                   9648:                                             undef($shownsymb);
                   9649:                                         }
1.1210    raeburn  9650:                                     }
1.1340    raeburn  9651:                                     if ($shownsymb) {
                   9652:                                         &js_escape(\$shownsymb);
                   9653:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9654:                                     }
1.1340    raeburn  9655:                                 } else {
                   9656:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9657:                                     &js_escape(\$shownurl);
                   9658:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9659:                                 }
1.1340    raeburn  9660:                             }
                   9661:                             &js_escape(\$msg);
                   9662:                             $result.=<<OFFLOAD
1.1210    raeburn  9663: <meta http-equiv="pragma" content="no-cache" />
                   9664: <script type="text/javascript">
1.1215    raeburn  9665: // <![CDATA[
1.1210    raeburn  9666: function LC_Offload_Now() {
                   9667:     var dest = "$newurl";
                   9668:     if (dest != '') {
                   9669:         window.location.href="$newurl";
                   9670:     }
                   9671: }
1.1214    raeburn  9672: \$(document).ready(function () {
                   9673:     window.alert('$msg');
                   9674:     if ($disable_submit) {
1.1210    raeburn  9675:         \$(".LC_hwk_submit").prop("disabled", true);
                   9676:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9677:     }
                   9678:     setTimeout('LC_Offload_Now()', $timeout);
                   9679: });
1.1215    raeburn  9680: // ]]>
1.1210    raeburn  9681: </script>
                   9682: OFFLOAD
                   9683:                         }
                   9684:                     }
                   9685:                 }
                   9686:             }
                   9687:         }
1.313     albertel 9688:     }
1.306     albertel 9689:     if (!defined($title)) {
                   9690: 	$title = 'The LearningOnline Network with CAPA';
                   9691:     }
1.460     albertel 9692:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9693:     if ($title =~ /^LON-CAPA\s+/) {
                   9694:         $result .= '<title> '.$title.'</title>';
                   9695:     } else {
                   9696:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9697:     }
                   9698:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9699:     if (!$args->{'frameset'}) {
                   9700:         $result .= ' /';
                   9701:     }
                   9702:     $result .= '>' 
1.1064    raeburn  9703:         .$inhibitprint
1.414     albertel 9704: 	.$head_extra;
1.1242    raeburn  9705:     my $clientmobile;
                   9706:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9707:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9708:     } else {
                   9709:         $clientmobile = $env{'browser.mobile'};
                   9710:     }
                   9711:     if ($clientmobile) {
1.1137    raeburn  9712:         $result .= '
1.1435    raeburn  9713: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9714: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9715:     }
1.1278    raeburn  9716:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9717:     return $result.'</head>';
1.306     albertel 9718: }
                   9719: 
                   9720: =pod
                   9721: 
1.340     albertel 9722: =item * &font_settings()
                   9723: 
                   9724: Returns neccessary <meta> to set the proper encoding
                   9725: 
1.1160    raeburn  9726: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9727: 
                   9728: =cut
                   9729: 
                   9730: sub font_settings {
1.1160    raeburn  9731:     my ($args) = @_;
1.340     albertel 9732:     my $headerstring='';
1.1160    raeburn  9733:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9734:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9735:         $headerstring.=
                   9736:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9737:         if (!$args->{'frameset'}) {
                   9738: 	    $headerstring.= ' /';
                   9739:         }
                   9740: 	$headerstring .= '>'."\n";
1.340     albertel 9741:     }
                   9742:     return $headerstring;
                   9743: }
                   9744: 
1.341     albertel 9745: =pod
                   9746: 
1.1064    raeburn  9747: =item * &print_suppression()
                   9748: 
                   9749: In course context returns css which causes the body to be blank when media="print",
                   9750: if printout generation is unavailable for the current resource.
                   9751: 
                   9752: This could be because:
                   9753: 
                   9754: (a) printstartdate is in the future
                   9755: 
                   9756: (b) printenddate is in the past
                   9757: 
                   9758: (c) there is an active exam block with "printout"
                   9759: functionality blocked
                   9760: 
                   9761: Users with pav, pfo or evb privileges are exempt.
                   9762: 
                   9763: Inputs: none
                   9764: 
                   9765: =cut
                   9766: 
                   9767: 
                   9768: sub print_suppression {
                   9769:     my $noprint;
                   9770:     if ($env{'request.course.id'}) {
                   9771:         my $scope = $env{'request.course.id'};
                   9772:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9773:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9774:             return;
                   9775:         }
                   9776:         if ($env{'request.course.sec'} ne '') {
                   9777:             $scope .= "/$env{'request.course.sec'}";
                   9778:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9779:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9780:                 return;
1.1064    raeburn  9781:             }
                   9782:         }
                   9783:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9784:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9785:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9786:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9787:         if ($blocked) {
                   9788:             my $checkrole = "cm./$cdom/$cnum";
                   9789:             if ($env{'request.course.sec'} ne '') {
                   9790:                 $checkrole .= "/$env{'request.course.sec'}";
                   9791:             }
                   9792:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9793:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9794:                 $noprint = 1;
                   9795:             }
                   9796:         }
                   9797:         unless ($noprint) {
                   9798:             my $symb = &Apache::lonnet::symbread();
                   9799:             if ($symb ne '') {
                   9800:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9801:                 if (ref($navmap)) {
                   9802:                     my $res = $navmap->getBySymb($symb);
                   9803:                     if (ref($res)) {
                   9804:                         if (!$res->resprintable()) {
                   9805:                             $noprint = 1;
                   9806:                         }
                   9807:                     }
                   9808:                 }
                   9809:             }
                   9810:         }
                   9811:         if ($noprint) {
                   9812:             return <<"ENDSTYLE";
                   9813: <style type="text/css" media="print">
                   9814:     body { display:none }
                   9815: </style>
                   9816: ENDSTYLE
                   9817:         }
                   9818:     }
                   9819:     return;
                   9820: }
                   9821: 
                   9822: =pod
                   9823: 
1.341     albertel 9824: =item * &xml_begin()
                   9825: 
                   9826: Returns the needed doctype and <html>
                   9827: 
                   9828: Inputs: none
                   9829: 
                   9830: =cut
                   9831: 
                   9832: sub xml_begin {
1.1168    raeburn  9833:     my ($is_frameset) = @_;
1.341     albertel 9834:     my $output='';
                   9835: 
                   9836:     if ($env{'browser.mathml'}) {
                   9837: 	$output='<?xml version="1.0"?>'
                   9838:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9839: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9840:             
                   9841: #	    .'<!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">] >'
                   9842: 	    .'<!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">'
                   9843:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9844: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9845:     } elsif ($is_frameset) {
                   9846:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9847:                 '<html>'."\n";
1.341     albertel 9848:     } else {
1.1168    raeburn  9849: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9850:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9851:     }
                   9852:     return $output;
                   9853: }
1.340     albertel 9854: 
                   9855: =pod
                   9856: 
1.306     albertel 9857: =item * &start_page()
                   9858: 
                   9859: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9860: 
1.648     raeburn  9861: Inputs:
                   9862: 
                   9863: =over 4
                   9864: 
                   9865: $title - optional title for the page
                   9866: 
                   9867: $head_extra - optional extra HTML to incude inside the <head>
                   9868: 
                   9869: $args - additional optional args supported are:
                   9870: 
                   9871: =over 8
                   9872: 
                   9873:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9874:                                     arg on
1.814     bisitz   9875:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9876:              add_entries    -> additional attributes to add to the  <body>
                   9877:              domain         -> force to color decorate a page for a 
1.317     albertel 9878:                                     specific domain
1.648     raeburn  9879:              function       -> force usage of a specific rolish color
1.317     albertel 9880:                                     scheme
1.648     raeburn  9881:              redirect       -> see &headtag()
                   9882:              bgcolor        -> override the default page bg color
                   9883:              js_ready       -> return a string ready for being used in 
1.317     albertel 9884:                                     a javascript writeln
1.648     raeburn  9885:              html_encode    -> return a string ready for being used in 
1.320     albertel 9886:                                     a html attribute
1.648     raeburn  9887:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9888:                                     $forcereg arg
1.648     raeburn  9889:              frameset       -> if true will start with a <frameset>
1.330     albertel 9890:                                     rather than <body>
1.648     raeburn  9891:              skip_phases    -> hash ref of 
1.338     albertel 9892:                                     head -> skip the <html><head> generation
                   9893:                                     body -> skip all <body> generation
1.648     raeburn  9894:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9895:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9896:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  9897:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9898:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9899:                                    to override those values, or add to them, specify the value to
                   9900:                                    include in the style attribute to include in the div tag by using
                   9901:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  9902:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9903:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9904:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9905:                                specific group
                   9906:              use_absolute   -> for request for external resource or syllabus, this
                   9907:                                will contain https://<hostname> if server uses
                   9908:                                https (as per hosts.tab), but request is for http
                   9909:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9910:              links_disabled -> Links in primary and secondary menus are disabled
                   9911:                                (Can enable them once page has loaded - see lonroles.pm
                   9912:                                for an example).
1.1380    raeburn  9913:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9914: 
1.648     raeburn  9915: =back
1.460     albertel 9916: 
1.648     raeburn  9917: =back
1.562     albertel 9918: 
1.306     albertel 9919: =cut
                   9920: 
                   9921: sub start_page {
1.309     albertel 9922:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9923:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9924: 
1.315     albertel 9925:     $env{'internal.start_page'}++;
1.1359    raeburn  9926:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9927: 
1.338     albertel 9928:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9929:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9930:     }
1.1316    raeburn  9931: 
                   9932:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9933:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9934:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9935:                 $args->{'no_primary_menu'} = 1;
                   9936:             }
                   9937:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9938:                 $args->{'no_inline_menu'} = 1;
                   9939:             }
                   9940:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9941:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9942:             }
                   9943:         } else {
                   9944:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9945:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9946:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9947:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9948:                     $args->{'no_primary_menu'} = 1;
                   9949:                 }
                   9950:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9951:                     $args->{'no_inline_menu'} = 1;
                   9952:                 }
                   9953:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9954:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9955:                 }
                   9956:             }
                   9957:         }
1.1316    raeburn  9958:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9959:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9960:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9961:     } elsif ($env{'request.course.id'}) {
                   9962:         my $expiretime=600;
                   9963:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9964:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9965:         }
                   9966:         my ($deeplinkmenu,$menuref);
                   9967:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9968:         if ($menucoll) {
                   9969:             if (ref($menuref) eq 'HASH') {
                   9970:                 %menu = %{$menuref};
                   9971:             }
                   9972:             if ($menu{'top'} eq 'n') {
                   9973:                 $args->{'no_primary_menu'} = 1;
                   9974:             }
                   9975:             if ($menu{'inline'} eq 'n') {
                   9976:                 unless (&Apache::lonnet::allowed('opa')) {
                   9977:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9978:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9979:                     my $crstype = &course_type();
                   9980:                     my $now = time;
                   9981:                     my $ccrole;
                   9982:                     if ($crstype eq 'Community') {
                   9983:                         $ccrole = 'co';
                   9984:                     } else {
                   9985:                         $ccrole = 'cc';
                   9986:                     }
                   9987:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9988:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9989:                         if ((($start) && ($start<0)) ||
                   9990:                             (($end) && ($end<$now))  ||
                   9991:                             (($start) && ($now<$start))) {
                   9992:                             $args->{'no_inline_menu'} = 1;
                   9993:                         }
                   9994:                     } else {
                   9995:                         $args->{'no_inline_menu'} = 1;
                   9996:                     }
                   9997:                 }
                   9998:             }
                   9999:         }
1.1316    raeburn  10000:     }
1.1359    raeburn  10001: 
1.1385    raeburn  10002:     my $showncrumbs;
1.338     albertel 10003:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   10004: 	if ($args->{'frameset'}) {
                   10005: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   10006: 						$args->{'add_entries'});
                   10007: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   10008:         } else {
                   10009:             $result .=
                   10010:                 &bodytag($title, 
                   10011:                          $args->{'function'},       $args->{'add_entries'},
                   10012:                          $args->{'only_body'},      $args->{'domain'},
                   10013:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  10014:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  10015:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   10016:                          \%menu,\$showncrumbs);
1.831     bisitz   10017:         }
1.330     albertel 10018:     }
1.338     albertel 10019: 
1.315     albertel 10020:     if ($args->{'js_ready'}) {
1.713     kaisler  10021: 		$result = &js_ready($result);
1.315     albertel 10022:     }
1.320     albertel 10023:     if ($args->{'html_encode'}) {
1.713     kaisler  10024: 		$result = &html_encode($result);
                   10025:     }
                   10026: 
1.813     bisitz   10027:     # Preparation for new and consistent functionlist at top of screen
                   10028:     # if ($args->{'functionlist'}) {
                   10029:     #            $result .= &build_functionlist();
                   10030:     #}
                   10031: 
1.964     droeschl 10032:     # Don't add anything more if only_body wanted or in const space
                   10033:     return $result if    $args->{'only_body'} 
                   10034:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   10035: 
                   10036:     #Breadcrumbs
1.758     kaisler  10037:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10038:         unless ($showncrumbs) {
1.758     kaisler  10039: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10040: 		#if any br links exists, add them to the breadcrumbs
                   10041: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10042: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10043: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10044: 			}
                   10045: 		}
1.1096    raeburn  10046:                 # if @advtools array contains items add then to the breadcrumbs
                   10047:                 if (@advtools > 0) {
                   10048:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10049:                 }
1.1272    raeburn  10050:                 my $menulink;
                   10051:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10052:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10053:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10054:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10055:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10056:                      (!$env{'request.role.adv'}))) {
                   10057:                     $menulink = 0;
                   10058:                 } else {
                   10059:                     undef($menulink);
                   10060:                 }
1.1385    raeburn  10061:                 my $linkprotout;
                   10062:                 if ($env{'request.deeplink.login'}) {
                   10063:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10064:                     if ($linkprotout) {
                   10065:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10066:                     }
                   10067:                 }
1.758     kaisler  10068: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10069: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10070: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10071:                                                                        '',$menulink,'',
                   10072:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10073:                 } else {
1.1437    raeburn  10074: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10075:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10076: 		}
1.1385    raeburn  10077:         }
1.320     albertel 10078:     }
1.315     albertel 10079:     return $result;
1.306     albertel 10080: }
                   10081: 
                   10082: sub end_page {
1.315     albertel 10083:     my ($args) = @_;
                   10084:     $env{'internal.end_page'}++;
1.330     albertel 10085:     my $result;
1.335     albertel 10086:     if ($args->{'discussion'}) {
                   10087: 	my ($target,$parser);
                   10088: 	if (ref($args->{'discussion'})) {
                   10089: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10090: 				$args->{'discussion'}{'parser'});
                   10091: 	}
                   10092: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10093:     }
1.330     albertel 10094:     if ($args->{'frameset'}) {
                   10095: 	$result .= '</frameset>';
                   10096:     } else {
1.635     raeburn  10097: 	$result .= &endbodytag($args);
1.330     albertel 10098:     }
1.1080    raeburn  10099:     unless ($args->{'notbody'}) {
                   10100:         $result .= "\n</html>";
                   10101:     }
1.330     albertel 10102: 
1.315     albertel 10103:     if ($args->{'js_ready'}) {
1.317     albertel 10104: 	$result = &js_ready($result);
1.315     albertel 10105:     }
1.335     albertel 10106: 
1.320     albertel 10107:     if ($args->{'html_encode'}) {
                   10108: 	$result = &html_encode($result);
                   10109:     }
1.335     albertel 10110: 
1.315     albertel 10111:     return $result;
                   10112: }
                   10113: 
1.1359    raeburn  10114: sub menucoll_in_effect {
                   10115:     my ($menucoll,$deeplinkmenu,%menu);
                   10116:     if ($env{'request.course.id'}) {
                   10117:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10118:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10119:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10120:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10121:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10122:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10123:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10124:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10125:                     if (ref($navmap)) {
                   10126:                         $deeplink = $navmap->get_mapparam(undef,
                   10127:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10128:                                                           '0.deeplink');
1.1370    raeburn  10129:                     } else {
                   10130:                         $check_login_symb = 1;
1.1362    raeburn  10131:                     }
                   10132:                 } else {
1.1370    raeburn  10133:                     my $symb = &Apache::lonnet::symbread();
                   10134:                     if ($symb) {
                   10135:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10136:                     } else {
                   10137:                         $check_login_symb = 1;
                   10138:                     }
1.1362    raeburn  10139:                 }
                   10140:             } else {
1.1370    raeburn  10141:                 $check_login_symb = 1;
                   10142:             }
                   10143:             if ($check_login_symb) {
1.1362    raeburn  10144:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10145:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10146:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10147:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10148:                     if (ref($navmap)) {
                   10149:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10150:                     }
                   10151:                 } else {
                   10152:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10153:                 }
                   10154:             }
1.1359    raeburn  10155:             if ($deeplink ne '') {
1.1378    raeburn  10156:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10157:                 if ($display =~ /^\d+$/) {
                   10158:                     $deeplinkmenu = 1;
                   10159:                     $menucoll = $display;
                   10160:                 }
                   10161:             }
                   10162:         }
                   10163:         if ($menucoll) {
                   10164:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10165:         }
                   10166:     }
                   10167:     return ($menucoll,$deeplinkmenu,\%menu);
                   10168: }
                   10169: 
1.1362    raeburn  10170: sub deeplink_login_symb {
                   10171:     my ($cnum,$cdom) = @_;
                   10172:     my $login_symb;
                   10173:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10174:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10175:     }
                   10176:     return $login_symb;
                   10177: }
                   10178: 
                   10179: sub symb_from_tinyurl {
                   10180:     my ($url,$cnum,$cdom) = @_;
                   10181:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10182:         my $key = $1;
                   10183:         my ($tinyurl,$login);
                   10184:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10185:         if (defined($cached)) {
                   10186:             $tinyurl = $result;
                   10187:         } else {
                   10188:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10189:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10190:             if ($currtiny{$key} ne '') {
                   10191:                 $tinyurl = $currtiny{$key};
                   10192:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10193:             }
1.1364    raeburn  10194:         }
                   10195:         if ($tinyurl ne '') {
                   10196:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10197:             if (wantarray) {
                   10198:                 return ($cnumreq,$symb);
                   10199:             } elsif ($cnumreq eq $cnum) {
                   10200:                 return $symb;
1.1362    raeburn  10201:             }
                   10202:         }
                   10203:     }
1.1364    raeburn  10204:     if (wantarray) {
                   10205:         return ();
                   10206:     } else {
                   10207:         return;
                   10208:     }
1.1362    raeburn  10209: }
                   10210: 
1.1405    raeburn  10211: sub usable_exttools {
                   10212:     my %tooltypes;
                   10213:     if ($env{'request.course.id'}) {
                   10214:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10215:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10216:                %tooltypes = (
                   10217:                              crs => 1,
                   10218:                              dom => 1,
                   10219:                             );
                   10220:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10221:                $tooltypes{'crs'} = 1;
                   10222:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10223:                $tooltypes{'dom'} = 1;
                   10224:            }
                   10225:         } else {
                   10226:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10227:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10228:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10229:             if ($crstype eq '') {
                   10230:                 $crstype = 'course';
                   10231:             }
                   10232:             if ($crstype eq 'course') {
                   10233:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10234:                     $crstype = 'official';
                   10235:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10236:                     $crstype = 'textbook';
                   10237:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10238:                     $crstype = 'lti';
                   10239:                 } else {
                   10240:                     $crstype = 'unofficial';
                   10241:                 }
                   10242:             }
                   10243:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10244:             if ($domdefaults{$crstype.'domexttool'}) {
                   10245:                 $tooltypes{'dom'} = 1;
                   10246:             }
                   10247:             if ($domdefaults{$crstype.'exttool'}) {
                   10248:                 $tooltypes{'crs'} = 1;
                   10249:             }
                   10250:         }
                   10251:     }
                   10252:     return %tooltypes;
                   10253: }
                   10254: 
1.1034    www      10255: sub wishlist_window {
                   10256:     return(<<'ENDWISHLIST');
1.1046    raeburn  10257: <script type="text/javascript">
1.1034    www      10258: // <![CDATA[
                   10259: // <!-- BEGIN LON-CAPA Internal
                   10260: function set_wishlistlink(title, path) {
                   10261:     if (!title) {
                   10262:         title = document.title;
                   10263:         title = title.replace(/^LON-CAPA /,'');
                   10264:     }
1.1175    raeburn  10265:     title = encodeURIComponent(title);
1.1203    raeburn  10266:     title = title.replace("'","\\\'");
1.1034    www      10267:     if (!path) {
                   10268:         path = location.pathname;
                   10269:     }
1.1175    raeburn  10270:     path = encodeURIComponent(path);
1.1203    raeburn  10271:     path = path.replace("'","\\\'");
1.1034    www      10272:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10273:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10274: }
                   10275: // END LON-CAPA Internal -->
                   10276: // ]]>
                   10277: </script>
                   10278: ENDWISHLIST
                   10279: }
                   10280: 
1.1030    www      10281: sub modal_window {
                   10282:     return(<<'ENDMODAL');
1.1046    raeburn  10283: <script type="text/javascript">
1.1030    www      10284: // <![CDATA[
                   10285: // <!-- BEGIN LON-CAPA Internal
                   10286: var modalWindow = {
                   10287: 	parent:"body",
                   10288: 	windowId:null,
                   10289: 	content:null,
                   10290: 	width:null,
                   10291: 	height:null,
                   10292: 	close:function()
                   10293: 	{
                   10294: 	        $(".LCmodal-window").remove();
                   10295: 	        $(".LCmodal-overlay").remove();
                   10296: 	},
                   10297: 	open:function()
                   10298: 	{
                   10299: 		var modal = "";
                   10300: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10301: 		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;\">";
                   10302: 		modal += this.content;
                   10303: 		modal += "</div>";	
                   10304: 
                   10305: 		$(this.parent).append(modal);
                   10306: 
                   10307: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10308: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10309: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10310: 	}
                   10311: };
1.1140    raeburn  10312: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10313: 	{
1.1266    raeburn  10314:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10315: 		modalWindow.windowId = "myModal";
                   10316: 		modalWindow.width = width;
                   10317: 		modalWindow.height = height;
1.1196    raeburn  10318: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10319: 		modalWindow.open();
1.1208    raeburn  10320: 	};
1.1030    www      10321: // END LON-CAPA Internal -->
                   10322: // ]]>
                   10323: </script>
                   10324: ENDMODAL
                   10325: }
                   10326: 
                   10327: sub modal_link {
1.1140    raeburn  10328:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10329:     unless ($width) { $width=480; }
                   10330:     unless ($height) { $height=400; }
1.1031    www      10331:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10332:     unless ($transparency) { $transparency='true'; }
                   10333: 
1.1074    raeburn  10334:     my $target_attr;
                   10335:     if (defined($target)) {
                   10336:         $target_attr = 'target="'.$target.'"';
                   10337:     }
                   10338:     return <<"ENDLINK";
1.1336    raeburn  10339: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10340: ENDLINK
1.1030    www      10341: }
                   10342: 
1.1032    www      10343: sub modal_adhoc_script {
1.1365    raeburn  10344:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10345:     my $mathjax;
                   10346:     if ($possmathjax) {
                   10347:         $mathjax = <<'ENDJAX';
                   10348:                if (typeof MathJax == 'object') {
                   10349:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10350:                }
                   10351: ENDJAX
                   10352:     }
1.1032    www      10353:     return (<<ENDADHOC);
1.1046    raeburn  10354: <script type="text/javascript">
1.1032    www      10355: // <![CDATA[
                   10356:         var $funcname = function()
                   10357:         {
                   10358:                 modalWindow.windowId = "myModal";
                   10359:                 modalWindow.width = $width;
                   10360:                 modalWindow.height = $height;
                   10361:                 modalWindow.content = '$content';
                   10362:                 modalWindow.open();
1.1365    raeburn  10363:                 $mathjax
1.1032    www      10364:         };  
                   10365: // ]]>
                   10366: </script>
                   10367: ENDADHOC
                   10368: }
                   10369: 
1.1041    www      10370: sub modal_adhoc_inner {
1.1365    raeburn  10371:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10372:     my $innerwidth=$width-20;
                   10373:     $content=&js_ready(
1.1140    raeburn  10374:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10375:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10376:                  $content.
1.1041    www      10377:                  &end_scrollbox().
1.1140    raeburn  10378:                  &end_page()
1.1041    www      10379:              );
1.1365    raeburn  10380:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10381: }
                   10382: 
                   10383: sub modal_adhoc_window {
1.1365    raeburn  10384:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10385:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10386:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10387: }
                   10388: 
                   10389: sub modal_adhoc_launch {
                   10390:     my ($funcname,$width,$height,$content)=@_;
                   10391:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10392: <script type="text/javascript">
                   10393: // <![CDATA[
                   10394: $funcname();
                   10395: // ]]>
                   10396: </script>
                   10397: ENDLAUNCH
                   10398: }
                   10399: 
                   10400: sub modal_adhoc_close {
                   10401:     return (<<ENDCLOSE);
                   10402: <script type="text/javascript">
                   10403: // <![CDATA[
                   10404: modalWindow.close();
                   10405: // ]]>
                   10406: </script>
                   10407: ENDCLOSE
                   10408: }
                   10409: 
1.1038    www      10410: sub togglebox_script {
                   10411:    return(<<ENDTOGGLE);
                   10412: <script type="text/javascript"> 
                   10413: // <![CDATA[
                   10414: function LCtoggleDisplay(id,hidetext,showtext) {
                   10415:    link = document.getElementById(id + "link").childNodes[0];
                   10416:    with (document.getElementById(id).style) {
                   10417:       if (display == "none" ) {
                   10418:           display = "inline";
                   10419:           link.nodeValue = hidetext;
                   10420:         } else {
                   10421:           display = "none";
                   10422:           link.nodeValue = showtext;
                   10423:        }
                   10424:    }
                   10425: }
                   10426: // ]]>
                   10427: </script>
                   10428: ENDTOGGLE
                   10429: }
                   10430: 
1.1039    www      10431: sub start_togglebox {
                   10432:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10433:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10434:     unless ($showtext) { $showtext=&mt('show'); }
                   10435:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10436:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10437:     return &start_data_table().
                   10438:            &start_data_table_header_row().
                   10439:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10440:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10441:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10442:            &end_data_table_header_row().
                   10443:            '<tr id="'.$id.'" style="display:none""><td>';
                   10444: }
                   10445: 
                   10446: sub end_togglebox {
                   10447:     return '</td></tr>'.&end_data_table();
                   10448: }
                   10449: 
1.1041    www      10450: sub LCprogressbar_script {
1.1302    raeburn  10451:    my ($id,$number_to_do)=@_;
                   10452:    if ($number_to_do) {
                   10453:        return(<<ENDPROGRESS);
1.1041    www      10454: <script type="text/javascript">
                   10455: // <![CDATA[
1.1045    www      10456: \$('#progressbar$id').progressbar({
1.1041    www      10457:   value: 0,
                   10458:   change: function(event, ui) {
                   10459:     var newVal = \$(this).progressbar('option', 'value');
                   10460:     \$('.pblabel', this).text(LCprogressTxt);
                   10461:   }
                   10462: });
                   10463: // ]]>
                   10464: </script>
                   10465: ENDPROGRESS
1.1302    raeburn  10466:    } else {
                   10467:        return(<<ENDPROGRESS);
                   10468: <script type="text/javascript">
                   10469: // <![CDATA[
                   10470: \$('#progressbar$id').progressbar({
                   10471:   value: false,
                   10472:   create: function(event, ui) {
                   10473:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10474:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10475:   }
                   10476: });
                   10477: // ]]>
                   10478: </script>
                   10479: ENDPROGRESS
                   10480:    }
1.1041    www      10481: }
                   10482: 
                   10483: sub LCprogressbarUpdate_script {
                   10484:    return(<<ENDPROGRESSUPDATE);
                   10485: <style type="text/css">
                   10486: .ui-progressbar { position:relative; }
1.1302    raeburn  10487: .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      10488: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10489: </style>
                   10490: <script type="text/javascript">
                   10491: // <![CDATA[
1.1045    www      10492: var LCprogressTxt='---';
                   10493: 
1.1302    raeburn  10494: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10495:    LCprogressTxt=progresstext;
1.1302    raeburn  10496:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10497:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10498:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10499:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10500:    } else {
                   10501:        \$('#progressbar'+id).progressbar('value',percent);
                   10502:    }
1.1041    www      10503: }
                   10504: // ]]>
                   10505: </script>
                   10506: ENDPROGRESSUPDATE
                   10507: }
                   10508: 
1.1042    www      10509: my $LClastpercent;
1.1045    www      10510: my $LCidcnt;
                   10511: my $LCcurrentid;
1.1042    www      10512: 
1.1041    www      10513: sub LCprogressbar {
1.1302    raeburn  10514:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10515:     $LClastpercent=0;
1.1045    www      10516:     $LCidcnt++;
                   10517:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10518:     my ($starting,$content);
                   10519:     if ($number_to_do) {
                   10520:         $starting=&mt('Starting');
                   10521:         $content=(<<ENDPROGBAR);
                   10522: $preamble
1.1045    www      10523:   <div id="progressbar$LCcurrentid">
1.1041    www      10524:     <span class="pblabel">$starting</span>
                   10525:   </div>
                   10526: ENDPROGBAR
1.1302    raeburn  10527:     } else {
                   10528:         $starting=&mt('Loading...');
                   10529:         $LClastpercent='false';
                   10530:         $content=(<<ENDPROGBAR);
                   10531: $preamble
                   10532:   <div id="progressbar$LCcurrentid">
                   10533:       <div class="progress-label">$starting</div>
                   10534:   </div>
                   10535: ENDPROGBAR
                   10536:     }
                   10537:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10538: }
                   10539: 
                   10540: sub LCprogressbarUpdate {
1.1302    raeburn  10541:     my ($r,$val,$text,$number_to_do)=@_;
                   10542:     if ($number_to_do) {
                   10543:         unless ($val) { 
                   10544:             if ($LClastpercent) {
                   10545:                 $val=$LClastpercent;
                   10546:             } else {
                   10547:                 $val=0;
                   10548:             }
                   10549:         }
                   10550:         if ($val<0) { $val=0; }
                   10551:         if ($val>100) { $val=0; }
                   10552:         $LClastpercent=$val;
                   10553:         unless ($text) { $text=$val.'%'; }
                   10554:     } else {
                   10555:         $val = 'false';
1.1042    www      10556:     }
1.1041    www      10557:     $text=&js_ready($text);
1.1044    www      10558:     &r_print($r,<<ENDUPDATE);
1.1041    www      10559: <script type="text/javascript">
                   10560: // <![CDATA[
1.1302    raeburn  10561: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10562: // ]]>
                   10563: </script>
                   10564: ENDUPDATE
1.1035    www      10565: }
                   10566: 
1.1042    www      10567: sub LCprogressbarClose {
                   10568:     my ($r)=@_;
                   10569:     $LClastpercent=0;
1.1044    www      10570:     &r_print($r,<<ENDCLOSE);
1.1042    www      10571: <script type="text/javascript">
                   10572: // <![CDATA[
1.1045    www      10573: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10574: // ]]>
                   10575: </script>
                   10576: ENDCLOSE
1.1044    www      10577: }
                   10578: 
                   10579: sub r_print {
                   10580:     my ($r,$to_print)=@_;
                   10581:     if ($r) {
                   10582:       $r->print($to_print);
                   10583:       $r->rflush();
                   10584:     } else {
                   10585:       print($to_print);
                   10586:     }
1.1042    www      10587: }
                   10588: 
1.320     albertel 10589: sub html_encode {
                   10590:     my ($result) = @_;
                   10591: 
1.322     albertel 10592:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10593:     
                   10594:     return $result;
                   10595: }
1.1044    www      10596: 
1.317     albertel 10597: sub js_ready {
                   10598:     my ($result) = @_;
                   10599: 
1.323     albertel 10600:     $result =~ s/[\n\r]/ /xmsg;
                   10601:     $result =~ s/\\/\\\\/xmsg;
                   10602:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10603:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10604:     
                   10605:     return $result;
                   10606: }
                   10607: 
1.315     albertel 10608: sub validate_page {
                   10609:     if (  exists($env{'internal.start_page'})
1.316     albertel 10610: 	  &&     $env{'internal.start_page'} > 1) {
                   10611: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10612: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10613: 				 $ENV{'request.filename'});
1.315     albertel 10614:     }
                   10615:     if (  exists($env{'internal.end_page'})
1.316     albertel 10616: 	  &&     $env{'internal.end_page'} > 1) {
                   10617: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10618: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10619: 				 $env{'request.filename'});
1.315     albertel 10620:     }
                   10621:     if (     exists($env{'internal.start_page'})
                   10622: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10623: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10624: 				 $env{'request.filename'});
1.315     albertel 10625:     }
                   10626:     if (   ! exists($env{'internal.start_page'})
                   10627: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10628: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10629: 				 $env{'request.filename'});
1.315     albertel 10630:     }
1.306     albertel 10631: }
1.315     albertel 10632: 
1.996     www      10633: 
                   10634: sub start_scrollbox {
1.1140    raeburn  10635:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10636:     unless ($outerwidth) { $outerwidth='520px'; }
                   10637:     unless ($width) { $width='500px'; }
                   10638:     unless ($height) { $height='200px'; }
1.1075    raeburn  10639:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10640:     if ($id ne '') {
1.1140    raeburn  10641:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10642:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10643:     }
1.1075    raeburn  10644:     if ($bgcolor ne '') {
                   10645:         $tdcol = "background-color: $bgcolor;";
                   10646:     }
1.1137    raeburn  10647:     my $nicescroll_js;
                   10648:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10649:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10650:     }
                   10651:     return <<"END";
                   10652: $nicescroll_js
                   10653: 
                   10654: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10655: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10656: END
                   10657: }
                   10658: 
                   10659: sub end_scrollbox {
                   10660:     return '</div></td></tr></table>';
                   10661: }
                   10662: 
                   10663: sub nicescroll_javascript {
                   10664:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10665:     my %options;
                   10666:     if (ref($cursor) eq 'HASH') {
                   10667:         %options = %{$cursor};
                   10668:     }
                   10669:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10670:         $options{'railalign'} = 'left';
                   10671:     }
                   10672:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10673:         my $function  = &get_users_function();
                   10674:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10675:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10676:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10677:         }
1.1140    raeburn  10678:     }
                   10679:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10680:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10681:             $options{'cursoropacity'}='1.0';
                   10682:         }
1.1140    raeburn  10683:     } else {
                   10684:         $options{'cursoropacity'}='1.0';
                   10685:     }
                   10686:     if ($options{'cursorfixedheight'} eq 'none') {
                   10687:         delete($options{'cursorfixedheight'});
                   10688:     } else {
                   10689:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10690:     }
                   10691:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10692:         delete($options{'railoffset'});
                   10693:     }
                   10694:     my @niceoptions;
                   10695:     while (my($key,$value) = each(%options)) {
                   10696:         if ($value =~ /^\{.+\}$/) {
                   10697:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10698:         } else {
1.1140    raeburn  10699:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10700:         }
1.1140    raeburn  10701:     }
                   10702:     my $nicescroll_js = '
1.1137    raeburn  10703: $(document).ready(
1.1140    raeburn  10704:       function() {
                   10705:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10706:       }
1.1137    raeburn  10707: );
                   10708: ';
1.1140    raeburn  10709:     if ($framecheck) {
                   10710:         $nicescroll_js .= '
                   10711: function expand_div(caller) {
                   10712:     if (top === self) {
                   10713:         document.getElementById("'.$id.'").style.width = "auto";
                   10714:         document.getElementById("'.$id.'").style.height = "auto";
                   10715:     } else {
                   10716:         try {
                   10717:             if (parent.frames) {
                   10718:                 if (parent.frames.length > 1) {
                   10719:                     var framesrc = parent.frames[1].location.href;
                   10720:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10721:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10722:                         document.getElementById("'.$id.'").style.width = "auto";
                   10723:                         document.getElementById("'.$id.'").style.height = "auto";
                   10724:                     }
                   10725:                 }
                   10726:             }
                   10727:         } catch (e) {
                   10728:             return;
                   10729:         }
1.1137    raeburn  10730:     }
1.1140    raeburn  10731:     return;
1.996     www      10732: }
1.1140    raeburn  10733: ';
                   10734:     }
                   10735:     if ($needjsready) {
                   10736:         $nicescroll_js = '
                   10737: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10738:     } else {
                   10739:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10740:     }
                   10741:     return $nicescroll_js;
1.996     www      10742: }
                   10743: 
1.318     albertel 10744: sub simple_error_page {
1.1150    bisitz   10745:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10746:     my %displayargs;
1.1151    raeburn  10747:     if (ref($args) eq 'HASH') {
                   10748:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10749:         if ($args->{'only_body'}) {
                   10750:             $displayargs{'only_body'} = 1;
                   10751:         }
                   10752:         if ($args->{'no_nav_bar'}) {
                   10753:             $displayargs{'no_nav_bar'} = 1;
                   10754:         }
1.1151    raeburn  10755:     } else {
                   10756:         $msg = &mt($msg);
                   10757:     }
1.1150    bisitz   10758: 
1.318     albertel 10759:     my $page =
1.1304    raeburn  10760: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10761: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10762: 	&Apache::loncommon::end_page();
                   10763:     if (ref($r)) {
                   10764: 	$r->print($page);
1.327     albertel 10765: 	return;
1.318     albertel 10766:     }
                   10767:     return $page;
                   10768: }
1.347     albertel 10769: 
                   10770: {
1.610     albertel 10771:     my @row_count;
1.961     onken    10772: 
                   10773:     sub start_data_table_count {
                   10774:         unshift(@row_count, 0);
                   10775:         return;
                   10776:     }
                   10777: 
                   10778:     sub end_data_table_count {
                   10779:         shift(@row_count);
                   10780:         return;
                   10781:     }
                   10782: 
1.347     albertel 10783:     sub start_data_table {
1.1018    raeburn  10784: 	my ($add_class,$id) = @_;
1.422     albertel 10785: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10786:         my $table_id;
                   10787:         if (defined($id)) {
                   10788:             $table_id = ' id="'.$id.'"';
                   10789:         }
1.961     onken    10790: 	&start_data_table_count();
1.1018    raeburn  10791: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10792:     }
                   10793: 
                   10794:     sub end_data_table {
1.961     onken    10795: 	&end_data_table_count();
1.389     albertel 10796: 	return '</table>'."\n";;
1.347     albertel 10797:     }
                   10798: 
                   10799:     sub start_data_table_row {
1.974     wenzelju 10800: 	my ($add_class, $id) = @_;
1.610     albertel 10801: 	$row_count[0]++;
                   10802: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10803: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10804:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10805:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10806:     }
1.471     banghart 10807:     
                   10808:     sub continue_data_table_row {
1.974     wenzelju 10809: 	my ($add_class, $id) = @_;
1.610     albertel 10810: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10811: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10812:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10813:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10814:     }
1.347     albertel 10815: 
                   10816:     sub end_data_table_row {
1.389     albertel 10817: 	return '</tr>'."\n";;
1.347     albertel 10818:     }
1.367     www      10819: 
1.421     albertel 10820:     sub start_data_table_empty_row {
1.707     bisitz   10821: #	$row_count[0]++;
1.421     albertel 10822: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10823:     }
                   10824: 
                   10825:     sub end_data_table_empty_row {
                   10826: 	return '</tr>'."\n";;
                   10827:     }
                   10828: 
1.367     www      10829:     sub start_data_table_header_row {
1.389     albertel 10830: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10831:     }
                   10832: 
                   10833:     sub end_data_table_header_row {
1.389     albertel 10834: 	return '</tr>'."\n";;
1.367     www      10835:     }
1.890     droeschl 10836: 
                   10837:     sub data_table_caption {
                   10838:         my $caption = shift;
                   10839:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10840:     }
1.347     albertel 10841: }
                   10842: 
1.548     albertel 10843: =pod
                   10844: 
                   10845: =item * &inhibit_menu_check($arg)
                   10846: 
                   10847: Checks for a inhibitmenu state and generates output to preserve it
                   10848: 
                   10849: Inputs:         $arg - can be any of
                   10850:                      - undef - in which case the return value is a string 
                   10851:                                to add  into arguments list of a uri
                   10852:                      - 'input' - in which case the return value is a HTML
                   10853:                                  <form> <input> field of type hidden to
                   10854:                                  preserve the value
                   10855:                      - a url - in which case the return value is the url with
                   10856:                                the neccesary cgi args added to preserve the
                   10857:                                inhibitmenu state
                   10858:                      - a ref to a url - no return value, but the string is
                   10859:                                         updated to include the neccessary cgi
                   10860:                                         args to preserve the inhibitmenu state
                   10861: 
                   10862: =cut
                   10863: 
                   10864: sub inhibit_menu_check {
                   10865:     my ($arg) = @_;
                   10866:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10867:     if ($arg eq 'input') {
                   10868: 	if ($env{'form.inhibitmenu'}) {
                   10869: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10870: 	} else {
                   10871: 	    return
                   10872: 	}
                   10873:     }
                   10874:     if ($env{'form.inhibitmenu'}) {
                   10875: 	if (ref($arg)) {
                   10876: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10877: 	} elsif ($arg eq '') {
                   10878: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10879: 	} else {
                   10880: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10881: 	}
                   10882:     }
                   10883:     if (!ref($arg)) {
                   10884: 	return $arg;
                   10885:     }
                   10886: }
                   10887: 
1.251     albertel 10888: ###############################################
1.182     matthew  10889: 
                   10890: =pod
                   10891: 
1.549     albertel 10892: =back
                   10893: 
                   10894: =head1 User Information Routines
                   10895: 
                   10896: =over 4
                   10897: 
1.405     albertel 10898: =item * &get_users_function()
1.182     matthew  10899: 
                   10900: Used by &bodytag to determine the current users primary role.
                   10901: Returns either 'student','coordinator','admin', or 'author'.
                   10902: 
                   10903: =cut
                   10904: 
                   10905: ###############################################
                   10906: sub get_users_function {
1.815     tempelho 10907:     my $function = 'norole';
1.818     tempelho 10908:     if ($env{'request.role'}=~/^(st)/) {
                   10909:         $function='student';
                   10910:     }
1.907     raeburn  10911:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10912:         $function='coordinator';
                   10913:     }
1.258     albertel 10914:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10915:         $function='admin';
                   10916:     }
1.826     bisitz   10917:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10918:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10919:         $function='author';
                   10920:     }
                   10921:     return $function;
1.54      www      10922: }
1.99      www      10923: 
                   10924: ###############################################
                   10925: 
1.233     raeburn  10926: =pod
                   10927: 
1.821     raeburn  10928: =item * &show_course()
                   10929: 
                   10930: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10931: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10932: 
                   10933: Inputs:
                   10934: None
                   10935: 
                   10936: Outputs:
                   10937: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10938: 
                   10939: =cut
                   10940: 
                   10941: ###############################################
                   10942: sub show_course {
1.1408    raeburn  10943:     my ($udom,$uname) = @_;
                   10944:     if (($udom ne '') && ($uname ne '')) {
                   10945:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10946:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10947:                 return 0;
                   10948:             } else {
                   10949:                 return 1;
                   10950:             }
                   10951:         }
                   10952:     }
1.821     raeburn  10953:     my $course = !$env{'user.adv'};
                   10954:     if (!$env{'user.adv'}) {
                   10955:         foreach my $env (keys(%env)) {
                   10956:             next if ($env !~ m/^user\.priv\./);
                   10957:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10958:                 $course = 0;
                   10959:                 last;
                   10960:             }
                   10961:         }
                   10962:     }
                   10963:     return $course;
                   10964: }
                   10965: 
                   10966: ###############################################
                   10967: 
                   10968: =pod
                   10969: 
1.542     raeburn  10970: =item * &check_user_status()
1.274     raeburn  10971: 
                   10972: Determines current status of supplied role for a
                   10973: specific user. Roles can be active, previous or future.
                   10974: 
                   10975: Inputs: 
                   10976: user's domain, user's username, course's domain,
1.375     raeburn  10977: course's number, optional section ID.
1.274     raeburn  10978: 
                   10979: Outputs:
                   10980: role status: active, previous or future. 
                   10981: 
                   10982: =cut
                   10983: 
                   10984: sub check_user_status {
1.412     raeburn  10985:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10986:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10987:     my @uroles = keys(%userinfo);
1.274     raeburn  10988:     my $srchstr;
                   10989:     my $active_chk = 'none';
1.412     raeburn  10990:     my $now = time;
1.274     raeburn  10991:     if (@uroles > 0) {
1.908     raeburn  10992:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10993:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10994:         } else {
1.412     raeburn  10995:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10996:         }
                   10997:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10998:             my $role_end = 0;
                   10999:             my $role_start = 0;
                   11000:             $active_chk = 'active';
1.412     raeburn  11001:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   11002:                 $role_end = $1;
                   11003:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   11004:                     $role_start = $1;
1.274     raeburn  11005:                 }
                   11006:             }
                   11007:             if ($role_start > 0) {
1.412     raeburn  11008:                 if ($now < $role_start) {
1.274     raeburn  11009:                     $active_chk = 'future';
                   11010:                 }
                   11011:             }
                   11012:             if ($role_end > 0) {
1.412     raeburn  11013:                 if ($now > $role_end) {
1.274     raeburn  11014:                     $active_chk = 'previous';
                   11015:                 }
                   11016:             }
                   11017:         }
                   11018:     }
                   11019:     return $active_chk;
                   11020: }
                   11021: 
                   11022: ###############################################
                   11023: 
                   11024: =pod
                   11025: 
1.405     albertel 11026: =item * &get_sections()
1.233     raeburn  11027: 
                   11028: Determines all the sections for a course including
                   11029: sections with students and sections containing other roles.
1.419     raeburn  11030: Incoming parameters: 
                   11031: 
                   11032: 1. domain
                   11033: 2. course number 
                   11034: 3. reference to array containing roles for which sections should 
                   11035: be gathered (optional).
                   11036: 4. reference to array containing status types for which sections 
                   11037: should be gathered (optional).
                   11038: 
                   11039: If the third argument is undefined, sections are gathered for any role. 
                   11040: If the fourth argument is undefined, sections are gathered for any status.
                   11041: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11042:  
1.374     raeburn  11043: Returns section hash (keys are section IDs, values are
                   11044: number of users in each section), subject to the
1.419     raeburn  11045: optional roles filter, optional status filter 
1.233     raeburn  11046: 
                   11047: =cut
                   11048: 
                   11049: ###############################################
                   11050: sub get_sections {
1.419     raeburn  11051:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11052:     if (!defined($cdom) || !defined($cnum)) {
                   11053:         my $cid =  $env{'request.course.id'};
                   11054: 
                   11055: 	return if (!defined($cid));
                   11056: 
                   11057:         $cdom = $env{'course.'.$cid.'.domain'};
                   11058:         $cnum = $env{'course.'.$cid.'.num'};
                   11059:     }
                   11060: 
                   11061:     my %sectioncount;
1.419     raeburn  11062:     my $now = time;
1.240     albertel 11063: 
1.1118    raeburn  11064:     my $check_students = 1;
                   11065:     my $only_students = 0;
                   11066:     if (ref($possible_roles) eq 'ARRAY') {
                   11067:         if (grep(/^st$/,@{$possible_roles})) {
                   11068:             if (@{$possible_roles} == 1) {
                   11069:                 $only_students = 1;
                   11070:             }
                   11071:         } else {
                   11072:             $check_students = 0;
                   11073:         }
                   11074:     }
                   11075: 
                   11076:     if ($check_students) { 
1.276     albertel 11077: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11078: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11079: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11080:         my $start_index = &Apache::loncoursedata::CL_START();
                   11081:         my $end_index = &Apache::loncoursedata::CL_END();
                   11082:         my $status;
1.366     albertel 11083: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11084: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11085: 				                     $data->[$status_index],
                   11086:                                                      $data->[$start_index],
                   11087:                                                      $data->[$end_index]);
                   11088:             if ($stu_status eq 'Active') {
                   11089:                 $status = 'active';
                   11090:             } elsif ($end < $now) {
                   11091:                 $status = 'previous';
                   11092:             } elsif ($start > $now) {
                   11093:                 $status = 'future';
                   11094:             } 
                   11095: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11096:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11097:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11098: 		    $sectioncount{$section}++;
                   11099:                 }
1.240     albertel 11100: 	    }
                   11101: 	}
                   11102:     }
1.1118    raeburn  11103:     if ($only_students) {
                   11104:         return %sectioncount;
                   11105:     }
1.240     albertel 11106:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11107:     foreach my $user (sort(keys(%courseroles))) {
                   11108: 	if ($user !~ /^(\w{2})/) { next; }
                   11109: 	my ($role) = ($user =~ /^(\w{2})/);
                   11110: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11111: 	my ($section,$status);
1.240     albertel 11112: 	if ($role eq 'cr' &&
                   11113: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11114: 	    $section=$1;
                   11115: 	}
                   11116: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11117: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11118:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11119:         if ($end == -1 && $start == -1) {
                   11120:             next; #deleted role
                   11121:         }
                   11122:         if (!defined($possible_status)) { 
                   11123:             $sectioncount{$section}++;
                   11124:         } else {
                   11125:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11126:                 $status = 'active';
                   11127:             } elsif ($end < $now) {
                   11128:                 $status = 'future';
                   11129:             } elsif ($start > $now) {
                   11130:                 $status = 'previous';
                   11131:             }
                   11132:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11133:                 $sectioncount{$section}++;
                   11134:             }
                   11135:         }
1.233     raeburn  11136:     }
1.366     albertel 11137:     return %sectioncount;
1.233     raeburn  11138: }
                   11139: 
1.274     raeburn  11140: ###############################################
1.294     raeburn  11141: 
                   11142: =pod
1.405     albertel 11143: 
                   11144: =item * &get_course_users()
                   11145: 
1.275     raeburn  11146: Retrieves usernames:domains for users in the specified course
                   11147: with specific role(s), and access status. 
                   11148: 
                   11149: Incoming parameters:
1.277     albertel 11150: 1. course domain
                   11151: 2. course number
                   11152: 3. access status: users must have - either active, 
1.275     raeburn  11153: previous, future, or all.
1.277     albertel 11154: 4. reference to array of permissible roles
1.288     raeburn  11155: 5. reference to array of section restrictions (optional)
                   11156: 6. reference to results object (hash of hashes).
                   11157: 7. reference to optional userdata hash
1.609     raeburn  11158: 8. reference to optional statushash
1.630     raeburn  11159: 9. flag if privileged users (except those set to unhide in
                   11160:    course settings) should be excluded    
1.609     raeburn  11161: Keys of top level results hash are roles.
1.275     raeburn  11162: Keys of inner hashes are username:domain, with 
                   11163: values set to access type.
1.288     raeburn  11164: Optional userdata hash returns an array with arguments in the 
                   11165: same order as loncoursedata::get_classlist() for student data.
                   11166: 
1.609     raeburn  11167: Optional statushash returns
                   11168: 
1.288     raeburn  11169: Entries for end, start, section and status are blank because
                   11170: of the possibility of multiple values for non-student roles.
                   11171: 
1.275     raeburn  11172: =cut
1.405     albertel 11173: 
1.275     raeburn  11174: ###############################################
1.405     albertel 11175: 
1.275     raeburn  11176: sub get_course_users {
1.630     raeburn  11177:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11178:     my %idx = ();
1.419     raeburn  11179:     my %seclists;
1.288     raeburn  11180: 
                   11181:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11182:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11183:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11184:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11185:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11186:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11187:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11188:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11189: 
1.290     albertel 11190:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11191:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11192:         my $now = time;
1.277     albertel 11193:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11194:             my $match = 0;
1.412     raeburn  11195:             my $secmatch = 0;
1.419     raeburn  11196:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11197:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11198:             if ($section eq '') {
                   11199:                 $section = 'none';
                   11200:             }
1.291     albertel 11201:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11202:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11203:                     $secmatch = 1;
                   11204:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11205:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11206:                         $secmatch = 1;
                   11207:                     }
                   11208:                 } else {  
1.419     raeburn  11209: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11210: 		        $secmatch = 1;
                   11211:                     }
1.290     albertel 11212: 		}
1.412     raeburn  11213:                 if (!$secmatch) {
                   11214:                     next;
                   11215:                 }
1.419     raeburn  11216:             }
1.275     raeburn  11217:             if (defined($$types{'active'})) {
1.288     raeburn  11218:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11219:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11220:                     $match = 1;
1.275     raeburn  11221:                 }
                   11222:             }
                   11223:             if (defined($$types{'previous'})) {
1.609     raeburn  11224:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11225:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11226:                     $match = 1;
1.275     raeburn  11227:                 }
                   11228:             }
                   11229:             if (defined($$types{'future'})) {
1.609     raeburn  11230:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11231:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11232:                     $match = 1;
1.275     raeburn  11233:                 }
                   11234:             }
1.609     raeburn  11235:             if ($match) {
                   11236:                 push(@{$seclists{$student}},$section);
                   11237:                 if (ref($userdata) eq 'HASH') {
                   11238:                     $$userdata{$student} = $$classlist{$student};
                   11239:                 }
                   11240:                 if (ref($statushash) eq 'HASH') {
                   11241:                     $statushash->{$student}{'st'}{$section} = $status;
                   11242:                 }
1.288     raeburn  11243:             }
1.275     raeburn  11244:         }
                   11245:     }
1.412     raeburn  11246:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11247:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11248:         my $now = time;
1.609     raeburn  11249:         my %displaystatus = ( previous => 'Expired',
                   11250:                               active   => 'Active',
                   11251:                               future   => 'Future',
                   11252:                             );
1.1121    raeburn  11253:         my (%nothide,@possdoms);
1.630     raeburn  11254:         if ($hidepriv) {
                   11255:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11256:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11257:                 if ($user !~ /:/) {
                   11258:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11259:                 } else {
                   11260:                     $nothide{$user} = 1;
                   11261:                 }
                   11262:             }
1.1121    raeburn  11263:             my @possdoms = ($cdom);
                   11264:             if ($coursehash{'checkforpriv'}) {
                   11265:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11266:             }
1.630     raeburn  11267:         }
1.439     raeburn  11268:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11269:             my $match = 0;
1.412     raeburn  11270:             my $secmatch = 0;
1.439     raeburn  11271:             my $status;
1.412     raeburn  11272:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11273:             $user =~ s/:$//;
1.439     raeburn  11274:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11275:             if ($end == -1 || $start == -1) {
                   11276:                 next;
                   11277:             }
                   11278:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11279:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11280:                 my ($uname,$udom) = split(/:/,$user);
                   11281:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11282:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11283:                         $secmatch = 1;
                   11284:                     } elsif ($usec eq '') {
1.420     albertel 11285:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11286:                             $secmatch = 1;
                   11287:                         }
                   11288:                     } else {
                   11289:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11290:                             $secmatch = 1;
                   11291:                         }
                   11292:                     }
                   11293:                     if (!$secmatch) {
                   11294:                         next;
                   11295:                     }
1.288     raeburn  11296:                 }
1.419     raeburn  11297:                 if ($usec eq '') {
                   11298:                     $usec = 'none';
                   11299:                 }
1.275     raeburn  11300:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11301:                     if ($hidepriv) {
1.1121    raeburn  11302:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11303:                             (!$nothide{$uname.':'.$udom})) {
                   11304:                             next;
                   11305:                         }
                   11306:                     }
1.503     raeburn  11307:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11308:                         $status = 'previous';
                   11309:                     } elsif ($start > $now) {
                   11310:                         $status = 'future';
                   11311:                     } else {
                   11312:                         $status = 'active';
                   11313:                     }
1.277     albertel 11314:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11315:                         if ($status eq $type) {
1.420     albertel 11316:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11317:                                 push(@{$$users{$role}{$user}},$type);
                   11318:                             }
1.288     raeburn  11319:                             $match = 1;
                   11320:                         }
                   11321:                     }
1.419     raeburn  11322:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11323:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11324: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11325:                         }
1.420     albertel 11326:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11327:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11328:                         }
1.609     raeburn  11329:                         if (ref($statushash) eq 'HASH') {
                   11330:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11331:                         }
1.275     raeburn  11332:                     }
                   11333:                 }
                   11334:             }
                   11335:         }
1.290     albertel 11336:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11337:             if ((defined($cdom)) && (defined($cnum))) {
                   11338:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11339:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11340:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11341:                     next if ($owner eq '');
                   11342:                     my ($ownername,$ownerdom);
                   11343:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11344:                         $ownername = $1;
                   11345:                         $ownerdom = $2;
                   11346:                     } else {
                   11347:                         $ownername = $owner;
                   11348:                         $ownerdom = $cdom;
                   11349:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11350:                     }
                   11351:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11352:                     if (defined($userdata) && 
1.609     raeburn  11353: 			!exists($$userdata{$owner})) {
                   11354: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11355:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11356:                             push(@{$seclists{$owner}},'none');
                   11357:                         }
                   11358:                         if (ref($statushash) eq 'HASH') {
                   11359:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11360:                         }
1.290     albertel 11361: 		    }
1.279     raeburn  11362:                 }
                   11363:             }
                   11364:         }
1.419     raeburn  11365:         foreach my $user (keys(%seclists)) {
                   11366:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11367:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11368:         }
1.275     raeburn  11369:     }
                   11370:     return;
                   11371: }
                   11372: 
1.288     raeburn  11373: sub get_user_info {
                   11374:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11375:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11376: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11377:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11378:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11379:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11380:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11381:     return;
                   11382: }
1.275     raeburn  11383: 
1.472     raeburn  11384: ###############################################
                   11385: 
                   11386: =pod
                   11387: 
                   11388: =item * &get_user_quota()
                   11389: 
1.1134    raeburn  11390: Retrieves quota assigned for storage of user files.
                   11391: Default is to report quota for portfolio files.
1.472     raeburn  11392: 
                   11393: Incoming parameters:
                   11394: 1. user's username
                   11395: 2. user's domain
1.1134    raeburn  11396: 3. quota name - portfolio, author, or course
1.1136    raeburn  11397:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11398: 4. crstype - official, unofficial, textbook, placement or community, 
                   11399:    if quota name is course
1.472     raeburn  11400: 
                   11401: Returns:
1.1163    raeburn  11402: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11403: 2. (Optional) Type of setting: custom or default
                   11404:    (individually assigned or default for user's 
                   11405:    institutional status).
                   11406: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11407:    or student - types as defined in localenroll::inst_usertypes 
                   11408:    for user's domain, which determines default quota for user.
                   11409: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11410: 
                   11411: If a value has been stored in the user's environment, 
1.536     raeburn  11412: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11413: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11414: 
                   11415: =cut
                   11416: 
                   11417: ###############################################
                   11418: 
                   11419: 
                   11420: sub get_user_quota {
1.1136    raeburn  11421:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11422:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11423:     if (!defined($udom)) {
                   11424:         $udom = $env{'user.domain'};
                   11425:     }
                   11426:     if (!defined($uname)) {
                   11427:         $uname = $env{'user.name'};
                   11428:     }
                   11429:     if (($udom eq '' || $uname eq '') ||
                   11430:         ($udom eq 'public') && ($uname eq 'public')) {
                   11431:         $quota = 0;
1.536     raeburn  11432:         $quotatype = 'default';
                   11433:         $defquota = 0; 
1.472     raeburn  11434:     } else {
1.536     raeburn  11435:         my $inststatus;
1.1134    raeburn  11436:         if ($quotaname eq 'course') {
                   11437:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11438:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11439:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11440:             } else {
                   11441:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11442:                 $quota = $cenv{'internal.uploadquota'};
                   11443:             }
1.536     raeburn  11444:         } else {
1.1134    raeburn  11445:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11446:                 if ($quotaname eq 'author') {
                   11447:                     $quota = $env{'environment.authorquota'};
                   11448:                 } else {
                   11449:                     $quota = $env{'environment.portfolioquota'};
                   11450:                 }
                   11451:                 $inststatus = $env{'environment.inststatus'};
                   11452:             } else {
                   11453:                 my %userenv = 
                   11454:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11455:                                          'authorquota','inststatus'],$udom,$uname);
                   11456:                 my ($tmp) = keys(%userenv);
                   11457:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11458:                     if ($quotaname eq 'author') {
                   11459:                         $quota = $userenv{'authorquota'};
                   11460:                     } else {
                   11461:                         $quota = $userenv{'portfolioquota'};
                   11462:                     }
                   11463:                     $inststatus = $userenv{'inststatus'};
                   11464:                 } else {
                   11465:                     undef(%userenv);
                   11466:                 }
                   11467:             }
                   11468:         }
                   11469:         if ($quota eq '' || wantarray) {
                   11470:             if ($quotaname eq 'course') {
                   11471:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11472:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11473:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11474:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11475:                     $defquota = $domdefs{$crstype.'quota'};
                   11476:                 }
                   11477:                 if ($defquota eq '') {
                   11478:                     $defquota = 500;
                   11479:                 }
1.1134    raeburn  11480:             } else {
                   11481:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11482:             }
                   11483:             if ($quota eq '') {
                   11484:                 $quota = $defquota;
                   11485:                 $quotatype = 'default';
                   11486:             } else {
                   11487:                 $quotatype = 'custom';
                   11488:             }
1.472     raeburn  11489:         }
                   11490:     }
1.536     raeburn  11491:     if (wantarray) {
                   11492:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11493:     } else {
                   11494:         return $quota;
                   11495:     }
1.472     raeburn  11496: }
                   11497: 
                   11498: ###############################################
                   11499: 
                   11500: =pod
                   11501: 
                   11502: =item * &default_quota()
                   11503: 
1.536     raeburn  11504: Retrieves default quota assigned for storage of user portfolio files,
                   11505: given an (optional) user's institutional status.
1.472     raeburn  11506: 
                   11507: Incoming parameters:
1.1142    raeburn  11508: 
1.472     raeburn  11509: 1. domain
1.536     raeburn  11510: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11511:    status types (e.g., faculty, staff, student etc.)
                   11512:    which apply to the user for whom the default is being retrieved.
                   11513:    If the institutional status string in undefined, the domain
1.1134    raeburn  11514:    default quota will be returned.
                   11515: 3.  quota name - portfolio, author, or course
                   11516:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11517: 
                   11518: Returns:
1.1142    raeburn  11519: 
1.1163    raeburn  11520: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11521: 2. (Optional) institutional type which determined the value of the
                   11522:    default quota.
1.472     raeburn  11523: 
                   11524: If a value has been stored in the domain's configuration db,
                   11525: it will return that, otherwise it returns 20 (for backwards 
                   11526: compatibility with domains which have not set up a configuration
1.1163    raeburn  11527: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11528: 
1.536     raeburn  11529: If the user's status includes multiple types (e.g., staff and student),
                   11530: the largest default quota which applies to the user determines the
                   11531: default quota returned.
                   11532: 
1.472     raeburn  11533: =cut
                   11534: 
                   11535: ###############################################
                   11536: 
                   11537: 
                   11538: sub default_quota {
1.1134    raeburn  11539:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11540:     my ($defquota,$settingstatus);
                   11541:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11542:                                             ['quotas'],$udom);
1.1134    raeburn  11543:     my $key = 'defaultquota';
                   11544:     if ($quotaname eq 'author') {
                   11545:         $key = 'authorquota';
                   11546:     }
1.622     raeburn  11547:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11548:         if ($inststatus ne '') {
1.765     raeburn  11549:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11550:             foreach my $item (@statuses) {
1.1134    raeburn  11551:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11552:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11553:                         if ($defquota eq '') {
1.1134    raeburn  11554:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11555:                             $settingstatus = $item;
1.1134    raeburn  11556:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11557:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11558:                             $settingstatus = $item;
                   11559:                         }
                   11560:                     }
1.1134    raeburn  11561:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11562:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11563:                         if ($defquota eq '') {
                   11564:                             $defquota = $quotahash{'quotas'}{$item};
                   11565:                             $settingstatus = $item;
                   11566:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11567:                             $defquota = $quotahash{'quotas'}{$item};
                   11568:                             $settingstatus = $item;
                   11569:                         }
1.536     raeburn  11570:                     }
                   11571:                 }
                   11572:             }
                   11573:         }
                   11574:         if ($defquota eq '') {
1.1134    raeburn  11575:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11576:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11577:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11578:                 $defquota = $quotahash{'quotas'}{'default'};
                   11579:             }
1.536     raeburn  11580:             $settingstatus = 'default';
1.1139    raeburn  11581:             if ($defquota eq '') {
                   11582:                 if ($quotaname eq 'author') {
                   11583:                     $defquota = 500;
                   11584:                 }
                   11585:             }
1.536     raeburn  11586:         }
                   11587:     } else {
                   11588:         $settingstatus = 'default';
1.1134    raeburn  11589:         if ($quotaname eq 'author') {
                   11590:             $defquota = 500;
                   11591:         } else {
                   11592:             $defquota = 20;
                   11593:         }
1.536     raeburn  11594:     }
                   11595:     if (wantarray) {
                   11596:         return ($defquota,$settingstatus);
1.472     raeburn  11597:     } else {
1.536     raeburn  11598:         return $defquota;
1.472     raeburn  11599:     }
                   11600: }
                   11601: 
1.1135    raeburn  11602: ###############################################
                   11603: 
                   11604: =pod
                   11605: 
1.1136    raeburn  11606: =item * &excess_filesize_warning()
1.1135    raeburn  11607: 
                   11608: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11609: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11610: space to be exceeded.
1.1136    raeburn  11611: 
                   11612: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11613: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11614: 
1.1165    raeburn  11615: Inputs: 7 
1.1136    raeburn  11616: 1. username or coursenum
1.1135    raeburn  11617: 2. domain
1.1136    raeburn  11618: 3. context ('author' or 'course')
1.1135    raeburn  11619: 4. filename of file for which action is being requested
                   11620: 5. filesize (kB) of file
                   11621: 6. action being taken: copy or upload.
1.1237    raeburn  11622: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11623: 
                   11624: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11625:          otherwise return null.
                   11626: 
                   11627: =back
1.1135    raeburn  11628: 
                   11629: =cut
                   11630: 
1.1136    raeburn  11631: sub excess_filesize_warning {
1.1165    raeburn  11632:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11633:     my $current_disk_usage = 0;
1.1165    raeburn  11634:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11635:     if ($context eq 'author') {
                   11636:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11637:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11638:     } else {
                   11639:         foreach my $subdir ('docs','supplemental') {
                   11640:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11641:         }
                   11642:     }
1.1135    raeburn  11643:     $disk_quota = int($disk_quota * 1000);
                   11644:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11645:         return '<p class="LC_warning">'.
1.1135    raeburn  11646:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11647:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11648:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11649:                             $disk_quota,$current_disk_usage).
                   11650:                '</p>';
                   11651:     }
                   11652:     return;
                   11653: }
                   11654: 
                   11655: ###############################################
                   11656: 
                   11657: 
1.1136    raeburn  11658: 
                   11659: 
1.384     raeburn  11660: sub get_secgrprole_info {
                   11661:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11662:     my %sections_count = &get_sections($cdom,$cnum);
                   11663:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11664:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11665:     my @groups = sort(keys(%curr_groups));
                   11666:     my $allroles = [];
                   11667:     my $rolehash;
                   11668:     my $accesshash = {
                   11669:                      active => 'Currently has access',
                   11670:                      future => 'Will have future access',
                   11671:                      previous => 'Previously had access',
                   11672:                   };
                   11673:     if ($needroles) {
                   11674:         $rolehash = {'all' => 'all'};
1.385     albertel 11675:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11676: 	if (&Apache::lonnet::error(%user_roles)) {
                   11677: 	    undef(%user_roles);
                   11678: 	}
                   11679:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11680:             my ($role)=split(/\:/,$item,2);
                   11681:             if ($role eq 'cr') { next; }
                   11682:             if ($role =~ /^cr/) {
                   11683:                 $$rolehash{$role} = (split('/',$role))[3];
                   11684:             } else {
                   11685:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11686:             }
                   11687:         }
                   11688:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11689:             push(@{$allroles},$key);
                   11690:         }
                   11691:         push (@{$allroles},'st');
                   11692:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11693:     }
                   11694:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11695: }
                   11696: 
1.555     raeburn  11697: sub user_picker {
1.1279    raeburn  11698:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11699:     my $currdom = $dom;
1.1253    raeburn  11700:     my @alldoms = &Apache::lonnet::all_domains();
                   11701:     if (@alldoms == 1) {
                   11702:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11703:                                                ['directorysrch'],$alldoms[0]);
                   11704:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11705:         my $showdom = $domdesc;
                   11706:         if ($showdom eq '') {
                   11707:             $showdom = $dom;
                   11708:         }
                   11709:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11710:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11711:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11712:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11713:             }
                   11714:         }
                   11715:     }
1.555     raeburn  11716:     my %curr_selected = (
                   11717:                         srchin => 'dom',
1.580     raeburn  11718:                         srchby => 'lastname',
1.555     raeburn  11719:                       );
                   11720:     my $srchterm;
1.625     raeburn  11721:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11722:         if ($srch->{'srchby'} ne '') {
                   11723:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11724:         }
                   11725:         if ($srch->{'srchin'} ne '') {
                   11726:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11727:         }
                   11728:         if ($srch->{'srchtype'} ne '') {
                   11729:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11730:         }
                   11731:         if ($srch->{'srchdomain'} ne '') {
                   11732:             $currdom = $srch->{'srchdomain'};
                   11733:         }
                   11734:         $srchterm = $srch->{'srchterm'};
                   11735:     }
1.1222    damieng  11736:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11737:                     'usr'       => 'Search criteria',
1.563     raeburn  11738:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11739:                     'uname'     => 'username',
                   11740:                     'lastname'  => 'last name',
1.555     raeburn  11741:                     'lastfirst' => 'last name, first name',
1.558     albertel 11742:                     'crs'       => 'in this course',
1.576     raeburn  11743:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11744:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11745:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11746:                     'exact'     => 'is',
                   11747:                     'contains'  => 'contains',
1.569     raeburn  11748:                     'begins'    => 'begins with',
1.1222    damieng  11749:                                        );
                   11750:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11751:                     'youm'      => "You must include some text to search for.",
                   11752:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11753:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11754:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11755:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11756:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11757:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11758:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11759:                                        );
1.1222    damieng  11760:     &html_escape(\%html_lt);
                   11761:     &js_escape(\%js_lt);
1.1255    raeburn  11762:     my $domform;
1.1277    raeburn  11763:     my $allow_blank = 1;
1.1255    raeburn  11764:     if ($fixeddom) {
1.1277    raeburn  11765:         $allow_blank = 0;
                   11766:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11767:     } else {
1.1287    raeburn  11768:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11769:         my ($trusted,$untrusted);
1.1287    raeburn  11770:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11771:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11772:         } elsif ($context eq 'author') {
1.1288    raeburn  11773:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11774:         } elsif ($context eq 'domain') {
1.1288    raeburn  11775:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11776:         }
1.1288    raeburn  11777:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11778:     }
1.563     raeburn  11779:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11780: 
                   11781:     my @srchins = ('crs','dom','alc','instd');
                   11782: 
                   11783:     foreach my $option (@srchins) {
                   11784:         # FIXME 'alc' option unavailable until 
                   11785:         #       loncreateuser::print_user_query_page()
                   11786:         #       has been completed.
                   11787:         next if ($option eq 'alc');
1.880     raeburn  11788:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11789:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11790:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11791:         if ($curr_selected{'srchin'} eq $option) {
                   11792:             $srchinsel .= ' 
1.1222    damieng  11793:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11794:         } else {
                   11795:             $srchinsel .= '
1.1222    damieng  11796:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11797:         }
1.555     raeburn  11798:     }
1.563     raeburn  11799:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11800: 
                   11801:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11802:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11803:         if ($curr_selected{'srchby'} eq $option) {
                   11804:             $srchbysel .= '
1.1222    damieng  11805:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11806:         } else {
                   11807:             $srchbysel .= '
1.1222    damieng  11808:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11809:          }
                   11810:     }
                   11811:     $srchbysel .= "\n  </select>\n";
                   11812: 
                   11813:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11814:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11815:         if ($curr_selected{'srchtype'} eq $option) {
                   11816:             $srchtypesel .= '
1.1222    damieng  11817:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11818:         } else {
                   11819:             $srchtypesel .= '
1.1222    damieng  11820:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11821:         }
                   11822:     }
                   11823:     $srchtypesel .= "\n  </select>\n";
                   11824: 
1.558     albertel 11825:     my ($newuserscript,$new_user_create);
1.994     raeburn  11826:     my $context_dom = $env{'request.role.domain'};
                   11827:     if ($context eq 'requestcrs') {
                   11828:         if ($env{'form.coursedom'} ne '') { 
                   11829:             $context_dom = $env{'form.coursedom'};
                   11830:         }
                   11831:     }
1.556     raeburn  11832:     if ($forcenewuser) {
1.576     raeburn  11833:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11834:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11835:                 if ($cancreate) {
                   11836:                     $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>';
                   11837:                 } else {
1.799     bisitz   11838:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11839:                     my %usertypetext = (
                   11840:                         official   => 'institutional',
                   11841:                         unofficial => 'non-institutional',
                   11842:                     );
1.799     bisitz   11843:                     $new_user_create = '<p class="LC_warning">'
                   11844:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11845:                                       .' '
                   11846:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11847:                                           ,'<a href="'.$helplink.'">','</a>')
                   11848:                                       .'</p><br />';
1.627     raeburn  11849:                 }
1.576     raeburn  11850:             }
                   11851:         }
                   11852: 
1.556     raeburn  11853:         $newuserscript = <<"ENDSCRIPT";
                   11854: 
1.570     raeburn  11855: function setSearch(createnew,callingForm) {
1.556     raeburn  11856:     if (createnew == 1) {
1.570     raeburn  11857:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11858:             if (callingForm.srchby.options[i].value == 'uname') {
                   11859:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11860:             }
                   11861:         }
1.570     raeburn  11862:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11863:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11864: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11865:             }
                   11866:         }
1.570     raeburn  11867:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11868:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11869:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11870:             }
                   11871:         }
1.570     raeburn  11872:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11873:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11874:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11875:             }
                   11876:         }
                   11877:     }
                   11878: }
                   11879: ENDSCRIPT
1.558     albertel 11880: 
1.556     raeburn  11881:     }
                   11882: 
1.555     raeburn  11883:     my $output = <<"END_BLOCK";
1.556     raeburn  11884: <script type="text/javascript">
1.824     bisitz   11885: // <![CDATA[
1.570     raeburn  11886: function validateEntry(callingForm) {
1.558     albertel 11887: 
1.556     raeburn  11888:     var checkok = 1;
1.558     albertel 11889:     var srchin;
1.570     raeburn  11890:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11891: 	if ( callingForm.srchin[i].checked ) {
                   11892: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11893: 	}
                   11894:     }
                   11895: 
1.570     raeburn  11896:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11897:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11898:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11899:     var srchterm =  callingForm.srchterm.value;
                   11900:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11901:     var msg = "";
                   11902: 
                   11903:     if (srchterm == "") {
                   11904:         checkok = 0;
1.1222    damieng  11905:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11906:     }
                   11907: 
1.569     raeburn  11908:     if (srchtype== 'begins') {
                   11909:         if (srchterm.length < 2) {
                   11910:             checkok = 0;
1.1222    damieng  11911:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11912:         }
                   11913:     }
                   11914: 
1.556     raeburn  11915:     if (srchtype== 'contains') {
                   11916:         if (srchterm.length < 3) {
                   11917:             checkok = 0;
1.1222    damieng  11918:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11919:         }
                   11920:     }
                   11921:     if (srchin == 'instd') {
                   11922:         if (srchdomain == '') {
                   11923:             checkok = 0;
1.1222    damieng  11924:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11925:         }
                   11926:     }
                   11927:     if (srchin == 'dom') {
                   11928:         if (srchdomain == '') {
                   11929:             checkok = 0;
1.1222    damieng  11930:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11931:         }
                   11932:     }
                   11933:     if (srchby == 'lastfirst') {
                   11934:         if (srchterm.indexOf(",") == -1) {
                   11935:             checkok = 0;
1.1222    damieng  11936:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11937:         }
                   11938:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11939:             checkok = 0;
1.1222    damieng  11940:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11941:         }
                   11942:     }
                   11943:     if (checkok == 0) {
1.1222    damieng  11944:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11945:         return;
                   11946:     }
                   11947:     if (checkok == 1) {
1.570     raeburn  11948:         callingForm.submit();
1.556     raeburn  11949:     }
                   11950: }
                   11951: 
                   11952: $newuserscript
                   11953: 
1.824     bisitz   11954: // ]]>
1.556     raeburn  11955: </script>
1.558     albertel 11956: 
                   11957: $new_user_create
                   11958: 
1.555     raeburn  11959: END_BLOCK
1.558     albertel 11960: 
1.876     raeburn  11961:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11962:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11963:                $domform.
                   11964:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11965:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11966:                $srchbysel.
                   11967:                $srchtypesel. 
                   11968:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11969:                $srchinsel.
                   11970:                &Apache::lonhtmlcommon::row_closure(1). 
                   11971:                &Apache::lonhtmlcommon::end_pick_box().
                   11972:                '<br />';
1.1253    raeburn  11973:     return ($output,1);
1.555     raeburn  11974: }
                   11975: 
1.612     raeburn  11976: sub user_rule_check {
1.615     raeburn  11977:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11978:     my ($response,%inst_response);
1.612     raeburn  11979:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11980:         if (keys(%{$usershash}) > 1) {
                   11981:             my (%by_username,%by_id,%userdoms);
                   11982:             my $checkid; 
                   11983:             if (ref($checks) eq 'HASH') {
                   11984:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11985:                     $checkid = 1;
                   11986:                 }
                   11987:             }
                   11988:             foreach my $user (keys(%{$usershash})) {
                   11989:                 my ($uname,$udom) = split(/:/,$user);
                   11990:                 if ($checkid) {
                   11991:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11992:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11993:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11994:                             $userdoms{$udom} = 1;
1.1227    raeburn  11995:                             if (ref($inst_results) eq 'HASH') {
                   11996:                                 $inst_results->{$uname.':'.$udom} = {};
                   11997:                             }
1.1226    raeburn  11998:                         }
                   11999:                     }
                   12000:                 } else {
                   12001:                     $by_username{$udom}{$uname} = 1;
                   12002:                     $userdoms{$udom} = 1;
1.1227    raeburn  12003:                     if (ref($inst_results) eq 'HASH') {
                   12004:                         $inst_results->{$uname.':'.$udom} = {};
                   12005:                     }
1.1226    raeburn  12006:                 }
                   12007:             }
                   12008:             foreach my $udom (keys(%userdoms)) {
                   12009:                 if (!$got_rules->{$udom}) {
                   12010:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12011:                                                              ['usercreation'],$udom);
                   12012:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12013:                         foreach my $item ('username','id') {
                   12014:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  12015:                                 $$curr_rules{$udom}{$item} =
                   12016:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  12017:                             }
                   12018:                         }
                   12019:                     }
                   12020:                     $got_rules->{$udom} = 1;
                   12021:                 }
1.612     raeburn  12022:             }
1.1226    raeburn  12023:             if ($checkid) {
                   12024:                 foreach my $udom (keys(%by_id)) {
                   12025:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   12026:                     if ($outcome eq 'ok') {
1.1227    raeburn  12027:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   12028:                             my $uname = $by_id{$udom}{$id};
                   12029:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12030:                         }
1.1226    raeburn  12031:                         if (ref($results) eq 'HASH') {
                   12032:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  12033:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   12034:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   12035:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12036:                                 }
1.1226    raeburn  12037:                             }
                   12038:                         }
                   12039:                     }
1.612     raeburn  12040:                 }
1.615     raeburn  12041:             } else {
1.1226    raeburn  12042:                 foreach my $udom (keys(%by_username)) {
                   12043:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12044:                     if ($outcome eq 'ok') {
1.1227    raeburn  12045:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12046:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12047:                         }
1.1226    raeburn  12048:                         if (ref($results) eq 'HASH') {
                   12049:                             foreach my $uname (keys(%{$results})) {
                   12050:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12051:                             }
                   12052:                         }
                   12053:                     }
                   12054:                 }
1.612     raeburn  12055:             }
1.1226    raeburn  12056:         } elsif (keys(%{$usershash}) == 1) {
                   12057:             my $user = (keys(%{$usershash}))[0];
                   12058:             my ($uname,$udom) = split(/:/,$user);
                   12059:             if (($udom ne '') && ($uname ne '')) {
                   12060:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12061:                     if (ref($checks) eq 'HASH') {
                   12062:                         if (defined($checks->{'username'})) {
                   12063:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12064:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12065:                         } elsif (defined($checks->{'id'})) {
                   12066:                             if ($usershash->{$user}->{'id'} ne '') {
                   12067:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12068:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12069:                                                                   $usershash->{$user}->{'id'});
                   12070:                             } else {
                   12071:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12072:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12073:                             }
1.585     raeburn  12074:                         }
1.1226    raeburn  12075:                     } else {
                   12076:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12077:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12078:                        return;
                   12079:                     }
                   12080:                     if (!$got_rules->{$udom}) {
                   12081:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12082:                                                                  ['usercreation'],$udom);
                   12083:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12084:                             foreach my $item ('username','id') {
                   12085:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12086:                                    $$curr_rules{$udom}{$item} = 
                   12087:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12088:                                 }
                   12089:                             }
                   12090:                         }
                   12091:                         $got_rules->{$udom} = 1;
1.585     raeburn  12092:                     }
                   12093:                 }
1.1226    raeburn  12094:             } else {
                   12095:                 return;
                   12096:             }
                   12097:         } else {
                   12098:             return;
                   12099:         }
                   12100:         foreach my $user (keys(%{$usershash})) {
                   12101:             my ($uname,$udom) = split(/:/,$user);
                   12102:             next if (($udom eq '') || ($uname eq ''));
                   12103:             my $id;
1.1227    raeburn  12104:             if (ref($inst_results) eq 'HASH') {
                   12105:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12106:                     $id = $inst_results->{$user}->{'id'};
                   12107:                 }
                   12108:             }
                   12109:             if ($id eq '') { 
                   12110:                 if (ref($usershash->{$user})) {
                   12111:                     $id = $usershash->{$user}->{'id'};
                   12112:                 }
1.585     raeburn  12113:             }
1.612     raeburn  12114:             foreach my $item (keys(%{$checks})) {
                   12115:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12116:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12117:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12118:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12119:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12120:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12121:                                 if ($rule_check{$rule}) {
                   12122:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12123:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12124:                                         if (ref($inst_results) eq 'HASH') {
                   12125:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12126:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12127:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12128:                                                 } elsif ($item eq 'id') {
                   12129:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12130:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12131:                                                     }
1.615     raeburn  12132:                                                 }
1.612     raeburn  12133:                                             }
                   12134:                                         }
1.615     raeburn  12135:                                     }
                   12136:                                     last;
1.585     raeburn  12137:                                 }
                   12138:                             }
                   12139:                         }
                   12140:                     }
                   12141:                 }
                   12142:             }
                   12143:         }
                   12144:     }
1.612     raeburn  12145:     return;
                   12146: }
                   12147: 
                   12148: sub user_rule_formats {
                   12149:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12150:     my %text = ( 
                   12151:                  'username' => 'Usernames',
                   12152:                  'id'       => 'IDs',
                   12153:                );
                   12154:     my $output;
                   12155:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12156:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12157:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12158:             $output = '<br />'.
                   12159:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12160:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12161:                       ' <ul>';
1.612     raeburn  12162:             foreach my $rule (@{$ruleorder}) {
                   12163:                 if (ref($curr_rules) eq 'ARRAY') {
                   12164:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12165:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12166:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12167:                                         $rules->{$rule}{'desc'}.'</li>';
                   12168:                         }
                   12169:                     }
                   12170:                 }
                   12171:             }
                   12172:             $output .= '</ul>';
                   12173:         }
                   12174:     }
                   12175:     return $output;
                   12176: }
                   12177: 
                   12178: sub instrule_disallow_msg {
1.615     raeburn  12179:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12180:     my $response;
                   12181:     my %text = (
                   12182:                   item   => 'username',
                   12183:                   items  => 'usernames',
                   12184:                   match  => 'matches',
                   12185:                   do     => 'does',
                   12186:                   action => 'a username',
                   12187:                   one    => 'one',
                   12188:                );
                   12189:     if ($count > 1) {
                   12190:         $text{'item'} = 'usernames';
                   12191:         $text{'match'} ='match';
                   12192:         $text{'do'} = 'do';
                   12193:         $text{'action'} = 'usernames',
                   12194:         $text{'one'} = 'ones';
                   12195:     }
                   12196:     if ($checkitem eq 'id') {
                   12197:         $text{'items'} = 'IDs';
                   12198:         $text{'item'} = 'ID';
                   12199:         $text{'action'} = 'an ID';
1.615     raeburn  12200:         if ($count > 1) {
                   12201:             $text{'item'} = 'IDs';
                   12202:             $text{'action'} = 'IDs';
                   12203:         }
1.612     raeburn  12204:     }
1.674     bisitz   12205:     $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  12206:     if ($mode eq 'upload') {
                   12207:         if ($checkitem eq 'username') {
                   12208:             $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'}.");
                   12209:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12210:             $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  12211:         }
1.669     raeburn  12212:     } elsif ($mode eq 'selfcreate') {
                   12213:         if ($checkitem eq 'id') {
                   12214:             $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.");
                   12215:         }
1.615     raeburn  12216:     } else {
                   12217:         if ($checkitem eq 'username') {
                   12218:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12219:         } elsif ($checkitem eq 'id') {
                   12220:             $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.");
                   12221:         }
1.612     raeburn  12222:     }
                   12223:     return $response;
1.585     raeburn  12224: }
                   12225: 
1.624     raeburn  12226: sub personal_data_fieldtitles {
                   12227:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12228:                         id => 'Student/Employee ID',
                   12229:                         permanentemail => 'E-mail address',
                   12230:                         lastname => 'Last Name',
                   12231:                         firstname => 'First Name',
                   12232:                         middlename => 'Middle Name',
                   12233:                         generation => 'Generation',
                   12234:                         gen => 'Generation',
1.765     raeburn  12235:                         inststatus => 'Affiliation',
1.624     raeburn  12236:                    );
                   12237:     return %fieldtitles;
                   12238: }
                   12239: 
1.642     raeburn  12240: sub sorted_inst_types {
                   12241:     my ($dom) = @_;
1.1185    raeburn  12242:     my ($usertypes,$order);
                   12243:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12244:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12245:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12246:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12247:     } else {
                   12248:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12249:     }
1.642     raeburn  12250:     my $othertitle = &mt('All users');
                   12251:     if ($env{'request.course.id'}) {
1.668     raeburn  12252:         $othertitle  = &mt('Any users');
1.642     raeburn  12253:     }
                   12254:     my @types;
                   12255:     if (ref($order) eq 'ARRAY') {
                   12256:         @types = @{$order};
                   12257:     }
                   12258:     if (@types == 0) {
                   12259:         if (ref($usertypes) eq 'HASH') {
                   12260:             @types = sort(keys(%{$usertypes}));
                   12261:         }
                   12262:     }
                   12263:     if (keys(%{$usertypes}) > 0) {
                   12264:         $othertitle = &mt('Other users');
                   12265:     }
                   12266:     return ($othertitle,$usertypes,\@types);
                   12267: }
                   12268: 
1.645     raeburn  12269: sub get_institutional_codes {
1.1361    raeburn  12270:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12271: # Get complete list of course sections to update
                   12272:     my @currsections = ();
                   12273:     my @currxlists = ();
1.1361    raeburn  12274:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12275:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12276:     my $crskey = $crs.':'.$coursecode;
                   12277:     @{$unclutteredsec{$crskey}} = ();
                   12278:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12279: 
                   12280:     if ($$settings{'internal.sectionnums'} ne '') {
                   12281:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12282:     }
                   12283: 
                   12284:     if ($$settings{'internal.crosslistings'} ne '') {
                   12285:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12286:     }
                   12287: 
                   12288:     if (@currxlists > 0) {
1.1361    raeburn  12289:         foreach my $xl (@currxlists) {
                   12290:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12291:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12292:                     push(@{$allcourses},$1);
1.645     raeburn  12293:                     $$LC_code{$1} = $2;
                   12294:                 }
                   12295:             }
                   12296:         }
                   12297:     }
1.1361    raeburn  12298: 
1.645     raeburn  12299:     if (@currsections > 0) {
1.1361    raeburn  12300:         foreach my $sec (@currsections) {
                   12301:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12302:                 my $instsec = $1;
1.645     raeburn  12303:                 my $lc_sec = $2;
1.1361    raeburn  12304:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12305:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12306:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12307:                 }
                   12308:             }
                   12309:         }
                   12310:     }
                   12311: 
                   12312:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12313:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12314:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12315:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12316:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12317:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12318:                     push(@{$allcourses},$sec);
1.1361    raeburn  12319:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12320:                 }
                   12321:             }
                   12322:         }
                   12323:     }
                   12324:     return;
                   12325: }
                   12326: 
1.971     raeburn  12327: sub get_standard_codeitems {
                   12328:     return ('Year','Semester','Department','Number','Section');
                   12329: }
                   12330: 
1.112     bowersj2 12331: =pod
                   12332: 
1.780     raeburn  12333: =head1 Slot Helpers
                   12334: 
                   12335: =over 4
                   12336: 
                   12337: =item * sorted_slots()
                   12338: 
1.1040    raeburn  12339: Sorts an array of slot names in order of an optional sort key,
                   12340: default sort is by slot start time (earliest first). 
1.780     raeburn  12341: 
                   12342: Inputs:
                   12343: 
                   12344: =over 4
                   12345: 
                   12346: slotsarr  - Reference to array of unsorted slot names.
                   12347: 
                   12348: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12349: 
1.1040    raeburn  12350: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12351: 
1.549     albertel 12352: =back
                   12353: 
1.780     raeburn  12354: Returns:
                   12355: 
                   12356: =over 4
                   12357: 
1.1040    raeburn  12358: sorted   - An array of slot names sorted by a specified sort key 
                   12359:            (default sort key is start time of the slot).
1.780     raeburn  12360: 
                   12361: =back
                   12362: 
                   12363: =cut
                   12364: 
                   12365: 
                   12366: sub sorted_slots {
1.1040    raeburn  12367:     my ($slotsarr,$slots,$sortkey) = @_;
                   12368:     if ($sortkey eq '') {
                   12369:         $sortkey = 'starttime';
                   12370:     }
1.780     raeburn  12371:     my @sorted;
                   12372:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12373:         @sorted =
                   12374:             sort {
                   12375:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12376:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12377:                      }
                   12378:                      if (ref($slots->{$a})) { return -1;}
                   12379:                      if (ref($slots->{$b})) { return 1;}
                   12380:                      return 0;
                   12381:                  } @{$slotsarr};
                   12382:     }
                   12383:     return @sorted;
                   12384: }
                   12385: 
1.1040    raeburn  12386: =pod
                   12387: 
                   12388: =item * get_future_slots()
                   12389: 
                   12390: Inputs:
                   12391: 
                   12392: =over 4
                   12393: 
                   12394: cnum - course number
                   12395: 
                   12396: cdom - course domain
                   12397: 
                   12398: now - current UNIX time
                   12399: 
                   12400: symb - optional symb
                   12401: 
                   12402: =back
                   12403: 
                   12404: Returns:
                   12405: 
                   12406: =over 4
                   12407: 
                   12408: sorted_reservable - ref to array of student_schedulable slots currently 
                   12409:                     reservable, ordered by end date of reservation period.
                   12410: 
                   12411: reservable_now - ref to hash of student_schedulable slots currently
                   12412:                  reservable.
                   12413: 
                   12414:     Keys in inner hash are:
                   12415:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12416:     (b) endreserve: end date of reservation period.
                   12417:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12418:         selected.
1.1040    raeburn  12419: 
                   12420: sorted_future - ref to array of student_schedulable slots reservable in
                   12421:                 the future, ordered by start date of reservation period.
                   12422: 
                   12423: future_reservable - ref to hash of student_schedulable slots reservable
                   12424:                     in the future.
                   12425: 
                   12426:     Keys in inner hash are:
                   12427:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12428:     (b) startreserve: start date of reservation period.
                   12429:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12430:         selected.
1.1040    raeburn  12431: 
                   12432: =back
                   12433: 
                   12434: =cut
                   12435: 
                   12436: sub get_future_slots {
                   12437:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12438:     my $map;
                   12439:     if ($symb) {
                   12440:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12441:     }
1.1040    raeburn  12442:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12443:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12444:     foreach my $slot (keys(%slots)) {
                   12445:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12446:         if ($symb) {
1.1229    raeburn  12447:             if ($slots{$slot}->{'symb'} ne '') {
                   12448:                 my $canuse;
                   12449:                 my %oksymbs;
                   12450:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12451:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12452:                 if ($oksymbs{$symb}) {
                   12453:                     $canuse = 1;
                   12454:                 } else {
                   12455:                     foreach my $item (@slotsymbs) {
                   12456:                         if ($item =~ /\.(page|sequence)$/) {
                   12457:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12458:                             if (($map ne '') && ($map eq $sloturl)) {
                   12459:                                 $canuse = 1;
                   12460:                                 last;
                   12461:                             }
                   12462:                         }
                   12463:                     }
                   12464:                 }
                   12465:                 next unless ($canuse);
                   12466:             }
1.1040    raeburn  12467:         }
                   12468:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12469:             ($slots{$slot}->{'endtime'} > $now)) {
                   12470:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12471:                 my $userallowed = 0;
                   12472:                 if ($slots{$slot}->{'allowedsections'}) {
                   12473:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12474:                     if (!defined($env{'request.role.sec'})
                   12475:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12476:                         $userallowed=1;
                   12477:                     } else {
                   12478:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12479:                             $userallowed=1;
                   12480:                         }
                   12481:                     }
                   12482:                     unless ($userallowed) {
                   12483:                         if (defined($env{'request.course.groups'})) {
                   12484:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12485:                             foreach my $group (@groups) {
                   12486:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12487:                                     $userallowed=1;
                   12488:                                     last;
                   12489:                                 }
                   12490:                             }
                   12491:                         }
                   12492:                     }
                   12493:                 }
                   12494:                 if ($slots{$slot}->{'allowedusers'}) {
                   12495:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12496:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12497:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12498:                         $userallowed = 1;
                   12499:                     }
                   12500:                 }
                   12501:                 next unless($userallowed);
                   12502:             }
                   12503:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12504:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12505:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12506:             my $uniqueperiod;
                   12507:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12508:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12509:             }
1.1040    raeburn  12510:             if (($startreserve < $now) &&
                   12511:                 (!$endreserve || $endreserve > $now)) {
                   12512:                 my $lastres = $endreserve;
                   12513:                 if (!$lastres) {
                   12514:                     $lastres = $slots{$slot}->{'starttime'};
                   12515:                 }
                   12516:                 $reservable_now{$slot} = {
                   12517:                                            symb       => $symb,
1.1250    raeburn  12518:                                            endreserve => $lastres,
                   12519:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12520:                                          };
                   12521:             } elsif (($startreserve > $now) &&
                   12522:                      (!$endreserve || $endreserve > $startreserve)) {
                   12523:                 $future_reservable{$slot} = {
                   12524:                                               symb         => $symb,
1.1250    raeburn  12525:                                               startreserve => $startreserve,
                   12526:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12527:                                             };
                   12528:             }
                   12529:         }
                   12530:     }
                   12531:     my @unsorted_reservable = keys(%reservable_now);
                   12532:     if (@unsorted_reservable > 0) {
                   12533:         @sorted_reservable = 
                   12534:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12535:     }
                   12536:     my @unsorted_future = keys(%future_reservable);
                   12537:     if (@unsorted_future > 0) {
                   12538:         @sorted_future =
                   12539:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12540:     }
                   12541:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12542: }
1.780     raeburn  12543: 
                   12544: =pod
                   12545: 
1.1057    foxr     12546: =back
                   12547: 
1.549     albertel 12548: =head1 HTTP Helpers
                   12549: 
                   12550: =over 4
                   12551: 
1.648     raeburn  12552: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12553: 
1.258     albertel 12554: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12555: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12556: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12557: 
                   12558: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12559: $possible_names is an ref to an array of form element names.  As an example:
                   12560: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12561: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12562: 
                   12563: =cut
1.1       albertel 12564: 
1.6       albertel 12565: sub get_unprocessed_cgi {
1.25      albertel 12566:   my ($query,$possible_names)= @_;
1.26      matthew  12567:   # $Apache::lonxml::debug=1;
1.356     albertel 12568:   foreach my $pair (split(/&/,$query)) {
                   12569:     my ($name, $value) = split(/=/,$pair);
1.369     www      12570:     $name = &unescape($name);
1.25      albertel 12571:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12572:       $value =~ tr/+/ /;
                   12573:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12574:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12575:     }
1.16      harris41 12576:   }
1.6       albertel 12577: }
                   12578: 
1.112     bowersj2 12579: =pod
                   12580: 
1.648     raeburn  12581: =item * &cacheheader() 
1.112     bowersj2 12582: 
                   12583: returns cache-controlling header code
                   12584: 
                   12585: =cut
                   12586: 
1.7       albertel 12587: sub cacheheader {
1.258     albertel 12588:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12589:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12590:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12591:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12592:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12593:     return $output;
1.7       albertel 12594: }
                   12595: 
1.112     bowersj2 12596: =pod
                   12597: 
1.648     raeburn  12598: =item * &no_cache($r) 
1.112     bowersj2 12599: 
                   12600: specifies header code to not have cache
                   12601: 
                   12602: =cut
                   12603: 
1.9       albertel 12604: sub no_cache {
1.216     albertel 12605:     my ($r) = @_;
                   12606:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12607: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12608:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12609:     $r->no_cache(1);
                   12610:     $r->header_out("Expires" => $date);
                   12611:     $r->header_out("Pragma" => "no-cache");
1.123     www      12612: }
                   12613: 
                   12614: sub content_type {
1.181     albertel 12615:     my ($r,$type,$charset) = @_;
1.299     foxr     12616:     if ($r) {
                   12617: 	#  Note that printout.pl calls this with undef for $r.
                   12618: 	&no_cache($r);
                   12619:     }
1.258     albertel 12620:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12621:     unless ($charset) {
                   12622: 	$charset=&Apache::lonlocal::current_encoding;
                   12623:     }
                   12624:     if ($charset) { $type.='; charset='.$charset; }
                   12625:     if ($r) {
                   12626: 	$r->content_type($type);
                   12627:     } else {
                   12628: 	print("Content-type: $type\n\n");
                   12629:     }
1.9       albertel 12630: }
1.25      albertel 12631: 
1.112     bowersj2 12632: =pod
                   12633: 
1.648     raeburn  12634: =item * &add_to_env($name,$value) 
1.112     bowersj2 12635: 
1.258     albertel 12636: adds $name to the %env hash with value
1.112     bowersj2 12637: $value, if $name already exists, the entry is converted to an array
                   12638: reference and $value is added to the array.
                   12639: 
                   12640: =cut
                   12641: 
1.25      albertel 12642: sub add_to_env {
                   12643:   my ($name,$value)=@_;
1.258     albertel 12644:   if (defined($env{$name})) {
                   12645:     if (ref($env{$name})) {
1.25      albertel 12646:       #already have multiple values
1.258     albertel 12647:       push(@{ $env{$name} },$value);
1.25      albertel 12648:     } else {
                   12649:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12650:       my $first=$env{$name};
                   12651:       undef($env{$name});
                   12652:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12653:     }
                   12654:   } else {
1.258     albertel 12655:     $env{$name}=$value;
1.25      albertel 12656:   }
1.31      albertel 12657: }
1.149     albertel 12658: 
                   12659: =pod
                   12660: 
1.648     raeburn  12661: =item * &get_env_multiple($name) 
1.149     albertel 12662: 
1.258     albertel 12663: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12664: values may be defined and end up as an array ref.
                   12665: 
                   12666: returns an array of values
                   12667: 
                   12668: =cut
                   12669: 
                   12670: sub get_env_multiple {
                   12671:     my ($name) = @_;
                   12672:     my @values;
1.258     albertel 12673:     if (defined($env{$name})) {
1.149     albertel 12674:         # exists is it an array
1.258     albertel 12675:         if (ref($env{$name})) {
                   12676:             @values=@{ $env{$name} };
1.149     albertel 12677:         } else {
1.258     albertel 12678:             $values[0]=$env{$name};
1.149     albertel 12679:         }
                   12680:     }
                   12681:     return(@values);
                   12682: }
                   12683: 
1.1249    damieng  12684: # Looks at given dependencies, and returns something depending on the context.
                   12685: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12686: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12687: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12688: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12689: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
                   12690: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12691: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12692: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12693: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12694: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12695: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12696: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12697: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
                   12698: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12699: sub ask_for_embedded_content {
1.1249    damieng  12700:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12701:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12702:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12703:         %currsubfile,%unused,$rem);
1.1071    raeburn  12704:     my $counter = 0;
                   12705:     my $numnew = 0;
1.987     raeburn  12706:     my $numremref = 0;
                   12707:     my $numinvalid = 0;
                   12708:     my $numpathchg = 0;
                   12709:     my $numexisting = 0;
1.1071    raeburn  12710:     my $numunused = 0;
                   12711:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12712:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12713:     my $heading = &mt('Upload embedded files');
                   12714:     my $buttontext = &mt('Upload');
                   12715: 
1.1249    damieng  12716:     # fills these variables based on the context:
                   12717:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12718:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12719:     if ($env{'request.course.id'}) {
1.1123    raeburn  12720:         if ($actionurl eq '/adm/dependencies') {
                   12721:             $navmap = Apache::lonnavmaps::navmap->new();
                   12722:         }
                   12723:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12724:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12725:     }
1.1123    raeburn  12726:     if (($actionurl eq '/adm/portfolio') || 
                   12727:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12728:         my $current_path='/';
                   12729:         if ($env{'form.currentpath'}) {
                   12730:             $current_path = $env{'form.currentpath'};
                   12731:         }
                   12732:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12733:             $udom = $cdom;
                   12734:             $uname = $cnum;
1.984     raeburn  12735:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12736:         } else {
                   12737:             $udom = $env{'user.domain'};
                   12738:             $uname = $env{'user.name'};
                   12739:             $url = '/userfiles/portfolio';
                   12740:         }
1.987     raeburn  12741:         $toplevel = $url.'/';
1.984     raeburn  12742:         $url .= $current_path;
                   12743:         $getpropath = 1;
1.987     raeburn  12744:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12745:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12746:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12747:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12748:         $toplevel = $url;
1.984     raeburn  12749:         if ($rest ne '') {
1.987     raeburn  12750:             $url .= $rest;
                   12751:         }
                   12752:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12753:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12754:             $url = $args->{'docs_url'};
                   12755:             $toplevel = $url;
1.1084    raeburn  12756:             if ($args->{'context'} eq 'paste') {
                   12757:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12758:                 ($path) = 
                   12759:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12760:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12761:                 $fileloc =~ s{^/}{};
                   12762:             }
1.1071    raeburn  12763:         }
1.1084    raeburn  12764:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12765:         if ($env{'request.course.id'} ne '') {
                   12766:             if (ref($args) eq 'HASH') {
                   12767:                 $url = $args->{'docs_url'};
                   12768:                 $title = $args->{'docs_title'};
1.1126    raeburn  12769:                 $toplevel = $url; 
                   12770:                 unless ($toplevel =~ m{^/}) {
                   12771:                     $toplevel = "/$url";
                   12772:                 }
1.1085    raeburn  12773:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12774:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12775:                     $path = $1;
                   12776:                 } else {
                   12777:                     ($path) =
                   12778:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12779:                 }
1.1195    raeburn  12780:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12781:                     $fileloc = $toplevel;
                   12782:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12783:                     my ($udom,$uname,$fname) =
                   12784:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12785:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12786:                 } else {
                   12787:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12788:                 }
1.1071    raeburn  12789:                 $fileloc =~ s{^/}{};
                   12790:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12791:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12792:             }
1.987     raeburn  12793:         }
1.1123    raeburn  12794:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12795:         $udom = $cdom;
                   12796:         $uname = $cnum;
                   12797:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12798:         $toplevel = $url;
                   12799:         $path = $url;
                   12800:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12801:         $fileloc =~ s{^/}{};
1.987     raeburn  12802:     }
1.1249    damieng  12803:     
                   12804:     # parses the dependency paths to get some info
                   12805:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12806:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12807:     # (will be completed later)
                   12808:     # $mapping:
                   12809:     #   for external URLs: external URL -> external URL
                   12810:     #   for relative paths: clean path -> original path
                   12811:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12812:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12813:     foreach my $file (keys(%{$allfiles})) {
                   12814:         my $embed_file;
                   12815:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12816:             $embed_file = $1;
                   12817:         } else {
                   12818:             $embed_file = $file;
                   12819:         }
1.1158    raeburn  12820:         my ($absolutepath,$cleaned_file);
                   12821:         if ($embed_file =~ m{^\w+://}) {
                   12822:             $cleaned_file = $embed_file;
1.1147    raeburn  12823:             $newfiles{$cleaned_file} = 1;
                   12824:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12825:         } else {
1.1158    raeburn  12826:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12827:             if ($embed_file =~ m{^/}) {
                   12828:                 $absolutepath = $embed_file;
                   12829:             }
1.1147    raeburn  12830:             if ($cleaned_file =~ m{/}) {
                   12831:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12832:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12833:                 my $item = $fname;
                   12834:                 if ($path ne '') {
                   12835:                     $item = $path.'/'.$fname;
                   12836:                     $subdependencies{$path}{$fname} = 1;
                   12837:                 } else {
                   12838:                     $dependencies{$item} = 1;
                   12839:                 }
                   12840:                 if ($absolutepath) {
                   12841:                     $mapping{$item} = $absolutepath;
                   12842:                 } else {
                   12843:                     $mapping{$item} = $embed_file;
                   12844:                 }
                   12845:             } else {
                   12846:                 $dependencies{$embed_file} = 1;
                   12847:                 if ($absolutepath) {
1.1147    raeburn  12848:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12849:                 } else {
1.1147    raeburn  12850:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12851:                 }
                   12852:             }
1.984     raeburn  12853:         }
                   12854:     }
1.1249    damieng  12855:     
                   12856:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12857:     # and lists
                   12858:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12859:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12860:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12861:     #                                    the path had to be cleaned up
                   12862:     # $existing: hash clean path -> 1 if the file exists
                   12863:     # $numexisting: number of keys in $existing
                   12864:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12865:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12866:     #                                      dependency subdirectories that are
                   12867:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12868:     my $dirptr = 16384;
1.984     raeburn  12869:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12870:         $currsubfile{$path} = {};
1.1123    raeburn  12871:         if (($actionurl eq '/adm/portfolio') || 
                   12872:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12873:             my ($sublistref,$listerror) =
                   12874:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12875:             if (ref($sublistref) eq 'ARRAY') {
                   12876:                 foreach my $line (@{$sublistref}) {
                   12877:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12878:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12879:                 }
1.984     raeburn  12880:             }
1.987     raeburn  12881:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12882:             if (opendir(my $dir,$url.'/'.$path)) {
                   12883:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12884:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12885:             }
1.1084    raeburn  12886:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12887:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12888:                   ($args->{'context'} eq 'paste')) ||
                   12889:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12890:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12891:                 my $dir;
                   12892:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12893:                     $dir = $fileloc;
                   12894:                 } else {
                   12895:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12896:                 }
1.1071    raeburn  12897:                 if ($dir ne '') {
                   12898:                     my ($sublistref,$listerror) =
                   12899:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12900:                     if (ref($sublistref) eq 'ARRAY') {
                   12901:                         foreach my $line (@{$sublistref}) {
                   12902:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12903:                                 undef,$mtime)=split(/\&/,$line,12);
                   12904:                             unless (($testdir&$dirptr) ||
                   12905:                                     ($file_name =~ /^\.\.?$/)) {
                   12906:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12907:                             }
                   12908:                         }
                   12909:                     }
                   12910:                 }
1.984     raeburn  12911:             }
                   12912:         }
                   12913:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12914:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12915:                 my $item = $path.'/'.$file;
                   12916:                 unless ($mapping{$item} eq $item) {
                   12917:                     $pathchanges{$item} = 1;
                   12918:                 }
                   12919:                 $existing{$item} = 1;
                   12920:                 $numexisting ++;
                   12921:             } else {
                   12922:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12923:             }
                   12924:         }
1.1071    raeburn  12925:         if ($actionurl eq '/adm/dependencies') {
                   12926:             foreach my $path (keys(%currsubfile)) {
                   12927:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12928:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12929:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12930:                              next if (($rem ne '') &&
                   12931:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12932:                                        (ref($navmap) &&
                   12933:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12934:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12935:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12936:                              $unused{$path.'/'.$file} = 1; 
                   12937:                          }
                   12938:                     }
                   12939:                 }
                   12940:             }
                   12941:         }
1.984     raeburn  12942:     }
1.1249    damieng  12943:     
                   12944:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12945:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12946:     my %currfile;
1.1123    raeburn  12947:     if (($actionurl eq '/adm/portfolio') ||
                   12948:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12949:         my ($dirlistref,$listerror) =
                   12950:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12951:         if (ref($dirlistref) eq 'ARRAY') {
                   12952:             foreach my $line (@{$dirlistref}) {
                   12953:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12954:                 $currfile{$file_name} = 1;
                   12955:             }
1.984     raeburn  12956:         }
1.987     raeburn  12957:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12958:         if (opendir(my $dir,$url)) {
1.987     raeburn  12959:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12960:             map {$currfile{$_} = 1;} @dir_list;
                   12961:         }
1.1084    raeburn  12962:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12963:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12964:               ($args->{'context'} eq 'paste')) ||
                   12965:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12966:         if ($env{'request.course.id'} ne '') {
                   12967:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12968:             if ($dir ne '') {
                   12969:                 my ($dirlistref,$listerror) =
                   12970:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12971:                 if (ref($dirlistref) eq 'ARRAY') {
                   12972:                     foreach my $line (@{$dirlistref}) {
                   12973:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12974:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12975:                         unless (($testdir&$dirptr) ||
                   12976:                                 ($file_name =~ /^\.\.?$/)) {
                   12977:                             $currfile{$file_name} = [$size,$mtime];
                   12978:                         }
                   12979:                     }
                   12980:                 }
                   12981:             }
                   12982:         }
1.984     raeburn  12983:     }
1.1249    damieng  12984:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12985:     # are not in subdirectories, using $currfile
1.984     raeburn  12986:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12987:         if (exists($currfile{$file})) {
1.987     raeburn  12988:             unless ($mapping{$file} eq $file) {
                   12989:                 $pathchanges{$file} = 1;
                   12990:             }
                   12991:             $existing{$file} = 1;
                   12992:             $numexisting ++;
                   12993:         } else {
1.984     raeburn  12994:             $newfiles{$file} = 1;
                   12995:         }
                   12996:     }
1.1071    raeburn  12997:     foreach my $file (keys(%currfile)) {
                   12998:         unless (($file eq $filename) ||
                   12999:                 ($file eq $filename.'.bak') ||
                   13000:                 ($dependencies{$file})) {
1.1085    raeburn  13001:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  13002:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   13003:                     next if (($rem ne '') &&
                   13004:                              (($env{"httpref.$rem".$file} ne '') ||
                   13005:                               (ref($navmap) &&
                   13006:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   13007:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   13008:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   13009:                 }
1.1085    raeburn  13010:             }
1.1071    raeburn  13011:             $unused{$file} = 1;
                   13012:         }
                   13013:     }
1.1249    damieng  13014:     
                   13015:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  13016:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   13017:         ($args->{'context'} eq 'paste')) {
                   13018:         $counter = scalar(keys(%existing));
                   13019:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  13020:         return ($output,$counter,$numpathchg,\%existing);
                   13021:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   13022:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   13023:         $counter = scalar(keys(%existing));
                   13024:         $numpathchg = scalar(keys(%pathchanges));
                   13025:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  13026:     }
1.1249    damieng  13027:     
                   13028:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   13029:     
                   13030:     # $upload_output: missing dependencies (with upload form)
                   13031:     # $modify_output: uploaded dependencies (in use)
                   13032:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  13033:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  13034:         if ($actionurl eq '/adm/dependencies') {
                   13035:             next if ($embed_file =~ m{^\w+://});
                   13036:         }
1.660     raeburn  13037:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13038:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13039:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13040:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13041:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13042:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13043:         }
1.1123    raeburn  13044:         $upload_output .= '</td>';
1.1071    raeburn  13045:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13046:             $upload_output.='<td align="right">'.
                   13047:                             '<span class="LC_info LC_fontsize_medium">'.
                   13048:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13049:             $numremref++;
1.660     raeburn  13050:         } elsif ($args->{'error_on_invalid_names'}
                   13051:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13052:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13053:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13054:             $numinvalid++;
1.660     raeburn  13055:         } else {
1.1123    raeburn  13056:             $upload_output .= '<td>'.
                   13057:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13058:                                                      $embed_file,\%mapping,
1.1071    raeburn  13059:                                                      $allfiles,$codebase,'upload');
                   13060:             $counter ++;
                   13061:             $numnew ++;
1.987     raeburn  13062:         }
                   13063:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13064:     }
                   13065:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13066:         if ($actionurl eq '/adm/dependencies') {
                   13067:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13068:             $modify_output .= &start_data_table_row().
                   13069:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13070:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13071:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13072:                               '<td>'.$size.'</td>'.
                   13073:                               '<td>'.$mtime.'</td>'.
                   13074:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13075:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13076:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13077:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13078:                               &embedded_file_element('upload_embedded',$counter,
                   13079:                                                      $embed_file,\%mapping,
                   13080:                                                      $allfiles,$codebase,'modify').
                   13081:                               '</div></td>'.
                   13082:                               &end_data_table_row()."\n";
                   13083:             $counter ++;
                   13084:         } else {
                   13085:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13086:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13087:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13088:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13089:                               &Apache::loncommon::end_data_table_row()."\n";
                   13090:         }
                   13091:     }
                   13092:     my $delidx = $counter;
                   13093:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13094:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13095:         $delete_output .= &start_data_table_row().
                   13096:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13097:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13098:                           '<td>'.$size.'</td>'.
                   13099:                           '<td>'.$mtime.'</td>'.
                   13100:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13101:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13102:                           &embedded_file_element('upload_embedded',$delidx,
                   13103:                                                  $oldfile,\%mapping,$allfiles,
                   13104:                                                  $codebase,'delete').'</td>'.
                   13105:                           &end_data_table_row()."\n"; 
                   13106:         $numunused ++;
                   13107:         $delidx ++;
1.987     raeburn  13108:     }
                   13109:     if ($upload_output) {
                   13110:         $upload_output = &start_data_table().
                   13111:                          $upload_output.
                   13112:                          &end_data_table()."\n";
                   13113:     }
1.1071    raeburn  13114:     if ($modify_output) {
                   13115:         $modify_output = &start_data_table().
                   13116:                          &start_data_table_header_row().
                   13117:                          '<th>'.&mt('File').'</th>'.
                   13118:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13119:                          '<th>'.&mt('Modified').'</th>'.
                   13120:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13121:                          &end_data_table_header_row().
                   13122:                          $modify_output.
                   13123:                          &end_data_table()."\n";
                   13124:     }
                   13125:     if ($delete_output) {
                   13126:         $delete_output = &start_data_table().
                   13127:                          &start_data_table_header_row().
                   13128:                          '<th>'.&mt('File').'</th>'.
                   13129:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13130:                          '<th>'.&mt('Modified').'</th>'.
                   13131:                          '<th>'.&mt('Delete?').'</th>'.
                   13132:                          &end_data_table_header_row().
                   13133:                          $delete_output.
                   13134:                          &end_data_table()."\n";
                   13135:     }
1.987     raeburn  13136:     my $applies = 0;
                   13137:     if ($numremref) {
                   13138:         $applies ++;
                   13139:     }
                   13140:     if ($numinvalid) {
                   13141:         $applies ++;
                   13142:     }
                   13143:     if ($numexisting) {
                   13144:         $applies ++;
                   13145:     }
1.1071    raeburn  13146:     if ($counter || $numunused) {
1.987     raeburn  13147:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13148:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13149:                   $state.'<h3>'.$heading.'</h3>'; 
                   13150:         if ($actionurl eq '/adm/dependencies') {
                   13151:             if ($numnew) {
                   13152:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13153:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13154:                            $upload_output.'<br />'."\n";
                   13155:             }
                   13156:             if ($numexisting) {
                   13157:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13158:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13159:                            $modify_output.'<br />'."\n";
                   13160:                            $buttontext = &mt('Save changes');
                   13161:             }
                   13162:             if ($numunused) {
                   13163:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13164:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13165:                            $delete_output.'<br />'."\n";
                   13166:                            $buttontext = &mt('Save changes');
                   13167:             }
                   13168:         } else {
                   13169:             $output .= $upload_output.'<br />'."\n";
                   13170:         }
                   13171:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13172:                    $counter.'" />'."\n";
                   13173:         if ($actionurl eq '/adm/dependencies') { 
                   13174:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13175:                        $numnew.'" />'."\n";
                   13176:         } elsif ($actionurl eq '') {
1.987     raeburn  13177:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13178:         }
                   13179:     } elsif ($applies) {
                   13180:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13181:         if ($applies > 1) {
                   13182:             $output .=  
1.1123    raeburn  13183:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13184:             if ($numremref) {
                   13185:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13186:             }
                   13187:             if ($numinvalid) {
                   13188:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13189:             }
                   13190:             if ($numexisting) {
                   13191:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13192:             }
                   13193:             $output .= '</ul><br />';
                   13194:         } elsif ($numremref) {
                   13195:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13196:         } elsif ($numinvalid) {
                   13197:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13198:         } elsif ($numexisting) {
                   13199:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13200:         }
                   13201:         $output .= $upload_output.'<br />';
                   13202:     }
                   13203:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13204:     $chgcount = $counter;
1.987     raeburn  13205:     if (keys(%pathchanges) > 0) {
                   13206:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13207:             if ($counter) {
1.987     raeburn  13208:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13209:                                                   $embed_file,\%mapping,
1.1071    raeburn  13210:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13211:             } else {
                   13212:                 $pathchange_output .= 
                   13213:                     &start_data_table_row().
                   13214:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13215:                     $chgcount.'" checked="checked" /></td>'.
                   13216:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13217:                     '<td>'.$embed_file.
                   13218:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13219:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13220:                     '</td>'.&end_data_table_row();
1.660     raeburn  13221:             }
1.987     raeburn  13222:             $numpathchg ++;
                   13223:             $chgcount ++;
1.660     raeburn  13224:         }
                   13225:     }
1.1127    raeburn  13226:     if (($counter) || ($numunused)) {
1.987     raeburn  13227:         if ($numpathchg) {
                   13228:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13229:                        $numpathchg.'" />'."\n";
                   13230:         }
                   13231:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13232:             ($actionurl eq '/adm/imsimport')) {
                   13233:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13234:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13235:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13236:         } elsif ($actionurl eq '/adm/dependencies') {
                   13237:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13238:         }
1.1123    raeburn  13239:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13240:     } elsif ($numpathchg) {
                   13241:         my %pathchange = ();
                   13242:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13243:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13244:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13245:         }
1.987     raeburn  13246:     }
1.1071    raeburn  13247:     return ($output,$counter,$numpathchg);
1.987     raeburn  13248: }
                   13249: 
1.1147    raeburn  13250: =pod
                   13251: 
                   13252: =item * clean_path($name)
                   13253: 
                   13254: Performs clean-up of directories, subdirectories and filename in an
                   13255: embedded object, referenced in an HTML file which is being uploaded
                   13256: to a course or portfolio, where 
                   13257: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13258: checked.
                   13259: 
                   13260: Clean-up is similar to replacements in lonnet::clean_filename()
                   13261: except each / between sub-directory and next level is preserved.
                   13262: 
                   13263: =cut
                   13264: 
                   13265: sub clean_path {
                   13266:     my ($embed_file) = @_;
                   13267:     $embed_file =~s{^/+}{};
                   13268:     my @contents;
                   13269:     if ($embed_file =~ m{/}) {
                   13270:         @contents = split(/\//,$embed_file);
                   13271:     } else {
                   13272:         @contents = ($embed_file);
                   13273:     }
                   13274:     my $lastidx = scalar(@contents)-1;
                   13275:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13276:         $contents[$i]=~s{\\}{/}g;
                   13277:         $contents[$i]=~s/\s+/\_/g;
                   13278:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13279:         if ($i == $lastidx) {
                   13280:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13281:         }
                   13282:     }
                   13283:     if ($lastidx > 0) {
                   13284:         return join('/',@contents);
                   13285:     } else {
                   13286:         return $contents[0];
                   13287:     }
                   13288: }
                   13289: 
1.987     raeburn  13290: sub embedded_file_element {
1.1071    raeburn  13291:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13292:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13293:                    (ref($codebase) eq 'HASH'));
                   13294:     my $output;
1.1071    raeburn  13295:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13296:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13297:     }
                   13298:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13299:                &escape($embed_file).'" />';
                   13300:     unless (($context eq 'upload_embedded') && 
                   13301:             ($mapping->{$embed_file} eq $embed_file)) {
                   13302:         $output .='
                   13303:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13304:     }
                   13305:     my $attrib;
                   13306:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13307:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13308:     }
                   13309:     $output .=
                   13310:         "\n\t\t".
                   13311:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13312:         $attrib.'" />';
                   13313:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13314:         $output .=
                   13315:             "\n\t\t".
                   13316:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13317:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13318:     }
1.987     raeburn  13319:     return $output;
1.660     raeburn  13320: }
                   13321: 
1.1071    raeburn  13322: sub get_dependency_details {
                   13323:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13324:     my ($size,$mtime,$showsize,$showmtime);
                   13325:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13326:         if ($embed_file =~ m{/}) {
                   13327:             my ($path,$fname) = split(/\//,$embed_file);
                   13328:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13329:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13330:             }
                   13331:         } else {
                   13332:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13333:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13334:             }
                   13335:         }
                   13336:         $showsize = $size/1024.0;
                   13337:         $showsize = sprintf("%.1f",$showsize);
                   13338:         if ($mtime > 0) {
                   13339:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13340:         }
                   13341:     }
                   13342:     return ($showsize,$showmtime);
                   13343: }
                   13344: 
                   13345: sub ask_embedded_js {
                   13346:     return <<"END";
                   13347: <script type="text/javascript"">
                   13348: // <![CDATA[
                   13349: function toggleBrowse(counter) {
                   13350:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13351:     var fileid = document.getElementById('embedded_item_'+counter);
                   13352:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13353:     if (chkboxid.checked == true) {
                   13354:         uploaddivid.style.display='block';
                   13355:     } else {
                   13356:         uploaddivid.style.display='none';
                   13357:         fileid.value = '';
                   13358:     }
                   13359: }
                   13360: // ]]>
                   13361: </script>
                   13362: 
                   13363: END
                   13364: }
                   13365: 
1.661     raeburn  13366: sub upload_embedded {
                   13367:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13368:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13369:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13370:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13371:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13372:         my $orig_uploaded_filename =
                   13373:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13374:         foreach my $type ('orig','ref','attrib','codebase') {
                   13375:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13376:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13377:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13378:             }
                   13379:         }
1.661     raeburn  13380:         my ($path,$fname) =
                   13381:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13382:         # no path, whole string is fname
                   13383:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13384:         $fname = &Apache::lonnet::clean_filename($fname);
                   13385:         # See if there is anything left
                   13386:         next if ($fname eq '');
                   13387: 
                   13388:         # Check if file already exists as a file or directory.
                   13389:         my ($state,$msg);
                   13390:         if ($context eq 'portfolio') {
                   13391:             my $port_path = $dirpath;
                   13392:             if ($group ne '') {
                   13393:                 $port_path = "groups/$group/$port_path";
                   13394:             }
1.987     raeburn  13395:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13396:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13397:                                               $dir_root,$port_path,$disk_quota,
                   13398:                                               $current_disk_usage,$uname,$udom);
                   13399:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13400:                 || $state eq 'file_locked') {
1.661     raeburn  13401:                 $output .= $msg;
                   13402:                 next;
                   13403:             }
                   13404:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13405:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13406:             if ($state eq 'exists') {
                   13407:                 $output .= $msg;
                   13408:                 next;
                   13409:             }
                   13410:         }
                   13411:         # Check if extension is valid
                   13412:         if (($fname =~ /\.(\w+)$/) &&
                   13413:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13414:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13415:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13416:             next;
                   13417:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13418:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13419:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13420:             next;
                   13421:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13422:             $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  13423:             next;
                   13424:         }
                   13425:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13426:         my $subdir = $path;
                   13427:         $subdir =~ s{/+$}{};
1.661     raeburn  13428:         if ($context eq 'portfolio') {
1.984     raeburn  13429:             my $result;
                   13430:             if ($state eq 'existingfile') {
                   13431:                 $result=
                   13432:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13433:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13434:             } else {
1.984     raeburn  13435:                 $result=
                   13436:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13437:                                                     $dirpath.
1.1123    raeburn  13438:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13439:                 if ($result !~ m|^/uploaded/|) {
                   13440:                     $output .= '<span class="LC_error">'
                   13441:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13442:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13443:                                .'</span><br />';
                   13444:                     next;
                   13445:                 } else {
1.987     raeburn  13446:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13447:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13448:                 }
1.661     raeburn  13449:             }
1.1123    raeburn  13450:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13451:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13452:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13453:             my $result =
1.1126    raeburn  13454:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13455:             if ($result !~ m|^/uploaded/|) {
                   13456:                 $output .= '<span class="LC_error">'
                   13457:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13458:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13459:                            .'</span><br />';
                   13460:                     next;
                   13461:             } else {
                   13462:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13463:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13464:                 if ($context eq 'syllabus') {
                   13465:                     &Apache::lonnet::make_public_indefinitely($result);
                   13466:                 }
1.987     raeburn  13467:             }
1.661     raeburn  13468:         } else {
                   13469: # Save the file
                   13470:             my $target = $env{'form.embedded_item_'.$i};
                   13471:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13472:             my $dest = $fullpath.$fname;
                   13473:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13474:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13475:             my $count;
                   13476:             my $filepath = $dir_root;
1.1027    raeburn  13477:             foreach my $subdir (@parts) {
                   13478:                 $filepath .= "/$subdir";
                   13479:                 if (!-e $filepath) {
1.661     raeburn  13480:                     mkdir($filepath,0770);
                   13481:                 }
                   13482:             }
                   13483:             my $fh;
                   13484:             if (!open($fh,'>'.$dest)) {
                   13485:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13486:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13487:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13488:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13489:                            '</span><br />';
                   13490:             } else {
                   13491:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13492:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13493:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13494:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13495:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13496:                               '</span><br />';
                   13497:                 } else {
1.987     raeburn  13498:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13499:                                $url.'</span>').'<br />';
                   13500:                     unless ($context eq 'testbank') {
                   13501:                         $footer .= &mt('View embedded file: [_1]',
                   13502:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13503:                     }
                   13504:                 }
                   13505:                 close($fh);
                   13506:             }
                   13507:         }
                   13508:         if ($env{'form.embedded_ref_'.$i}) {
                   13509:             $pathchange{$i} = 1;
                   13510:         }
                   13511:     }
                   13512:     if ($output) {
                   13513:         $output = '<p>'.$output.'</p>';
                   13514:     }
                   13515:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13516:     $returnflag = 'ok';
1.1071    raeburn  13517:     my $numpathchgs = scalar(keys(%pathchange));
                   13518:     if ($numpathchgs > 0) {
1.987     raeburn  13519:         if ($context eq 'portfolio') {
                   13520:             $output .= '<p>'.&mt('or').'</p>';
                   13521:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13522:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13523:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13524:             $returnflag = 'modify_orightml';
                   13525:         }
                   13526:     }
1.1071    raeburn  13527:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13528: }
                   13529: 
                   13530: sub modify_html_form {
                   13531:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13532:     my $end = 0;
                   13533:     my $modifyform;
                   13534:     if ($context eq 'upload_embedded') {
                   13535:         return unless (ref($pathchange) eq 'HASH');
                   13536:         if ($env{'form.number_embedded_items'}) {
                   13537:             $end += $env{'form.number_embedded_items'};
                   13538:         }
                   13539:         if ($env{'form.number_pathchange_items'}) {
                   13540:             $end += $env{'form.number_pathchange_items'};
                   13541:         }
                   13542:         if ($end) {
                   13543:             for (my $i=0; $i<$end; $i++) {
                   13544:                 if ($i < $env{'form.number_embedded_items'}) {
                   13545:                     next unless($pathchange->{$i});
                   13546:                 }
                   13547:                 $modifyform .=
                   13548:                     &start_data_table_row().
                   13549:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13550:                     'checked="checked" /></td>'.
                   13551:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13552:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13553:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13554:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13555:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13556:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13557:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13558:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13559:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13560:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13561:                     &end_data_table_row();
1.1071    raeburn  13562:             }
1.987     raeburn  13563:         }
                   13564:     } else {
                   13565:         $modifyform = $pathchgtable;
                   13566:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13567:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13568:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13569:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13570:         }
                   13571:     }
                   13572:     if ($modifyform) {
1.1071    raeburn  13573:         if ($actionurl eq '/adm/dependencies') {
                   13574:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13575:         }
1.987     raeburn  13576:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13577:                '<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".
                   13578:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13579:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13580:                '</ol></p>'."\n".'<p>'.
                   13581:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13582:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13583:                &start_data_table()."\n".
                   13584:                &start_data_table_header_row().
                   13585:                '<th>'.&mt('Change?').'</th>'.
                   13586:                '<th>'.&mt('Current reference').'</th>'.
                   13587:                '<th>'.&mt('Required reference').'</th>'.
                   13588:                &end_data_table_header_row()."\n".
                   13589:                $modifyform.
                   13590:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13591:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13592:                '</form>'."\n";
                   13593:     }
                   13594:     return;
                   13595: }
                   13596: 
                   13597: sub modify_html_refs {
1.1123    raeburn  13598:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13599:     my $container;
                   13600:     if ($context eq 'portfolio') {
                   13601:         $container = $env{'form.container'};
                   13602:     } elsif ($context eq 'coursedoc') {
                   13603:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13604:     } elsif ($context eq 'manage_dependencies') {
                   13605:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13606:         $container = "/$container";
1.1123    raeburn  13607:     } elsif ($context eq 'syllabus') {
                   13608:         $container = $url;
1.987     raeburn  13609:     } else {
1.1027    raeburn  13610:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13611:     }
                   13612:     my (%allfiles,%codebase,$output,$content);
                   13613:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13614:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13615:         if (wantarray) {
                   13616:             return ('',0,0); 
                   13617:         } else {
                   13618:             return;
                   13619:         }
                   13620:     }
                   13621:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13622:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13623:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13624:             if (wantarray) {
                   13625:                 return ('',0,0);
                   13626:             } else {
                   13627:                 return;
                   13628:             }
                   13629:         } 
1.987     raeburn  13630:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13631:         if ($content eq '-1') {
                   13632:             if (wantarray) {
                   13633:                 return ('',0,0);
                   13634:             } else {
                   13635:                 return;
                   13636:             }
                   13637:         }
1.987     raeburn  13638:     } else {
1.1071    raeburn  13639:         unless ($container =~ /^\Q$dir_root\E/) {
                   13640:             if (wantarray) {
                   13641:                 return ('',0,0);
                   13642:             } else {
                   13643:                 return;
                   13644:             }
                   13645:         } 
1.1317    raeburn  13646:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13647:             $content = join('', <$fh>);
                   13648:             close($fh);
                   13649:         } else {
1.1071    raeburn  13650:             if (wantarray) {
                   13651:                 return ('',0,0);
                   13652:             } else {
                   13653:                 return;
                   13654:             }
1.987     raeburn  13655:         }
                   13656:     }
                   13657:     my ($count,$codebasecount) = (0,0);
                   13658:     my $mm = new File::MMagic;
                   13659:     my $mime_type = $mm->checktype_contents($content);
                   13660:     if ($mime_type eq 'text/html') {
                   13661:         my $parse_result = 
                   13662:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13663:                                                     \%codebase,\$content);
                   13664:         if ($parse_result eq 'ok') {
                   13665:             foreach my $i (@changes) {
                   13666:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13667:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13668:                 if ($allfiles{$ref}) {
                   13669:                     my $newname =  $orig;
                   13670:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13671:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13672:                     if ($attrib_regexp =~ /:/) {
                   13673:                         $attrib_regexp =~ s/\:/|/g;
                   13674:                     }
                   13675:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13676:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13677:                         $count += $numchg;
1.1123    raeburn  13678:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13679:                         delete($allfiles{$ref});
1.987     raeburn  13680:                     }
                   13681:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13682:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13683:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13684:                         $codebasecount ++;
                   13685:                     }
                   13686:                 }
                   13687:             }
1.1123    raeburn  13688:             my $skiprewrites;
1.987     raeburn  13689:             if ($count || $codebasecount) {
                   13690:                 my $saveresult;
1.1071    raeburn  13691:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13692:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13693:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13694:                     if ($url eq $container) {
                   13695:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13696:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13697:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13698:                                             $fname.'</span>').'</p>';
1.987     raeburn  13699:                     } else {
                   13700:                          $output = '<p class="LC_error">'.
                   13701:                                    &mt('Error: update failed for: [_1].',
                   13702:                                    '<span class="LC_filename">'.
                   13703:                                    $container.'</span>').'</p>';
                   13704:                     }
1.1123    raeburn  13705:                     if ($context eq 'syllabus') {
                   13706:                         unless ($saveresult eq 'ok') {
                   13707:                             $skiprewrites = 1;
                   13708:                         }
                   13709:                     }
1.987     raeburn  13710:                 } else {
1.1317    raeburn  13711:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13712:                         print $fh $content;
                   13713:                         close($fh);
                   13714:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13715:                                   $count,'<span class="LC_filename">'.
                   13716:                                   $container.'</span>').'</p>';
1.661     raeburn  13717:                     } else {
1.987     raeburn  13718:                          $output = '<p class="LC_error">'.
                   13719:                                    &mt('Error: could not update [_1].',
                   13720:                                    '<span class="LC_filename">'.
                   13721:                                    $container.'</span>').'</p>';
1.661     raeburn  13722:                     }
                   13723:                 }
                   13724:             }
1.1123    raeburn  13725:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13726:                 my ($actionurl,$state);
                   13727:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13728:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13729:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13730:                                               \%codebase,
                   13731:                                               {'context' => 'rewrites',
                   13732:                                                'ignore_remote_references' => 1,});
                   13733:                 if (ref($mapping) eq 'HASH') {
                   13734:                     my $rewrites = 0;
                   13735:                     foreach my $key (keys(%{$mapping})) {
                   13736:                         next if ($key =~ m{^https?://});
                   13737:                         my $ref = $mapping->{$key};
                   13738:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13739:                         my $attrib;
                   13740:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13741:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13742:                         }
                   13743:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13744:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13745:                             $rewrites += $numchg;
                   13746:                         }
                   13747:                     }
                   13748:                     if ($rewrites) {
                   13749:                         my $saveresult; 
                   13750:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13751:                         if ($url eq $container) {
                   13752:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13753:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13754:                                             $count,'<span class="LC_filename">'.
                   13755:                                             $fname.'</span>').'</p>';
                   13756:                         } else {
                   13757:                             $output .= '<p class="LC_error">'.
                   13758:                                        &mt('Error: could not update links in [_1].',
                   13759:                                        '<span class="LC_filename">'.
                   13760:                                        $container.'</span>').'</p>';
                   13761: 
                   13762:                         }
                   13763:                     }
                   13764:                 }
                   13765:             }
1.987     raeburn  13766:         } else {
                   13767:             &logthis('Failed to parse '.$container.
                   13768:                      ' to modify references: '.$parse_result);
1.661     raeburn  13769:         }
                   13770:     }
1.1071    raeburn  13771:     if (wantarray) {
                   13772:         return ($output,$count,$codebasecount);
                   13773:     } else {
                   13774:         return $output;
                   13775:     }
1.661     raeburn  13776: }
                   13777: 
                   13778: sub check_for_existing {
                   13779:     my ($path,$fname,$element) = @_;
                   13780:     my ($state,$msg);
                   13781:     if (-d $path.'/'.$fname) {
                   13782:         $state = 'exists';
                   13783:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13784:     } elsif (-e $path.'/'.$fname) {
                   13785:         $state = 'exists';
                   13786:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13787:     }
                   13788:     if ($state eq 'exists') {
                   13789:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13790:     }
                   13791:     return ($state,$msg);
                   13792: }
                   13793: 
                   13794: sub check_for_upload {
                   13795:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13796:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13797:     my $filesize = length($env{'form.'.$element});
                   13798:     if (!$filesize) {
                   13799:         my $msg = '<span class="LC_error">'.
                   13800:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13801:                       '<span class="LC_filename">'.$fname.'</span>',
                   13802:                       $filesize).'<br />'.
1.1007    raeburn  13803:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13804:                   '</span>';
                   13805:         return ('zero_bytes',$msg);
                   13806:     }
                   13807:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13808:     my $getpropath = 1;
1.1021    raeburn  13809:     my ($dirlistref,$listerror) =
                   13810:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13811:     my $found_file = 0;
                   13812:     my $locked_file = 0;
1.991     raeburn  13813:     my @lockers;
                   13814:     my $navmap;
                   13815:     if ($env{'request.course.id'}) {
                   13816:         $navmap = Apache::lonnavmaps::navmap->new();
                   13817:     }
1.1021    raeburn  13818:     if (ref($dirlistref) eq 'ARRAY') {
                   13819:         foreach my $line (@{$dirlistref}) {
                   13820:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13821:             if ($file_name eq $fname){
                   13822:                 $file_name = $path.$file_name;
                   13823:                 if ($group ne '') {
                   13824:                     $file_name = $group.$file_name;
                   13825:                 }
                   13826:                 $found_file = 1;
                   13827:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13828:                     foreach my $lock (@lockers) {
                   13829:                         if (ref($lock) eq 'ARRAY') {
                   13830:                             my ($symb,$crsid) = @{$lock};
                   13831:                             if ($crsid eq $env{'request.course.id'}) {
                   13832:                                 if (ref($navmap)) {
                   13833:                                     my $res = $navmap->getBySymb($symb);
                   13834:                                     foreach my $part (@{$res->parts()}) { 
                   13835:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13836:                                         unless (($slot_status == $res->RESERVED) ||
                   13837:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13838:                                             $locked_file = 1;
                   13839:                                         }
1.991     raeburn  13840:                                     }
1.1021    raeburn  13841:                                 } else {
                   13842:                                     $locked_file = 1;
1.991     raeburn  13843:                                 }
                   13844:                             } else {
                   13845:                                 $locked_file = 1;
                   13846:                             }
                   13847:                         }
1.1021    raeburn  13848:                    }
                   13849:                 } else {
                   13850:                     my @info = split(/\&/,$rest);
                   13851:                     my $currsize = $info[6]/1000;
                   13852:                     if ($currsize < $filesize) {
                   13853:                         my $extra = $filesize - $currsize;
                   13854:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13855:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13856:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1179    bisitz   13857:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13858:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13859:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13860:                             return ('will_exceed_quota',$msg);
                   13861:                         }
1.984     raeburn  13862:                     }
                   13863:                 }
1.661     raeburn  13864:             }
                   13865:         }
                   13866:     }
                   13867:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13868:         my $msg = '<p class="LC_warning">'.
                   13869:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13870:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13871:         return ('will_exceed_quota',$msg);
                   13872:     } elsif ($found_file) {
                   13873:         if ($locked_file) {
1.1179    bisitz   13874:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13875:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1179    bisitz   13876:             $msg .= '</p>';
1.661     raeburn  13877:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13878:             return ('file_locked',$msg);
                   13879:         } else {
1.1179    bisitz   13880:             my $msg = '<p class="LC_error">';
1.984     raeburn  13881:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   13882:             $msg .= '</p>';
1.984     raeburn  13883:             return ('existingfile',$msg);
1.661     raeburn  13884:         }
                   13885:     }
                   13886: }
                   13887: 
1.987     raeburn  13888: sub check_for_traversal {
                   13889:     my ($path,$url,$toplevel) = @_;
                   13890:     my @parts=split(/\//,$path);
                   13891:     my $cleanpath;
                   13892:     my $fullpath = $url;
                   13893:     for (my $i=0;$i<@parts;$i++) {
                   13894:         next if ($parts[$i] eq '.');
                   13895:         if ($parts[$i] eq '..') {
                   13896:             $fullpath =~ s{([^/]+/)$}{};
                   13897:         } else {
                   13898:             $fullpath .= $parts[$i].'/';
                   13899:         }
                   13900:     }
                   13901:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13902:         $cleanpath = $1;
                   13903:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13904:         my $curr_toprel = $1;
                   13905:         my @parts = split(/\//,$curr_toprel);
                   13906:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13907:         my @urlparts = split(/\//,$url_toprel);
                   13908:         my $doubledots;
                   13909:         my $startdiff = -1;
                   13910:         for (my $i=0; $i<@urlparts; $i++) {
                   13911:             if ($startdiff == -1) {
                   13912:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13913:                     $startdiff = $i;
                   13914:                     $doubledots .= '../';
                   13915:                 }
                   13916:             } else {
                   13917:                 $doubledots .= '../';
                   13918:             }
                   13919:         }
                   13920:         if ($startdiff > -1) {
                   13921:             $cleanpath = $doubledots;
                   13922:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13923:                 $cleanpath .= $parts[$i].'/';
                   13924:             }
                   13925:         }
                   13926:     }
                   13927:     $cleanpath =~ s{(/)$}{};
                   13928:     return $cleanpath;
                   13929: }
1.31      albertel 13930: 
1.1053    raeburn  13931: sub is_archive_file {
                   13932:     my ($mimetype) = @_;
                   13933:     if (($mimetype eq 'application/octet-stream') ||
                   13934:         ($mimetype eq 'application/x-stuffit') ||
                   13935:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13936:         return 1;
                   13937:     }
                   13938:     return;
                   13939: }
                   13940: 
                   13941: sub decompress_form {
1.1065    raeburn  13942:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13943:     my %lt = &Apache::lonlocal::texthash (
                   13944:         this => 'This file is an archive file.',
1.1067    raeburn  13945:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13946:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13947:         youm => 'You may wish to extract its contents.',
                   13948:         extr => 'Extract contents',
1.1067    raeburn  13949:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13950:         proa => 'Process automatically?',
1.1053    raeburn  13951:         yes  => 'Yes',
                   13952:         no   => 'No',
1.1067    raeburn  13953:         fold => 'Title for folder containing movie',
                   13954:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13955:     );
1.1065    raeburn  13956:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13957:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13958:     my $info = &list_archive_contents($fileloc,\@paths);
                   13959:     if (@paths) {
                   13960:         foreach my $path (@paths) {
                   13961:             $path =~ s{^/}{};
1.1067    raeburn  13962:             if ($path =~ m{^([^/]+)/$}) {
                   13963:                 $topdir = $1;
                   13964:             }
1.1065    raeburn  13965:             if ($path =~ m{^([^/]+)/}) {
                   13966:                 $toplevel{$1} = $path;
                   13967:             } else {
                   13968:                 $toplevel{$path} = $path;
                   13969:             }
                   13970:         }
                   13971:     }
1.1067    raeburn  13972:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13973:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13974:                         "$topdir/media/",
                   13975:                         "$topdir/media/$topdir.mp4",
                   13976:                         "$topdir/media/FirstFrame.png",
                   13977:                         "$topdir/media/player.swf",
                   13978:                         "$topdir/media/swfobject.js",
                   13979:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13980:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13981:                          "$topdir/$topdir.mp4",
                   13982:                          "$topdir/$topdir\_config.xml",
                   13983:                          "$topdir/$topdir\_controller.swf",
                   13984:                          "$topdir/$topdir\_embed.css",
                   13985:                          "$topdir/$topdir\_First_Frame.png",
                   13986:                          "$topdir/$topdir\_player.html",
                   13987:                          "$topdir/$topdir\_Thumbnails.png",
                   13988:                          "$topdir/playerProductInstall.swf",
                   13989:                          "$topdir/scripts/",
                   13990:                          "$topdir/scripts/config_xml.js",
                   13991:                          "$topdir/scripts/handlebars.js",
                   13992:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13993:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13994:                          "$topdir/scripts/modernizr.js",
                   13995:                          "$topdir/scripts/player-min.js",
                   13996:                          "$topdir/scripts/swfobject.js",
                   13997:                          "$topdir/skins/",
                   13998:                          "$topdir/skins/configuration_express.xml",
                   13999:                          "$topdir/skins/express_show/",
                   14000:                          "$topdir/skins/express_show/player-min.css",
                   14001:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  14002:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   14003:                          "$topdir/$topdir.mp4",
                   14004:                          "$topdir/$topdir\_config.xml",
                   14005:                          "$topdir/$topdir\_controller.swf",
                   14006:                          "$topdir/$topdir\_embed.css",
                   14007:                          "$topdir/$topdir\_First_Frame.png",
                   14008:                          "$topdir/$topdir\_player.html",
                   14009:                          "$topdir/$topdir\_Thumbnails.png",
                   14010:                          "$topdir/playerProductInstall.swf",
                   14011:                          "$topdir/scripts/",
                   14012:                          "$topdir/scripts/config_xml.js",
                   14013:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   14014:                          "$topdir/skins/",
                   14015:                          "$topdir/skins/configuration_express.xml",
                   14016:                          "$topdir/skins/express_show/",
                   14017:                          "$topdir/skins/express_show/spritesheet.min.css",
                   14018:                          "$topdir/skins/express_show/spritesheet.png",
                   14019:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  14020:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  14021:         if (@diffs == 0) {
1.1164    raeburn  14022:             $is_camtasia = 6;
                   14023:         } else {
1.1197    raeburn  14024:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  14025:             if (@diffs == 0) {
                   14026:                 $is_camtasia = 8;
1.1197    raeburn  14027:             } else {
                   14028:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   14029:                 if (@diffs == 0) {
                   14030:                     $is_camtasia = 8;
                   14031:                 }
1.1164    raeburn  14032:             }
1.1067    raeburn  14033:         }
                   14034:     }
                   14035:     my $output;
                   14036:     if ($is_camtasia) {
                   14037:         $output = <<"ENDCAM";
                   14038: <script type="text/javascript" language="Javascript">
                   14039: // <![CDATA[
                   14040: 
                   14041: function camtasiaToggle() {
                   14042:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14043:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14044:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14045:                 document.getElementById('camtasia_titles').style.display='block';
                   14046:             } else {
                   14047:                 document.getElementById('camtasia_titles').style.display='none';
                   14048:             }
                   14049:         }
                   14050:     }
                   14051:     return;
                   14052: }
                   14053: 
                   14054: // ]]>
                   14055: </script>
                   14056: <p>$lt{'camt'}</p>
                   14057: ENDCAM
1.1065    raeburn  14058:     } else {
1.1067    raeburn  14059:         $output = '<p>'.$lt{'this'};
                   14060:         if ($info eq '') {
                   14061:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14062:         } else {
                   14063:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14064:                        '<div><pre>'.$info.'</pre></div>';
                   14065:         }
1.1065    raeburn  14066:     }
1.1067    raeburn  14067:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14068:     my $duplicates;
                   14069:     my $num = 0;
                   14070:     if (ref($dirlist) eq 'ARRAY') {
                   14071:         foreach my $item (@{$dirlist}) {
                   14072:             if (ref($item) eq 'ARRAY') {
                   14073:                 if (exists($toplevel{$item->[0]})) {
                   14074:                     $duplicates .= 
                   14075:                         &start_data_table_row().
                   14076:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14077:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14078:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14079:                         'value="1" />'.&mt('Yes').'</label>'.
                   14080:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14081:                         '<td>'.$item->[0].'</td>';
                   14082:                     if ($item->[2]) {
                   14083:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14084:                     } else {
                   14085:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14086:                     }
                   14087:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14088:                                    '<td>'.
                   14089:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14090:                                    '</td>'.
                   14091:                                    &end_data_table_row();
                   14092:                     $num ++;
                   14093:                 }
                   14094:             }
                   14095:         }
                   14096:     }
                   14097:     my $itemcount;
                   14098:     if (@paths > 0) {
                   14099:         $itemcount = scalar(@paths);
                   14100:     } else {
                   14101:         $itemcount = 1;
                   14102:     }
1.1067    raeburn  14103:     if ($is_camtasia) {
                   14104:         $output .= $lt{'auto'}.'<br />'.
                   14105:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14106:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14107:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14108:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14109:                    $lt{'no'}.'</label></span><br />'.
                   14110:                    '<div id="camtasia_titles" style="display:block">'.
                   14111:                    &Apache::lonhtmlcommon::start_pick_box().
                   14112:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14113:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14114:                    &Apache::lonhtmlcommon::row_closure().
                   14115:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14116:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14117:                    &Apache::lonhtmlcommon::row_closure(1).
                   14118:                    &Apache::lonhtmlcommon::end_pick_box().
                   14119:                    '</div>';
                   14120:     }
1.1065    raeburn  14121:     $output .= 
                   14122:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14123:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14124:         "\n";
1.1065    raeburn  14125:     if ($duplicates ne '') {
                   14126:         $output .= '<p><span class="LC_warning">'.
                   14127:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14128:                    &start_data_table().
                   14129:                    &start_data_table_header_row().
                   14130:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14131:                    '<th>'.&mt('Name').'</th>'.
                   14132:                    '<th>'.&mt('Type').'</th>'.
                   14133:                    '<th>'.&mt('Size').'</th>'.
                   14134:                    '<th>'.&mt('Last modified').'</th>'.
                   14135:                    &end_data_table_header_row().
                   14136:                    $duplicates.
                   14137:                    &end_data_table().
                   14138:                    '</p>';
                   14139:     }
1.1067    raeburn  14140:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14141:     if (ref($hiddenelements) eq 'HASH') {
                   14142:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14143:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14144:         }
                   14145:     }
                   14146:     $output .= <<"END";
1.1067    raeburn  14147: <br />
1.1053    raeburn  14148: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14149: </form>
                   14150: $noextract
                   14151: END
                   14152:     return $output;
                   14153: }
                   14154: 
1.1065    raeburn  14155: sub decompression_utility {
                   14156:     my ($program) = @_;
                   14157:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14158:     my $location;
                   14159:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14160:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14161:                          '/usr/sbin/') {
                   14162:             if (-x $dir.$program) {
                   14163:                 $location = $dir.$program;
                   14164:                 last;
                   14165:             }
                   14166:         }
                   14167:     }
                   14168:     return $location;
                   14169: }
                   14170: 
                   14171: sub list_archive_contents {
                   14172:     my ($file,$pathsref) = @_;
                   14173:     my (@cmd,$output);
                   14174:     my $needsregexp;
                   14175:     if ($file =~ /\.zip$/) {
                   14176:         @cmd = (&decompression_utility('unzip'),"-l");
                   14177:         $needsregexp = 1;
                   14178:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14179:              ($file =~ /\.tgz$/)) {
                   14180:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14181:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14182:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14183:     } elsif ($file =~ m|\.tar$|) {
                   14184:         @cmd = (&decompression_utility('tar'),"-tf");
                   14185:     }
                   14186:     if (@cmd) {
                   14187:         undef($!);
                   14188:         undef($@);
                   14189:         if (open(my $fh,"-|", @cmd, $file)) {
                   14190:             while (my $line = <$fh>) {
                   14191:                 $output .= $line;
                   14192:                 chomp($line);
                   14193:                 my $item;
                   14194:                 if ($needsregexp) {
                   14195:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14196:                 } else {
                   14197:                     $item = $line;
                   14198:                 }
                   14199:                 if ($item ne '') {
                   14200:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14201:                         push(@{$pathsref},$item);
                   14202:                     } 
                   14203:                 }
                   14204:             }
                   14205:             close($fh);
                   14206:         }
                   14207:     }
                   14208:     return $output;
                   14209: }
                   14210: 
1.1053    raeburn  14211: sub decompress_uploaded_file {
                   14212:     my ($file,$dir) = @_;
                   14213:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14214:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14215:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14216:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14217:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14218:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14219:     my $decompressed = $env{'cgi.decompressed'};
                   14220:     &Apache::lonnet::delenv('cgi.file');
                   14221:     &Apache::lonnet::delenv('cgi.dir');
                   14222:     &Apache::lonnet::delenv('cgi.decompressed');
                   14223:     return ($decompressed,$result);
                   14224: }
                   14225: 
1.1055    raeburn  14226: sub process_decompression {
                   14227:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14228:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14229:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14230:                &mt('Unexpected file path.').'</p>'."\n";
                   14231:     }
                   14232:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14233:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14234:                &mt('Unexpected course context.').'</p>'."\n";
                   14235:     }
1.1293    raeburn  14236:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14237:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14238:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14239:     }
1.1055    raeburn  14240:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14241:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14242:         $error = &mt('Filename not a supported archive file type.').
                   14243:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14244:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14245:     } else {
                   14246:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14247:         if ($docuhome eq 'no_host') {
                   14248:             $error = &mt('Could not determine home server for course.');
                   14249:         } else {
                   14250:             my @ids=&Apache::lonnet::current_machine_ids();
                   14251:             my $currdir = "$dir_root/$destination";
                   14252:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14253:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14254:                        "$dir_root/$destination";
                   14255:             } else {
                   14256:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14257:                        "$dir_root/$docudom/$docuname/$destination";
                   14258:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14259:                     $error = &mt('Archive file not found.');
                   14260:                 }
                   14261:             }
1.1065    raeburn  14262:             my (@to_overwrite,@to_skip);
                   14263:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14264:                 my $total = $env{'form.archive_overwrite_total'};
                   14265:                 for (my $i=0; $i<$total; $i++) {
                   14266:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14267:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14268:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14269:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14270:                     }
                   14271:                 }
                   14272:             }
                   14273:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14274:             my $numoverwrite = scalar(@to_overwrite);
                   14275:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14276:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14277:             } elsif ($dir eq '') {
1.1055    raeburn  14278:                 $error = &mt('Directory containing archive file unavailable.');
                   14279:             } elsif (!$error) {
1.1065    raeburn  14280:                 my ($decompressed,$display);
1.1292    raeburn  14281:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14282:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14283:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14284:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14285:                         ($decompressed,$display) = 
                   14286:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14287:                         foreach my $item (@to_skip) {
                   14288:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14289:                                 if (-f "$dir/$tempdir/$item") { 
                   14290:                                     unlink("$dir/$tempdir/$item");
                   14291:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14292:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14293:                                 }
                   14294:                             }
                   14295:                         }
                   14296:                         foreach my $item (@to_overwrite) {
                   14297:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14298:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14299:                                     if (-f "$dir/$item") {
                   14300:                                         unlink("$dir/$item");
                   14301:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14302:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14303:                                     }
                   14304:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14305:                                 }
1.1065    raeburn  14306:                             }
                   14307:                         }
1.1292    raeburn  14308:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14309:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14310:                         }
1.1065    raeburn  14311:                     }
                   14312:                 } else {
                   14313:                     ($decompressed,$display) = 
                   14314:                         &decompress_uploaded_file($file,$dir);
                   14315:                 }
1.1055    raeburn  14316:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14317:                     $output = '<p class="LC_info">'.
                   14318:                               &mt('Files extracted successfully from archive.').
                   14319:                               '</p>'."\n";
1.1055    raeburn  14320:                     my ($warning,$result,@contents);
                   14321:                     my ($newdirlistref,$newlisterror) =
                   14322:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14323:                                                  $docuname,1);
                   14324:                     my (%is_dir,%changes,@newitems);
                   14325:                     my $dirptr = 16384;
1.1065    raeburn  14326:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14327:                         foreach my $dir_line (@{$newdirlistref}) {
                   14328:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14329:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14330:                                 push(@newitems,$item);
                   14331:                                 if ($dirptr&$testdir) {
                   14332:                                     $is_dir{$item} = 1;
                   14333:                                 }
                   14334:                                 $changes{$item} = 1;
                   14335:                             }
                   14336:                         }
                   14337:                     }
                   14338:                     if (keys(%changes) > 0) {
                   14339:                         foreach my $item (sort(@newitems)) {
                   14340:                             if ($changes{$item}) {
                   14341:                                 push(@contents,$item);
                   14342:                             }
                   14343:                         }
                   14344:                     }
                   14345:                     if (@contents > 0) {
1.1067    raeburn  14346:                         my $wantform;
                   14347:                         unless ($env{'form.autoextract_camtasia'}) {
                   14348:                             $wantform = 1;
                   14349:                         }
1.1056    raeburn  14350:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14351:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14352:                                                                 $currdir,\%is_dir,
                   14353:                                                                 \%children,\%parent,
1.1056    raeburn  14354:                                                                 \@contents,\%dirorder,
                   14355:                                                                 \%titles,$wantform);
1.1055    raeburn  14356:                         if ($datatable ne '') {
                   14357:                             $output .= &archive_options_form('decompressed',$datatable,
                   14358:                                                              $count,$hiddenelem);
1.1065    raeburn  14359:                             my $startcount = 6;
1.1055    raeburn  14360:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14361:                                                            \%titles,\%children);
1.1055    raeburn  14362:                         }
1.1067    raeburn  14363:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14364:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14365:                             my %displayed;
                   14366:                             my $total = 1;
                   14367:                             $env{'form.archive_directory'} = [];
                   14368:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14369:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14370:                                 $path =~ s{/$}{};
                   14371:                                 my $item;
                   14372:                                 if ($path ne '') {
                   14373:                                     $item = "$path/$titles{$i}";
                   14374:                                 } else {
                   14375:                                     $item = $titles{$i};
                   14376:                                 }
                   14377:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14378:                                 if ($item eq $contents[0]) {
                   14379:                                     push(@{$env{'form.archive_directory'}},$i);
                   14380:                                     $env{'form.archive_'.$i} = 'display';
                   14381:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14382:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14383:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14384:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14385:                                     $env{'form.archive_'.$i} = 'display';
                   14386:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14387:                                     $displayed{'web'} = $i;
                   14388:                                 } else {
1.1164    raeburn  14389:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14390:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14391:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14392:                                         push(@{$env{'form.archive_directory'}},$i);
                   14393:                                     }
                   14394:                                     $env{'form.archive_'.$i} = 'dependency';
                   14395:                                 }
                   14396:                                 $total ++;
                   14397:                             }
                   14398:                             for (my $i=1; $i<$total; $i++) {
                   14399:                                 next if ($i == $displayed{'web'});
                   14400:                                 next if ($i == $displayed{'folder'});
                   14401:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14402:                             }
                   14403:                             $env{'form.phase'} = 'decompress_cleanup';
                   14404:                             $env{'form.archivedelete'} = 1;
                   14405:                             $env{'form.archive_count'} = $total-1;
                   14406:                             $output .=
                   14407:                                 &process_extracted_files('coursedocs',$docudom,
                   14408:                                                          $docuname,$destination,
                   14409:                                                          $dir_root,$hiddenelem);
                   14410:                         }
1.1055    raeburn  14411:                     } else {
                   14412:                         $warning = &mt('No new items extracted from archive file.');
                   14413:                     }
                   14414:                 } else {
                   14415:                     $output = $display;
                   14416:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14417:                 }
                   14418:             }
                   14419:         }
                   14420:     }
                   14421:     if ($error) {
                   14422:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14423:                    $error.'</p>'."\n";
                   14424:     }
                   14425:     if ($warning) {
                   14426:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14427:     }
                   14428:     return $output;
                   14429: }
                   14430: 
                   14431: sub get_extracted {
1.1056    raeburn  14432:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14433:         $titles,$wantform) = @_;
1.1055    raeburn  14434:     my $count = 0;
                   14435:     my $depth = 0;
                   14436:     my $datatable;
1.1056    raeburn  14437:     my @hierarchy;
1.1055    raeburn  14438:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14439:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14440:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14441:     foreach my $item (@{$contents}) {
                   14442:         $count ++;
1.1056    raeburn  14443:         @{$dirorder->{$count}} = @hierarchy;
                   14444:         $titles->{$count} = $item;
1.1055    raeburn  14445:         &archive_hierarchy($depth,$count,$parent,$children);
                   14446:         if ($wantform) {
                   14447:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14448:                                        $currdir,$depth,$count);
                   14449:         }
                   14450:         if ($is_dir->{$item}) {
                   14451:             $depth ++;
1.1056    raeburn  14452:             push(@hierarchy,$count);
                   14453:             $parent->{$depth} = $count;
1.1055    raeburn  14454:             $datatable .=
                   14455:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14456:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14457:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14458:             $depth --;
1.1056    raeburn  14459:             pop(@hierarchy);
1.1055    raeburn  14460:         }
                   14461:     }
                   14462:     return ($count,$datatable);
                   14463: }
                   14464: 
                   14465: sub recurse_extracted_archive {
1.1056    raeburn  14466:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14467:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14468:     my $result='';
1.1056    raeburn  14469:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14470:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14471:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14472:         return $result;
                   14473:     }
                   14474:     my $dirptr = 16384;
                   14475:     my ($newdirlistref,$newlisterror) =
                   14476:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14477:     if (ref($newdirlistref) eq 'ARRAY') {
                   14478:         foreach my $dir_line (@{$newdirlistref}) {
                   14479:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14480:             unless ($item =~ /^\.+$/) {
                   14481:                 $$count ++;
1.1056    raeburn  14482:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14483:                 $titles->{$$count} = $item;
1.1055    raeburn  14484:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14485: 
1.1055    raeburn  14486:                 my $is_dir;
                   14487:                 if ($dirptr&$testdir) {
                   14488:                     $is_dir = 1;
                   14489:                 }
                   14490:                 if ($wantform) {
                   14491:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14492:                 }
                   14493:                 if ($is_dir) {
                   14494:                     $$depth ++;
1.1056    raeburn  14495:                     push(@{$hierarchy},$$count);
                   14496:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14497:                     $result .=
                   14498:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14499:                                                    $docuname,$depth,$count,
1.1056    raeburn  14500:                                                    $hierarchy,$dirorder,$children,
                   14501:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14502:                     $$depth --;
1.1056    raeburn  14503:                     pop(@{$hierarchy});
1.1055    raeburn  14504:                 }
                   14505:             }
                   14506:         }
                   14507:     }
                   14508:     return $result;
                   14509: }
                   14510: 
                   14511: sub archive_hierarchy {
                   14512:     my ($depth,$count,$parent,$children) =@_;
                   14513:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14514:         if (exists($parent->{$depth})) {
                   14515:              $children->{$parent->{$depth}} .= $count.':';
                   14516:         }
                   14517:     }
                   14518:     return;
                   14519: }
                   14520: 
                   14521: sub archive_row {
                   14522:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14523:     my ($name) = ($item =~ m{([^/]+)$});
                   14524:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14525:                                        'display'    => 'Add as file',
1.1055    raeburn  14526:                                        'dependency' => 'Include as dependency',
                   14527:                                        'discard'    => 'Discard',
                   14528:                                       );
                   14529:     if ($is_dir) {
1.1059    raeburn  14530:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14531:     }
1.1056    raeburn  14532:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14533:     my $offset = 0;
1.1055    raeburn  14534:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14535:         $offset ++;
1.1065    raeburn  14536:         if ($action ne 'display') {
                   14537:             $offset ++;
                   14538:         }  
1.1055    raeburn  14539:         $output .= '<td><span class="LC_nobreak">'.
                   14540:                    '<label><input type="radio" name="archive_'.$count.
                   14541:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14542:         my $text = $choices{$action};
                   14543:         if ($is_dir) {
                   14544:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14545:             if ($action eq 'display') {
1.1059    raeburn  14546:                 $text = &mt('Add as folder');
1.1055    raeburn  14547:             }
1.1056    raeburn  14548:         } else {
                   14549:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14550: 
                   14551:         }
                   14552:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14553:         if ($action eq 'dependency') {
                   14554:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14555:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14556:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14557:                        '<option value=""></option>'."\n".
                   14558:                        '</select>'."\n".
                   14559:                        '</div>';
1.1059    raeburn  14560:         } elsif ($action eq 'display') {
                   14561:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14562:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14563:                        '</div>';
1.1055    raeburn  14564:         }
1.1056    raeburn  14565:         $output .= '</td>';
1.1055    raeburn  14566:     }
                   14567:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14568:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14569:     for (my $i=0; $i<$depth; $i++) {
                   14570:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14571:     }
                   14572:     if ($is_dir) {
                   14573:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14574:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14575:     } else {
                   14576:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14577:     }
                   14578:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14579:                &end_data_table_row();
                   14580:     return $output;
                   14581: }
                   14582: 
                   14583: sub archive_options_form {
1.1065    raeburn  14584:     my ($form,$display,$count,$hiddenelem) = @_;
                   14585:     my %lt = &Apache::lonlocal::texthash(
                   14586:                perm => 'Permanently remove archive file?',
                   14587:                hows => 'How should each extracted item be incorporated in the course?',
                   14588:                cont => 'Content actions for all',
                   14589:                addf => 'Add as folder/file',
                   14590:                incd => 'Include as dependency for a displayed file',
                   14591:                disc => 'Discard',
                   14592:                no   => 'No',
                   14593:                yes  => 'Yes',
                   14594:                save => 'Save',
                   14595:     );
                   14596:     my $output = <<"END";
                   14597: <form name="$form" method="post" action="">
                   14598: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14599: <label>
                   14600:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14601: </label>
                   14602: &nbsp;
                   14603: <label>
                   14604:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14605: </span>
                   14606: </p>
                   14607: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14608: <br />$lt{'hows'}
                   14609: <div class="LC_columnSection">
                   14610:   <fieldset>
                   14611:     <legend>$lt{'cont'}</legend>
                   14612:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14613:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14614:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14615:   </fieldset>
                   14616: </div>
                   14617: END
                   14618:     return $output.
1.1055    raeburn  14619:            &start_data_table()."\n".
1.1065    raeburn  14620:            $display."\n".
1.1055    raeburn  14621:            &end_data_table()."\n".
                   14622:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14623:            $hiddenelem.
1.1065    raeburn  14624:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14625:            '</form>';
                   14626: }
                   14627: 
                   14628: sub archive_javascript {
1.1056    raeburn  14629:     my ($startcount,$numitems,$titles,$children) = @_;
                   14630:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14631:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14632:     my $scripttag = <<START;
                   14633: <script type="text/javascript">
                   14634: // <![CDATA[
                   14635: 
                   14636: function checkAll(form,prefix) {
                   14637:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14638:     for (var i=0; i < form.elements.length; i++) {
                   14639:         var id = form.elements[i].id;
                   14640:         if ((id != '') && (id != undefined)) {
                   14641:             if (idstr.test(id)) {
                   14642:                 if (form.elements[i].type == 'radio') {
                   14643:                     form.elements[i].checked = true;
1.1056    raeburn  14644:                     var nostart = i-$startcount;
1.1059    raeburn  14645:                     var offset = nostart%7;
                   14646:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14647:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14648:                 }
                   14649:             }
                   14650:         }
                   14651:     }
                   14652: }
                   14653: 
                   14654: function propagateCheck(form,count) {
                   14655:     if (count > 0) {
1.1059    raeburn  14656:         var startelement = $startcount + ((count-1) * 7);
                   14657:         for (var j=1; j<6; j++) {
                   14658:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14659:                 var item = startelement + j; 
                   14660:                 if (form.elements[item].type == 'radio') {
                   14661:                     if (form.elements[item].checked) {
                   14662:                         containerCheck(form,count,j);
                   14663:                         break;
                   14664:                     }
1.1055    raeburn  14665:                 }
                   14666:             }
                   14667:         }
                   14668:     }
                   14669: }
                   14670: 
                   14671: numitems = $numitems
1.1056    raeburn  14672: var titles = new Array(numitems);
                   14673: var parents = new Array(numitems);
1.1055    raeburn  14674: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14675:     parents[i] = new Array;
1.1055    raeburn  14676: }
1.1059    raeburn  14677: var maintitle = '$maintitle';
1.1055    raeburn  14678: 
                   14679: START
                   14680: 
1.1056    raeburn  14681:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14682:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14683:         for (my $i=0; $i<@contents; $i ++) {
                   14684:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14685:         }
                   14686:     }
                   14687: 
1.1056    raeburn  14688:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14689:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14690:     }
                   14691: 
1.1055    raeburn  14692:     $scripttag .= <<END;
                   14693: 
                   14694: function containerCheck(form,count,offset) {
                   14695:     if (count > 0) {
1.1056    raeburn  14696:         dependencyCheck(form,count,offset);
1.1059    raeburn  14697:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14698:         form.elements[item].checked = true;
                   14699:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14700:             if (parents[count].length > 0) {
                   14701:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14702:                     containerCheck(form,parents[count][j],offset);
                   14703:                 }
                   14704:             }
                   14705:         }
                   14706:     }
                   14707: }
                   14708: 
                   14709: function dependencyCheck(form,count,offset) {
                   14710:     if (count > 0) {
1.1059    raeburn  14711:         var chosen = (offset+$startcount)+7*(count-1);
                   14712:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14713:         var currtype = form.elements[depitem].type;
                   14714:         if (form.elements[chosen].value == 'dependency') {
                   14715:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14716:             form.elements[depitem].options.length = 0;
                   14717:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14718:             for (var i=1; i<=numitems; i++) {
                   14719:                 if (i == count) {
                   14720:                     continue;
                   14721:                 }
1.1059    raeburn  14722:                 var startelement = $startcount + (i-1) * 7;
                   14723:                 for (var j=1; j<6; j++) {
                   14724:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14725:                         var item = startelement + j;
                   14726:                         if (form.elements[item].type == 'radio') {
                   14727:                             if (form.elements[item].checked) {
                   14728:                                 if (form.elements[item].value == 'display') {
                   14729:                                     var n = form.elements[depitem].options.length;
                   14730:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14731:                                 }
                   14732:                             }
                   14733:                         }
                   14734:                     }
                   14735:                 }
                   14736:             }
                   14737:         } else {
                   14738:             document.getElementById('arc_depon_'+count).style.display='none';
                   14739:             form.elements[depitem].options.length = 0;
                   14740:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14741:         }
1.1059    raeburn  14742:         titleCheck(form,count,offset);
1.1056    raeburn  14743:     }
                   14744: }
                   14745: 
                   14746: function propagateSelect(form,count,offset) {
                   14747:     if (count > 0) {
1.1065    raeburn  14748:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14749:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14750:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14751:             if (parents[count].length > 0) {
                   14752:                 for (var j=0; j<parents[count].length; j++) {
                   14753:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14754:                 }
                   14755:             }
                   14756:         }
                   14757:     }
                   14758: }
1.1056    raeburn  14759: 
                   14760: function containerSelect(form,count,offset,picked) {
                   14761:     if (count > 0) {
1.1065    raeburn  14762:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14763:         if (form.elements[item].type == 'radio') {
                   14764:             if (form.elements[item].value == 'dependency') {
                   14765:                 if (form.elements[item+1].type == 'select-one') {
                   14766:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14767:                         if (form.elements[item+1].options[i].value == picked) {
                   14768:                             form.elements[item+1].selectedIndex = i;
                   14769:                             break;
                   14770:                         }
                   14771:                     }
                   14772:                 }
                   14773:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14774:                     if (parents[count].length > 0) {
                   14775:                         for (var j=0; j<parents[count].length; j++) {
                   14776:                             containerSelect(form,parents[count][j],offset,picked);
                   14777:                         }
                   14778:                     }
                   14779:                 }
                   14780:             }
                   14781:         }
                   14782:     }
                   14783: }
                   14784: 
1.1059    raeburn  14785: function titleCheck(form,count,offset) {
                   14786:     if (count > 0) {
                   14787:         var chosen = (offset+$startcount)+7*(count-1);
                   14788:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14789:         var currtype = form.elements[depitem].type;
                   14790:         if (form.elements[chosen].value == 'display') {
                   14791:             document.getElementById('arc_title_'+count).style.display='block';
                   14792:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14793:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14794:             }
                   14795:         } else {
                   14796:             document.getElementById('arc_title_'+count).style.display='none';
                   14797:             if (currtype == 'text') { 
                   14798:                 document.getElementById('archive_title_'+count).value='';
                   14799:             }
                   14800:         }
                   14801:     }
                   14802:     return;
                   14803: }
                   14804: 
1.1055    raeburn  14805: // ]]>
                   14806: </script>
                   14807: END
                   14808:     return $scripttag;
                   14809: }
                   14810: 
                   14811: sub process_extracted_files {
1.1067    raeburn  14812:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14813:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14814:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14815:     my @ids=&Apache::lonnet::current_machine_ids();
                   14816:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14817:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14818:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14819:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14820:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14821:         $pathtocheck = "$dir_root/$destination";
                   14822:         $dir = $dir_root;
                   14823:         $ishome = 1;
                   14824:     } else {
                   14825:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14826:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14827:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14828:     }
                   14829:     my $currdir = "$dir_root/$destination";
                   14830:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14831:     if ($env{'form.folderpath'}) {
                   14832:         my @items = split('&',$env{'form.folderpath'});
                   14833:         $folders{'0'} = $items[-2];
1.1099    raeburn  14834:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14835:             $containers{'0'}='page';
                   14836:         } else {  
                   14837:             $containers{'0'}='sequence';
                   14838:         }
1.1055    raeburn  14839:     }
                   14840:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14841:     if ($numitems) {
                   14842:         for (my $i=1; $i<=$numitems; $i++) {
                   14843:             my $path = $env{'form.archive_content_'.$i};
                   14844:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14845:                 my $item = $1;
                   14846:                 $toplevelitems{$item} = $i;
                   14847:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14848:                     $is_dir{$item} = 1;
                   14849:                 }
                   14850:             }
                   14851:         }
                   14852:     }
1.1067    raeburn  14853:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14854:     if (keys(%toplevelitems) > 0) {
                   14855:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14856:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14857:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14858:     }
1.1066    raeburn  14859:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14860:     if ($numitems) {
                   14861:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14862:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14863:             my $path = $env{'form.archive_content_'.$i};
                   14864:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14865:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14866:                     if ($prefix ne '' && $path ne '') {
                   14867:                         if (-e $prefix.$path) {
1.1066    raeburn  14868:                             if ((@archdirs > 0) && 
                   14869:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14870:                                 $todeletedir{$prefix.$path} = 1;
                   14871:                             } else {
                   14872:                                 $todelete{$prefix.$path} = 1;
                   14873:                             }
1.1055    raeburn  14874:                         }
                   14875:                     }
                   14876:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14877:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14878:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14879:                     $docstitle = $env{'form.archive_title_'.$i};
                   14880:                     if ($docstitle eq '') {
                   14881:                         $docstitle = $title;
                   14882:                     }
1.1055    raeburn  14883:                     $outer = 0;
1.1056    raeburn  14884:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14885:                         if (@{$dirorder{$i}} > 0) {
                   14886:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14887:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14888:                                     $outer = $item;
                   14889:                                     last;
                   14890:                                 }
                   14891:                             }
                   14892:                         }
                   14893:                     }
                   14894:                     my ($errtext,$fatal) = 
                   14895:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14896:                                                '/'.$folders{$outer}.'.'.
                   14897:                                                $containers{$outer});
                   14898:                     next if ($fatal);
                   14899:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14900:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14901:                             $mapinner{$i} = time;
1.1055    raeburn  14902:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14903:                             $containers{$i} = 'sequence';
                   14904:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14905:                                       $folders{$i}.'.'.$containers{$i};
                   14906:                             my $newidx = &LONCAPA::map::getresidx();
                   14907:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14908:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14909:                             push(@LONCAPA::map::order,$newidx);
                   14910:                             my ($outtext,$errtext) =
                   14911:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14912:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14913:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14914:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14915:                             unless ($errtext) {
1.1294    raeburn  14916:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14917:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14918:                                             '</li>'."\n";
1.1067    raeburn  14919:                             }
1.1055    raeburn  14920:                         }
                   14921:                     } else {
                   14922:                         if ($context eq 'coursedocs') {
                   14923:                             my $newidx=&LONCAPA::map::getresidx();
                   14924:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14925:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14926:                                       $title;
1.1392    raeburn  14927:                             if (($outer !~ /\D/) &&
                   14928:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14929:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14930:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14931:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14932:                                 }
                   14933:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14934:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14935:                                 }
                   14936:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14937:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14938:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14939:                                         unless ($ishome) {
                   14940:                                             my $fetch = "$newdest{$i}/$title";
                   14941:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14942:                                             $prompttofetch{$fetch} = 1;
                   14943:                                         }
1.1292    raeburn  14944:                                     }
1.1067    raeburn  14945:                                 }
1.1294    raeburn  14946:                                 $LONCAPA::map::resources[$newidx]=
                   14947:                                     $docstitle.':'.$url.':false:normal:res';
                   14948:                                 push(@LONCAPA::map::order, $newidx);
                   14949:                                 my ($outtext,$errtext)=
                   14950:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14951:                                                             $docuname.'/'.$folders{$outer}.
                   14952:                                                             '.'.$containers{$outer},1,1);
                   14953:                                 unless ($errtext) {
                   14954:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14955:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14956:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14957:                                                    '</li>'."\n";
                   14958:                                     }
1.1067    raeburn  14959:                                 }
1.1294    raeburn  14960:                             } else {
                   14961:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14962:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14963:                             }
1.1055    raeburn  14964:                         }
                   14965:                     }
1.1086    raeburn  14966:                 }
                   14967:             } else {
1.1294    raeburn  14968:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14969:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14970:             }
                   14971:         }
                   14972:         for (my $i=1; $i<=$numitems; $i++) {
                   14973:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14974:             my $path = $env{'form.archive_content_'.$i};
                   14975:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14976:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14977:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14978:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14979:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14980:                         my ($itemidx,$fullpath,$relpath);
                   14981:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14982:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14983:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14984:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14985:                                     $itemidx = $j;
1.1056    raeburn  14986:                                 }
                   14987:                             }
1.1086    raeburn  14988:                         }
                   14989:                         if ($itemidx eq '') {
                   14990:                             $itemidx =  0;
                   14991:                         } 
                   14992:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14993:                             if ($mapinner{$referrer{$i}}) {
                   14994:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14995:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14996:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14997:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14998:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14999:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15000:                                             if (!-e $fullpath) {
                   15001:                                                 mkdir($fullpath,0755);
1.1056    raeburn  15002:                                             }
                   15003:                                         }
1.1086    raeburn  15004:                                     } else {
                   15005:                                         last;
1.1056    raeburn  15006:                                     }
1.1086    raeburn  15007:                                 }
                   15008:                             }
                   15009:                         } elsif ($newdest{$referrer{$i}}) {
                   15010:                             $fullpath = $newdest{$referrer{$i}};
                   15011:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   15012:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   15013:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   15014:                                     last;
                   15015:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   15016:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   15017:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15018:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   15019:                                         if (!-e $fullpath) {
                   15020:                                             mkdir($fullpath,0755);
1.1056    raeburn  15021:                                         }
                   15022:                                     }
1.1086    raeburn  15023:                                 } else {
                   15024:                                     last;
1.1056    raeburn  15025:                                 }
1.1055    raeburn  15026:                             }
                   15027:                         }
1.1086    raeburn  15028:                         if ($fullpath ne '') {
                   15029:                             if (-e "$prefix$path") {
1.1292    raeburn  15030:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   15031:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   15032:                                 }
1.1086    raeburn  15033:                             }
                   15034:                             if (-e "$fullpath/$title") {
                   15035:                                 my $showpath;
                   15036:                                 if ($relpath ne '') {
                   15037:                                     $showpath = "$relpath/$title";
                   15038:                                 } else {
                   15039:                                     $showpath = "/$title";
                   15040:                                 } 
1.1294    raeburn  15041:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15042:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15043:                                            '</li>'."\n";
1.1292    raeburn  15044:                                 unless ($ishome) {
                   15045:                                     my $fetch = "$fullpath/$title";
                   15046:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15047:                                     $prompttofetch{$fetch} = 1;
                   15048:                                 }
1.1086    raeburn  15049:                             }
                   15050:                         }
1.1055    raeburn  15051:                     }
1.1086    raeburn  15052:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15053:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15054:                                     &HTML::Entities::encode($path,'<>&"'),
                   15055:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15056:                                 '<br />';
1.1055    raeburn  15057:                 }
                   15058:             } else {
1.1294    raeburn  15059:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15060:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15061:             }
                   15062:         }
                   15063:         if (keys(%todelete)) {
                   15064:             foreach my $key (keys(%todelete)) {
                   15065:                 unlink($key);
1.1066    raeburn  15066:             }
                   15067:         }
                   15068:         if (keys(%todeletedir)) {
                   15069:             foreach my $key (keys(%todeletedir)) {
                   15070:                 rmdir($key);
                   15071:             }
                   15072:         }
                   15073:         foreach my $dir (sort(keys(%is_dir))) {
                   15074:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15075:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15076:             }
                   15077:         }
1.1067    raeburn  15078:         if ($result ne '') {
                   15079:             $output .= '<ul>'."\n".
                   15080:                        $result."\n".
                   15081:                        '</ul>';
                   15082:         }
                   15083:         unless ($ishome) {
                   15084:             my $replicationfail;
                   15085:             foreach my $item (keys(%prompttofetch)) {
                   15086:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15087:                 unless ($fetchresult eq 'ok') {
                   15088:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15089:                 }
                   15090:             }
                   15091:             if ($replicationfail) {
                   15092:                 $output .= '<p class="LC_error">'.
                   15093:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15094:                            $replicationfail.
                   15095:                            '</ul></p>';
                   15096:             }
                   15097:         }
1.1055    raeburn  15098:     } else {
                   15099:         $warning = &mt('No items found in archive.');
                   15100:     }
                   15101:     if ($error) {
                   15102:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15103:                    $error.'</p>'."\n";
                   15104:     }
                   15105:     if ($warning) {
                   15106:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15107:     }
                   15108:     return $output;
                   15109: }
                   15110: 
1.1066    raeburn  15111: sub cleanup_empty_dirs {
                   15112:     my ($path) = @_;
                   15113:     if (($path ne '') && (-d $path)) {
                   15114:         if (opendir(my $dirh,$path)) {
                   15115:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15116:             my $numitems = 0;
                   15117:             foreach my $item (@dircontents) {
                   15118:                 if (-d "$path/$item") {
1.1111    raeburn  15119:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15120:                     if (-e "$path/$item") {
                   15121:                         $numitems ++;
                   15122:                     }
                   15123:                 } else {
                   15124:                     $numitems ++;
                   15125:                 }
                   15126:             }
                   15127:             if ($numitems == 0) {
                   15128:                 rmdir($path);
                   15129:             }
                   15130:             closedir($dirh);
                   15131:         }
                   15132:     }
                   15133:     return;
                   15134: }
                   15135: 
1.41      ng       15136: =pod
1.45      matthew  15137: 
1.1162    raeburn  15138: =item * &get_folder_hierarchy()
1.1068    raeburn  15139: 
                   15140: Provides hierarchy of names of folders/sub-folders containing the current
                   15141: item,
                   15142: 
                   15143: Inputs: 3
                   15144:      - $navmap - navmaps object
                   15145: 
                   15146:      - $map - url for map (either the trigger itself, or map containing
                   15147:                            the resource, which is the trigger).
                   15148: 
                   15149:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15150: 
                   15151: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15152: 
                   15153: =cut
                   15154: 
                   15155: sub get_folder_hierarchy {
                   15156:     my ($navmap,$map,$showitem) = @_;
                   15157:     my @pathitems;
                   15158:     if (ref($navmap)) {
                   15159:         my $mapres = $navmap->getResourceByUrl($map);
                   15160:         if (ref($mapres)) {
                   15161:             my $pcslist = $mapres->map_hierarchy();
                   15162:             if ($pcslist ne '') {
                   15163:                 my @pcs = split(/,/,$pcslist);
                   15164:                 foreach my $pc (@pcs) {
                   15165:                     if ($pc == 1) {
1.1129    raeburn  15166:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15167:                     } else {
                   15168:                         my $res = $navmap->getByMapPc($pc);
                   15169:                         if (ref($res)) {
                   15170:                             my $title = $res->compTitle();
                   15171:                             $title =~ s/\W+/_/g;
                   15172:                             if ($title ne '') {
                   15173:                                 push(@pathitems,$title);
                   15174:                             }
                   15175:                         }
                   15176:                     }
                   15177:                 }
                   15178:             }
1.1071    raeburn  15179:             if ($showitem) {
                   15180:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15181:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15182:                 } else {
                   15183:                     my $maptitle = $mapres->compTitle();
                   15184:                     $maptitle =~ s/\W+/_/g;
                   15185:                     if ($maptitle ne '') {
                   15186:                         push(@pathitems,$maptitle);
                   15187:                     }
1.1068    raeburn  15188:                 }
                   15189:             }
                   15190:         }
                   15191:     }
                   15192:     return @pathitems;
                   15193: }
                   15194: 
                   15195: =pod
                   15196: 
1.1015    raeburn  15197: =item * &get_turnedin_filepath()
                   15198: 
                   15199: Determines path in a user's portfolio file for storage of files uploaded
                   15200: to a specific essayresponse or dropbox item.
                   15201: 
                   15202: Inputs: 3 required + 1 optional.
                   15203: $symb is symb for resource, $uname and $udom are for current user (required).
                   15204: $caller is optional (can be "submission", if routine is called when storing
                   15205: an upoaded file when "Submit Answer" button was pressed).
                   15206: 
                   15207: Returns array containing $path and $multiresp. 
                   15208: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15209: than one file upload item.  Callers of routine should append partid as a 
                   15210: subdirectory to $path in cases where $multiresp is 1.
                   15211: 
                   15212: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15213: 
                   15214: =cut
                   15215: 
                   15216: sub get_turnedin_filepath {
                   15217:     my ($symb,$uname,$udom,$caller) = @_;
                   15218:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15219:     my $turnindir;
                   15220:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15221:     $turnindir = $userhash{'turnindir'};
                   15222:     my ($path,$multiresp);
                   15223:     if ($turnindir eq '') {
                   15224:         if ($caller eq 'submission') {
                   15225:             $turnindir = &mt('turned in');
                   15226:             $turnindir =~ s/\W+/_/g;
                   15227:             my %newhash = (
                   15228:                             'turnindir' => $turnindir,
                   15229:                           );
                   15230:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15231:         }
                   15232:     }
                   15233:     if ($turnindir ne '') {
                   15234:         $path = '/'.$turnindir.'/';
                   15235:         my ($multipart,$turnin,@pathitems);
                   15236:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15237:         if (defined($navmap)) {
                   15238:             my $mapres = $navmap->getResourceByUrl($map);
                   15239:             if (ref($mapres)) {
                   15240:                 my $pcslist = $mapres->map_hierarchy();
                   15241:                 if ($pcslist ne '') {
                   15242:                     foreach my $pc (split(/,/,$pcslist)) {
                   15243:                         my $res = $navmap->getByMapPc($pc);
                   15244:                         if (ref($res)) {
                   15245:                             my $title = $res->compTitle();
                   15246:                             $title =~ s/\W+/_/g;
                   15247:                             if ($title ne '') {
1.1149    raeburn  15248:                                 if (($pc > 1) && (length($title) > 12)) {
                   15249:                                     $title = substr($title,0,12);
                   15250:                                 }
1.1015    raeburn  15251:                                 push(@pathitems,$title);
                   15252:                             }
                   15253:                         }
                   15254:                     }
                   15255:                 }
                   15256:                 my $maptitle = $mapres->compTitle();
                   15257:                 $maptitle =~ s/\W+/_/g;
                   15258:                 if ($maptitle ne '') {
1.1149    raeburn  15259:                     if (length($maptitle) > 12) {
                   15260:                         $maptitle = substr($maptitle,0,12);
                   15261:                     }
1.1015    raeburn  15262:                     push(@pathitems,$maptitle);
                   15263:                 }
                   15264:                 unless ($env{'request.state'} eq 'construct') {
                   15265:                     my $res = $navmap->getBySymb($symb);
                   15266:                     if (ref($res)) {
                   15267:                         my $partlist = $res->parts();
                   15268:                         my $totaluploads = 0;
                   15269:                         if (ref($partlist) eq 'ARRAY') {
                   15270:                             foreach my $part (@{$partlist}) {
                   15271:                                 my @types = $res->responseType($part);
                   15272:                                 my @ids = $res->responseIds($part);
                   15273:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15274:                                     if ($types[$i] eq 'essay') {
                   15275:                                         my $partid = $part.'_'.$ids[$i];
                   15276:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15277:                                             $totaluploads ++;
                   15278:                                         }
                   15279:                                     }
                   15280:                                 }
                   15281:                             }
                   15282:                             if ($totaluploads > 1) {
                   15283:                                 $multiresp = 1;
                   15284:                             }
                   15285:                         }
                   15286:                     }
                   15287:                 }
                   15288:             } else {
                   15289:                 return;
                   15290:             }
                   15291:         } else {
                   15292:             return;
                   15293:         }
                   15294:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15295:         $restitle =~ s/\W+/_/g;
                   15296:         if ($restitle eq '') {
                   15297:             $restitle = ($resurl =~ m{/[^/]+$});
                   15298:             if ($restitle eq '') {
                   15299:                 $restitle = time;
                   15300:             }
                   15301:         }
1.1149    raeburn  15302:         if (length($restitle) > 12) {
                   15303:             $restitle = substr($restitle,0,12);
                   15304:         }
1.1015    raeburn  15305:         push(@pathitems,$restitle);
                   15306:         $path .= join('/',@pathitems);
                   15307:     }
                   15308:     return ($path,$multiresp);
                   15309: }
                   15310: 
                   15311: =pod
                   15312: 
1.464     albertel 15313: =back
1.41      ng       15314: 
1.112     bowersj2 15315: =head1 CSV Upload/Handling functions
1.38      albertel 15316: 
1.41      ng       15317: =over 4
                   15318: 
1.648     raeburn  15319: =item * &upfile_store($r)
1.41      ng       15320: 
                   15321: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15322: needs $env{'form.upfile'}
1.41      ng       15323: returns $datatoken to be put into hidden field
                   15324: 
                   15325: =cut
1.31      albertel 15326: 
                   15327: sub upfile_store {
                   15328:     my $r=shift;
1.258     albertel 15329:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15330:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15331:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15332:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15333: 
1.1299    raeburn  15334:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15335:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15336:                                      time.'_'.$$);
                   15337:     return if ($datatoken eq '');
                   15338: 
1.31      albertel 15339:     {
1.158     raeburn  15340:         my $datafile = $r->dir_config('lonDaemons').
                   15341:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15342:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15343:             print $fh $env{'form.upfile'};
1.158     raeburn  15344:             close($fh);
                   15345:         }
1.31      albertel 15346:     }
                   15347:     return $datatoken;
                   15348: }
                   15349: 
1.56      matthew  15350: =pod
                   15351: 
1.1290    raeburn  15352: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15353: 
                   15354: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15355: $datatoken is the name to assign to the temporary file.
1.258     albertel 15356: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15357: 
                   15358: =cut
1.31      albertel 15359: 
                   15360: sub load_tmp_file {
1.1290    raeburn  15361:     my ($r,$datatoken) = @_;
                   15362:     return if ($datatoken eq '');
1.31      albertel 15363:     my @studentdata=();
                   15364:     {
1.158     raeburn  15365:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15366:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15367:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15368:             @studentdata=<$fh>;
                   15369:             close($fh);
                   15370:         }
1.31      albertel 15371:     }
1.258     albertel 15372:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15373: }
                   15374: 
1.1290    raeburn  15375: sub valid_datatoken {
                   15376:     my ($datatoken) = @_;
1.1325    raeburn  15377:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15378:         return $datatoken;
                   15379:     }
                   15380:     return;
                   15381: }
                   15382: 
1.56      matthew  15383: =pod
                   15384: 
1.648     raeburn  15385: =item * &upfile_record_sep()
1.41      ng       15386: 
                   15387: Separate uploaded file into records
                   15388: returns array of records,
1.258     albertel 15389: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15390: 
                   15391: =cut
1.31      albertel 15392: 
                   15393: sub upfile_record_sep {
1.258     albertel 15394:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15395:     } else {
1.248     albertel 15396: 	my @records;
1.258     albertel 15397: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15398: 	    if ($line=~/^\s*$/) { next; }
                   15399: 	    push(@records,$line);
                   15400: 	}
                   15401: 	return @records;
1.31      albertel 15402:     }
                   15403: }
                   15404: 
1.56      matthew  15405: =pod
                   15406: 
1.648     raeburn  15407: =item * &record_sep($record)
1.41      ng       15408: 
1.258     albertel 15409: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15410: 
                   15411: =cut
                   15412: 
1.263     www      15413: sub takeleft {
                   15414:     my $index=shift;
                   15415:     return substr('0000'.$index,-4,4);
                   15416: }
                   15417: 
1.31      albertel 15418: sub record_sep {
                   15419:     my $record=shift;
                   15420:     my %components=();
1.258     albertel 15421:     if ($env{'form.upfiletype'} eq 'xml') {
                   15422:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15423:         my $i=0;
1.356     albertel 15424:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15425:             $field=~s/^(\"|\')//;
                   15426:             $field=~s/(\"|\')$//;
1.263     www      15427:             $components{&takeleft($i)}=$field;
1.31      albertel 15428:             $i++;
                   15429:         }
1.258     albertel 15430:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15431:         my $i=0;
1.356     albertel 15432:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15433:             $field=~s/^(\"|\')//;
                   15434:             $field=~s/(\"|\')$//;
1.263     www      15435:             $components{&takeleft($i)}=$field;
1.31      albertel 15436:             $i++;
                   15437:         }
                   15438:     } else {
1.561     www      15439:         my $separator=',';
1.480     banghart 15440:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15441:             $separator=';';
1.480     banghart 15442:         }
1.31      albertel 15443:         my $i=0;
1.561     www      15444: # the character we are looking for to indicate the end of a quote or a record 
                   15445:         my $looking_for=$separator;
                   15446: # do not add the characters to the fields
                   15447:         my $ignore=0;
                   15448: # we just encountered a separator (or the beginning of the record)
                   15449:         my $just_found_separator=1;
                   15450: # store the field we are working on here
                   15451:         my $field='';
                   15452: # work our way through all characters in record
                   15453:         foreach my $character ($record=~/(.)/g) {
                   15454:             if ($character eq $looking_for) {
                   15455:                if ($character ne $separator) {
                   15456: # Found the end of a quote, again looking for separator
                   15457:                   $looking_for=$separator;
                   15458:                   $ignore=1;
                   15459:                } else {
                   15460: # Found a separator, store away what we got
                   15461:                   $components{&takeleft($i)}=$field;
                   15462: 	          $i++;
                   15463:                   $just_found_separator=1;
                   15464:                   $ignore=0;
                   15465:                   $field='';
                   15466:                }
                   15467:                next;
                   15468:             }
                   15469: # single or double quotation marks after a separator indicate beginning of a quote
                   15470: # we are now looking for the end of the quote and need to ignore separators
                   15471:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15472:                $looking_for=$character;
                   15473:                next;
                   15474:             }
                   15475: # ignore would be true after we reached the end of a quote
                   15476:             if ($ignore) { next; }
                   15477:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15478:             $field.=$character;
                   15479:             $just_found_separator=0; 
1.31      albertel 15480:         }
1.561     www      15481: # catch the very last entry, since we never encountered the separator
                   15482:         $components{&takeleft($i)}=$field;
1.31      albertel 15483:     }
                   15484:     return %components;
                   15485: }
                   15486: 
1.144     matthew  15487: ######################################################
                   15488: ######################################################
                   15489: 
1.56      matthew  15490: =pod
                   15491: 
1.648     raeburn  15492: =item * &upfile_select_html()
1.41      ng       15493: 
1.144     matthew  15494: Return HTML code to select a file from the users machine and specify 
                   15495: the file type.
1.41      ng       15496: 
                   15497: =cut
                   15498: 
1.144     matthew  15499: ######################################################
                   15500: ######################################################
1.31      albertel 15501: sub upfile_select_html {
1.144     matthew  15502:     my %Types = (
                   15503:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15504:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15505:                  space => &mt('Space separated'),
                   15506:                  tab   => &mt('Tabulator separated'),
                   15507: #                 xml   => &mt('HTML/XML'),
                   15508:                  );
                   15509:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15510:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15511:     foreach my $type (sort(keys(%Types))) {
                   15512:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15513:     }
                   15514:     $Str .= "</select>\n";
                   15515:     return $Str;
1.31      albertel 15516: }
                   15517: 
1.301     albertel 15518: sub get_samples {
                   15519:     my ($records,$toget) = @_;
                   15520:     my @samples=({});
                   15521:     my $got=0;
                   15522:     foreach my $rec (@$records) {
                   15523: 	my %temp = &record_sep($rec);
                   15524: 	if (! grep(/\S/, values(%temp))) { next; }
                   15525: 	if (%temp) {
                   15526: 	    $samples[$got]=\%temp;
                   15527: 	    $got++;
                   15528: 	    if ($got == $toget) { last; }
                   15529: 	}
                   15530:     }
                   15531:     return \@samples;
                   15532: }
                   15533: 
1.144     matthew  15534: ######################################################
                   15535: ######################################################
                   15536: 
1.56      matthew  15537: =pod
                   15538: 
1.648     raeburn  15539: =item * &csv_print_samples($r,$records)
1.41      ng       15540: 
                   15541: Prints a table of sample values from each column uploaded $r is an
                   15542: Apache Request ref, $records is an arrayref from
                   15543: &Apache::loncommon::upfile_record_sep
                   15544: 
                   15545: =cut
                   15546: 
1.144     matthew  15547: ######################################################
                   15548: ######################################################
1.31      albertel 15549: sub csv_print_samples {
                   15550:     my ($r,$records) = @_;
1.662     bisitz   15551:     my $samples = &get_samples($records,5);
1.301     albertel 15552: 
1.594     raeburn  15553:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15554:               &start_data_table_header_row());
1.356     albertel 15555:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15556:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15557:     $r->print(&end_data_table_header_row());
1.301     albertel 15558:     foreach my $hash (@$samples) {
1.594     raeburn  15559: 	$r->print(&start_data_table_row());
1.356     albertel 15560: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15561: 	    $r->print('<td>');
1.356     albertel 15562: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15563: 	    $r->print('</td>');
                   15564: 	}
1.594     raeburn  15565: 	$r->print(&end_data_table_row());
1.31      albertel 15566:     }
1.594     raeburn  15567:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15568: }
                   15569: 
1.144     matthew  15570: ######################################################
                   15571: ######################################################
                   15572: 
1.56      matthew  15573: =pod
                   15574: 
1.648     raeburn  15575: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15576: 
                   15577: Prints a table to create associations between values and table columns.
1.144     matthew  15578: 
1.41      ng       15579: $r is an Apache Request ref,
                   15580: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15581: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15582: 
                   15583: =cut
                   15584: 
1.144     matthew  15585: ######################################################
                   15586: ######################################################
1.31      albertel 15587: sub csv_print_select_table {
                   15588:     my ($r,$records,$d) = @_;
1.301     albertel 15589:     my $i=0;
                   15590:     my $samples = &get_samples($records,1);
1.144     matthew  15591:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15592: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15593:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15594:               '<th>'.&mt('Column').'</th>'.
                   15595:               &end_data_table_header_row()."\n");
1.356     albertel 15596:     foreach my $array_ref (@$d) {
                   15597: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15598: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15599: 
1.875     bisitz   15600: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15601: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15602: 	$r->print('<option value="none"></option>');
1.356     albertel 15603: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15604: 	    $r->print('<option value="'.$sample.'"'.
                   15605:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15606:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15607: 	}
1.594     raeburn  15608: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15609: 	$i++;
                   15610:     }
1.594     raeburn  15611:     $r->print(&end_data_table());
1.31      albertel 15612:     $i--;
                   15613:     return $i;
                   15614: }
1.56      matthew  15615: 
1.144     matthew  15616: ######################################################
                   15617: ######################################################
                   15618: 
1.56      matthew  15619: =pod
1.31      albertel 15620: 
1.648     raeburn  15621: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15622: 
                   15623: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15624: 
                   15625: $r is an Apache Request ref,
                   15626: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15627: $d is an array of 2 element arrays (internal name, displayed name)
                   15628: 
                   15629: =cut
                   15630: 
1.144     matthew  15631: ######################################################
                   15632: ######################################################
1.31      albertel 15633: sub csv_samples_select_table {
                   15634:     my ($r,$records,$d) = @_;
                   15635:     my $i=0;
1.144     matthew  15636:     #
1.662     bisitz   15637:     my $max_samples = 5;
                   15638:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15639:     $r->print(&start_data_table().
                   15640:               &start_data_table_header_row().'<th>'.
                   15641:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15642:               &end_data_table_header_row());
1.301     albertel 15643: 
                   15644:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15645: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15646: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15647: 	foreach my $option (@$d) {
                   15648: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15649: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15650:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15651:                       $display.'</option>');
1.31      albertel 15652: 	}
                   15653: 	$r->print('</select></td><td>');
1.662     bisitz   15654: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15655: 	    if (defined($samples->[$line]{$key})) { 
                   15656: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15657: 	    }
                   15658: 	}
1.594     raeburn  15659: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15660: 	$i++;
                   15661:     }
1.594     raeburn  15662:     $r->print(&end_data_table());
1.31      albertel 15663:     $i--;
                   15664:     return($i);
1.115     matthew  15665: }
                   15666: 
1.144     matthew  15667: ######################################################
                   15668: ######################################################
                   15669: 
1.115     matthew  15670: =pod
                   15671: 
1.648     raeburn  15672: =item * &clean_excel_name($name)
1.115     matthew  15673: 
                   15674: Returns a replacement for $name which does not contain any illegal characters.
                   15675: 
                   15676: =cut
                   15677: 
1.144     matthew  15678: ######################################################
                   15679: ######################################################
1.115     matthew  15680: sub clean_excel_name {
                   15681:     my ($name) = @_;
                   15682:     $name =~ s/[:\*\?\/\\]//g;
                   15683:     if (length($name) > 31) {
                   15684:         $name = substr($name,0,31);
                   15685:     }
                   15686:     return $name;
1.25      albertel 15687: }
1.84      albertel 15688: 
1.85      albertel 15689: =pod
                   15690: 
1.648     raeburn  15691: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15692: 
                   15693: Returns either 1 or undef
                   15694: 
                   15695: 1 if the part is to be hidden, undef if it is to be shown
                   15696: 
                   15697: Arguments are:
                   15698: 
                   15699: $id the id of the part to be checked
                   15700: $symb, optional the symb of the resource to check
                   15701: $udom, optional the domain of the user to check for
                   15702: $uname, optional the username of the user to check for
                   15703: 
                   15704: =cut
1.84      albertel 15705: 
                   15706: sub check_if_partid_hidden {
                   15707:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15708:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15709: 					 $symb,$udom,$uname);
1.141     albertel 15710:     my $truth=1;
                   15711:     #if the string starts with !, then the list is the list to show not hide
                   15712:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15713:     my @hiddenlist=split(/,/,$hiddenparts);
                   15714:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15715: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15716:     }
1.141     albertel 15717:     return !$truth;
1.84      albertel 15718: }
1.127     matthew  15719: 
1.138     matthew  15720: 
                   15721: ############################################################
                   15722: ############################################################
                   15723: 
                   15724: =pod
                   15725: 
1.157     matthew  15726: =back 
                   15727: 
1.138     matthew  15728: =head1 cgi-bin script and graphing routines
                   15729: 
1.157     matthew  15730: =over 4
                   15731: 
1.648     raeburn  15732: =item * &get_cgi_id()
1.138     matthew  15733: 
                   15734: Inputs: none
                   15735: 
                   15736: Returns an id which can be used to pass environment variables
                   15737: to various cgi-bin scripts.  These environment variables will
                   15738: be removed from the users environment after a given time by
                   15739: the routine &Apache::lonnet::transfer_profile_to_env.
                   15740: 
                   15741: =cut
                   15742: 
                   15743: ############################################################
                   15744: ############################################################
1.152     albertel 15745: my $uniq=0;
1.136     matthew  15746: sub get_cgi_id {
1.154     albertel 15747:     $uniq=($uniq+1)%100000;
1.280     albertel 15748:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15749: }
                   15750: 
1.127     matthew  15751: ############################################################
                   15752: ############################################################
                   15753: 
                   15754: =pod
                   15755: 
1.648     raeburn  15756: =item * &DrawBarGraph()
1.127     matthew  15757: 
1.138     matthew  15758: Facilitates the plotting of data in a (stacked) bar graph.
                   15759: Puts plot definition data into the users environment in order for 
                   15760: graph.png to plot it.  Returns an <img> tag for the plot.
                   15761: The bars on the plot are labeled '1','2',...,'n'.
                   15762: 
                   15763: Inputs:
                   15764: 
                   15765: =over 4
                   15766: 
                   15767: =item $Title: string, the title of the plot
                   15768: 
                   15769: =item $xlabel: string, text describing the X-axis of the plot
                   15770: 
                   15771: =item $ylabel: string, text describing the Y-axis of the plot
                   15772: 
                   15773: =item $Max: scalar, the maximum Y value to use in the plot
                   15774: If $Max is < any data point, the graph will not be rendered.
                   15775: 
1.140     matthew  15776: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15777: they are plotted.  If undefined, default values will be used.
                   15778: 
1.178     matthew  15779: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15780: 
1.138     matthew  15781: =item @Values: An array of array references.  Each array reference holds data
                   15782: to be plotted in a stacked bar chart.
                   15783: 
1.239     matthew  15784: =item If the final element of @Values is a hash reference the key/value
                   15785: pairs will be added to the graph definition.
                   15786: 
1.138     matthew  15787: =back
                   15788: 
                   15789: Returns:
                   15790: 
                   15791: An <img> tag which references graph.png and the appropriate identifying
                   15792: information for the plot.
                   15793: 
1.127     matthew  15794: =cut
                   15795: 
                   15796: ############################################################
                   15797: ############################################################
1.134     matthew  15798: sub DrawBarGraph {
1.178     matthew  15799:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15800:     #
                   15801:     if (! defined($colors)) {
                   15802:         $colors = ['#33ff00', 
                   15803:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15804:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15805:                   ]; 
                   15806:     }
1.228     matthew  15807:     my $extra_settings = {};
                   15808:     if (ref($Values[-1]) eq 'HASH') {
                   15809:         $extra_settings = pop(@Values);
                   15810:     }
1.127     matthew  15811:     #
1.136     matthew  15812:     my $identifier = &get_cgi_id();
                   15813:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15814:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15815:         return '';
                   15816:     }
1.225     matthew  15817:     #
                   15818:     my @Labels;
                   15819:     if (defined($labels)) {
                   15820:         @Labels = @$labels;
                   15821:     } else {
                   15822:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15823:             push(@Labels,$i+1);
1.225     matthew  15824:         }
                   15825:     }
                   15826:     #
1.129     matthew  15827:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15828:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15829:     my %ValuesHash;
                   15830:     my $NumSets=1;
                   15831:     foreach my $array (@Values) {
                   15832:         next if (! ref($array));
1.136     matthew  15833:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15834:             join(',',@$array);
1.129     matthew  15835:     }
1.127     matthew  15836:     #
1.136     matthew  15837:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15838:     if ($NumBars < 3) {
                   15839:         $width = 120+$NumBars*32;
1.220     matthew  15840:         $xskip = 1;
1.225     matthew  15841:         $bar_width = 30;
                   15842:     } elsif ($NumBars < 5) {
                   15843:         $width = 120+$NumBars*20;
                   15844:         $xskip = 1;
                   15845:         $bar_width = 20;
1.220     matthew  15846:     } elsif ($NumBars < 10) {
1.136     matthew  15847:         $width = 120+$NumBars*15;
                   15848:         $xskip = 1;
                   15849:         $bar_width = 15;
                   15850:     } elsif ($NumBars <= 25) {
                   15851:         $width = 120+$NumBars*11;
                   15852:         $xskip = 5;
                   15853:         $bar_width = 8;
                   15854:     } elsif ($NumBars <= 50) {
                   15855:         $width = 120+$NumBars*8;
                   15856:         $xskip = 5;
                   15857:         $bar_width = 4;
                   15858:     } else {
                   15859:         $width = 120+$NumBars*8;
                   15860:         $xskip = 5;
                   15861:         $bar_width = 4;
                   15862:     }
                   15863:     #
1.137     matthew  15864:     $Max = 1 if ($Max < 1);
                   15865:     if ( int($Max) < $Max ) {
                   15866:         $Max++;
                   15867:         $Max = int($Max);
                   15868:     }
1.127     matthew  15869:     $Title  = '' if (! defined($Title));
                   15870:     $xlabel = '' if (! defined($xlabel));
                   15871:     $ylabel = '' if (! defined($ylabel));
1.369     www      15872:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15873:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15874:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15875:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15876:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15877:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15878:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15879:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15880:     $ValuesHash{$id.'.height'}   = $height;
                   15881:     $ValuesHash{$id.'.width'}    = $width;
                   15882:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15883:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15884:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15885:     #
1.228     matthew  15886:     # Deal with other parameters
                   15887:     while (my ($key,$value) = each(%$extra_settings)) {
                   15888:         $ValuesHash{$id.'.'.$key} = $value;
                   15889:     }
                   15890:     #
1.646     raeburn  15891:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15892:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15893: }
                   15894: 
                   15895: ############################################################
                   15896: ############################################################
                   15897: 
                   15898: =pod
                   15899: 
1.648     raeburn  15900: =item * &DrawXYGraph()
1.137     matthew  15901: 
1.138     matthew  15902: Facilitates the plotting of data in an XY graph.
                   15903: Puts plot definition data into the users environment in order for 
                   15904: graph.png to plot it.  Returns an <img> tag for the plot.
                   15905: 
                   15906: Inputs:
                   15907: 
                   15908: =over 4
                   15909: 
                   15910: =item $Title: string, the title of the plot
                   15911: 
                   15912: =item $xlabel: string, text describing the X-axis of the plot
                   15913: 
                   15914: =item $ylabel: string, text describing the Y-axis of the plot
                   15915: 
                   15916: =item $Max: scalar, the maximum Y value to use in the plot
                   15917: If $Max is < any data point, the graph will not be rendered.
                   15918: 
                   15919: =item $colors: Array ref containing the hex color codes for the data to be 
                   15920: plotted in.  If undefined, default values will be used.
                   15921: 
                   15922: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15923: 
                   15924: =item $Ydata: Array ref containing Array refs.  
1.185     www      15925: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15926: 
                   15927: =item %Values: hash indicating or overriding any default values which are 
                   15928: passed to graph.png.  
                   15929: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15930: 
                   15931: =back
                   15932: 
                   15933: Returns:
                   15934: 
                   15935: An <img> tag which references graph.png and the appropriate identifying
                   15936: information for the plot.
                   15937: 
1.137     matthew  15938: =cut
                   15939: 
                   15940: ############################################################
                   15941: ############################################################
                   15942: sub DrawXYGraph {
                   15943:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15944:     #
                   15945:     # Create the identifier for the graph
                   15946:     my $identifier = &get_cgi_id();
                   15947:     my $id = 'cgi.'.$identifier;
                   15948:     #
                   15949:     $Title  = '' if (! defined($Title));
                   15950:     $xlabel = '' if (! defined($xlabel));
                   15951:     $ylabel = '' if (! defined($ylabel));
                   15952:     my %ValuesHash = 
                   15953:         (
1.369     www      15954:          $id.'.title'  => &escape($Title),
                   15955:          $id.'.xlabel' => &escape($xlabel),
                   15956:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15957:          $id.'.y_max_value'=> $Max,
                   15958:          $id.'.labels'     => join(',',@$Xlabels),
                   15959:          $id.'.PlotType'   => 'XY',
                   15960:          );
                   15961:     #
                   15962:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15963:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15964:     }
                   15965:     #
                   15966:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15967:         return '';
                   15968:     }
                   15969:     my $NumSets=1;
1.138     matthew  15970:     foreach my $array (@{$Ydata}){
1.137     matthew  15971:         next if (! ref($array));
                   15972:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15973:     }
1.138     matthew  15974:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15975:     #
                   15976:     # Deal with other parameters
                   15977:     while (my ($key,$value) = each(%Values)) {
                   15978:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15979:     }
                   15980:     #
1.646     raeburn  15981:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15982:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15983: }
                   15984: 
                   15985: ############################################################
                   15986: ############################################################
                   15987: 
                   15988: =pod
                   15989: 
1.648     raeburn  15990: =item * &DrawXYYGraph()
1.138     matthew  15991: 
                   15992: Facilitates the plotting of data in an XY graph with two Y axes.
                   15993: Puts plot definition data into the users environment in order for 
                   15994: graph.png to plot it.  Returns an <img> tag for the plot.
                   15995: 
                   15996: Inputs:
                   15997: 
                   15998: =over 4
                   15999: 
                   16000: =item $Title: string, the title of the plot
                   16001: 
                   16002: =item $xlabel: string, text describing the X-axis of the plot
                   16003: 
                   16004: =item $ylabel: string, text describing the Y-axis of the plot
                   16005: 
                   16006: =item $colors: Array ref containing the hex color codes for the data to be 
                   16007: plotted in.  If undefined, default values will be used.
                   16008: 
                   16009: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   16010: 
                   16011: =item $Ydata1: The first data set
                   16012: 
                   16013: =item $Min1: The minimum value of the left Y-axis
                   16014: 
                   16015: =item $Max1: The maximum value of the left Y-axis
                   16016: 
                   16017: =item $Ydata2: The second data set
                   16018: 
                   16019: =item $Min2: The minimum value of the right Y-axis
                   16020: 
                   16021: =item $Max2: The maximum value of the left Y-axis
                   16022: 
                   16023: =item %Values: hash indicating or overriding any default values which are 
                   16024: passed to graph.png.  
                   16025: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   16026: 
                   16027: =back
                   16028: 
                   16029: Returns:
                   16030: 
                   16031: An <img> tag which references graph.png and the appropriate identifying
                   16032: information for the plot.
1.136     matthew  16033: 
                   16034: =cut
                   16035: 
                   16036: ############################################################
                   16037: ############################################################
1.137     matthew  16038: sub DrawXYYGraph {
                   16039:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16040:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16041:     #
                   16042:     # Create the identifier for the graph
                   16043:     my $identifier = &get_cgi_id();
                   16044:     my $id = 'cgi.'.$identifier;
                   16045:     #
                   16046:     $Title  = '' if (! defined($Title));
                   16047:     $xlabel = '' if (! defined($xlabel));
                   16048:     $ylabel = '' if (! defined($ylabel));
                   16049:     my %ValuesHash = 
                   16050:         (
1.369     www      16051:          $id.'.title'  => &escape($Title),
                   16052:          $id.'.xlabel' => &escape($xlabel),
                   16053:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16054:          $id.'.labels' => join(',',@$Xlabels),
                   16055:          $id.'.PlotType' => 'XY',
                   16056:          $id.'.NumSets' => 2,
1.137     matthew  16057:          $id.'.two_axes' => 1,
                   16058:          $id.'.y1_max_value' => $Max1,
                   16059:          $id.'.y1_min_value' => $Min1,
                   16060:          $id.'.y2_max_value' => $Max2,
                   16061:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16062:          );
                   16063:     #
1.137     matthew  16064:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16065:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16066:     }
                   16067:     #
                   16068:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16069:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16070:         return '';
                   16071:     }
                   16072:     my $NumSets=1;
1.137     matthew  16073:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16074:         next if (! ref($array));
                   16075:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16076:     }
                   16077:     #
                   16078:     # Deal with other parameters
                   16079:     while (my ($key,$value) = each(%Values)) {
                   16080:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16081:     }
                   16082:     #
1.646     raeburn  16083:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16084:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16085: }
                   16086: 
                   16087: ############################################################
                   16088: ############################################################
                   16089: 
                   16090: =pod
                   16091: 
1.157     matthew  16092: =back 
                   16093: 
1.139     matthew  16094: =head1 Statistics helper routines?  
                   16095: 
                   16096: Bad place for them but what the hell.
                   16097: 
1.157     matthew  16098: =over 4
                   16099: 
1.648     raeburn  16100: =item * &chartlink()
1.139     matthew  16101: 
                   16102: Returns a link to the chart for a specific student.  
                   16103: 
                   16104: Inputs:
                   16105: 
                   16106: =over 4
                   16107: 
                   16108: =item $linktext: The text of the link
                   16109: 
                   16110: =item $sname: The students username
                   16111: 
                   16112: =item $sdomain: The students domain
                   16113: 
                   16114: =back
                   16115: 
1.157     matthew  16116: =back
                   16117: 
1.139     matthew  16118: =cut
                   16119: 
                   16120: ############################################################
                   16121: ############################################################
                   16122: sub chartlink {
                   16123:     my ($linktext, $sname, $sdomain) = @_;
                   16124:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16125:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16126:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16127:        '">'.$linktext.'</a>';
1.153     matthew  16128: }
                   16129: 
                   16130: #######################################################
                   16131: #######################################################
                   16132: 
                   16133: =pod
                   16134: 
                   16135: =head1 Course Environment Routines
1.157     matthew  16136: 
                   16137: =over 4
1.153     matthew  16138: 
1.648     raeburn  16139: =item * &restore_course_settings()
1.153     matthew  16140: 
1.648     raeburn  16141: =item * &store_course_settings()
1.153     matthew  16142: 
                   16143: Restores/Store indicated form parameters from the course environment.
                   16144: Will not overwrite existing values of the form parameters.
                   16145: 
                   16146: Inputs: 
                   16147: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16148: 
                   16149: a hash ref describing the data to be stored.  For example:
                   16150:    
                   16151: %Save_Parameters = ('Status' => 'scalar',
                   16152:     'chartoutputmode' => 'scalar',
                   16153:     'chartoutputdata' => 'scalar',
                   16154:     'Section' => 'array',
1.373     raeburn  16155:     'Group' => 'array',
1.153     matthew  16156:     'StudentData' => 'array',
                   16157:     'Maps' => 'array');
                   16158: 
                   16159: Returns: both routines return nothing
                   16160: 
1.631     raeburn  16161: =back
                   16162: 
1.153     matthew  16163: =cut
                   16164: 
                   16165: #######################################################
                   16166: #######################################################
                   16167: sub store_course_settings {
1.496     albertel 16168:     return &store_settings($env{'request.course.id'},@_);
                   16169: }
                   16170: 
                   16171: sub store_settings {
1.153     matthew  16172:     # save to the environment
                   16173:     # appenv the same items, just to be safe
1.300     albertel 16174:     my $udom  = $env{'user.domain'};
                   16175:     my $uname = $env{'user.name'};
1.496     albertel 16176:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16177:     my %SaveHash;
                   16178:     my %AppHash;
                   16179:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16180:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16181:         my $envname = 'environment.'.$basename;
1.258     albertel 16182:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16183:             # Save this value away
                   16184:             if ($type eq 'scalar' &&
1.258     albertel 16185:                 (! exists($env{$envname}) || 
                   16186:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16187:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16188:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16189:             } elsif ($type eq 'array') {
                   16190:                 my $stored_form;
1.258     albertel 16191:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16192:                     $stored_form = join(',',
                   16193:                                         map {
1.369     www      16194:                                             &escape($_);
1.258     albertel 16195:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16196:                 } else {
                   16197:                     $stored_form = 
1.369     www      16198:                         &escape($env{'form.'.$setting});
1.153     matthew  16199:                 }
                   16200:                 # Determine if the array contents are the same.
1.258     albertel 16201:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16202:                     $SaveHash{$basename} = $stored_form;
                   16203:                     $AppHash{$envname}   = $stored_form;
                   16204:                 }
                   16205:             }
                   16206:         }
                   16207:     }
                   16208:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16209:                                           $udom,$uname);
1.153     matthew  16210:     if ($put_result !~ /^(ok|delayed)/) {
                   16211:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16212:                                  'got error:'.$put_result);
                   16213:     }
                   16214:     # Make sure these settings stick around in this session, too
1.646     raeburn  16215:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16216:     return;
                   16217: }
                   16218: 
                   16219: sub restore_course_settings {
1.499     albertel 16220:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16221: }
                   16222: 
                   16223: sub restore_settings {
                   16224:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16225:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16226:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16227:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16228:             '.'.$setting;
1.258     albertel 16229:         if (exists($env{$envname})) {
1.153     matthew  16230:             if ($type eq 'scalar') {
1.258     albertel 16231:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16232:             } elsif ($type eq 'array') {
1.258     albertel 16233:                 $env{'form.'.$setting} = [ 
1.153     matthew  16234:                                            map { 
1.369     www      16235:                                                &unescape($_); 
1.258     albertel 16236:                                            } split(',',$env{$envname})
1.153     matthew  16237:                                            ];
                   16238:             }
                   16239:         }
                   16240:     }
1.127     matthew  16241: }
                   16242: 
1.618     raeburn  16243: #######################################################
                   16244: #######################################################
                   16245: 
                   16246: =pod
                   16247: 
                   16248: =head1 Domain E-mail Routines  
                   16249: 
                   16250: =over 4
                   16251: 
1.648     raeburn  16252: =item * &build_recipient_list()
1.618     raeburn  16253: 
1.1144    raeburn  16254: Build recipient lists for following types of e-mail:
1.766     raeburn  16255: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16256: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16257: module change checking, student/employee ID conflict checks, as
                   16258: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16259: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16260: 
                   16261: Inputs:
1.619     raeburn  16262: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16263: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16264: requestsmail, updatesmail, or idconflictsmail).
                   16265: 
1.619     raeburn  16266: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16267: 
1.619     raeburn  16268: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16269: i.e., predates configuration by DC via domainprefs.pm
                   16270: 
                   16271: $requname username of requester (if mailing type is helpdeskmail)
                   16272: 
                   16273: $requdom domain of requester (if mailing type is helpdeskmail)
                   16274: 
                   16275: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16276: 
1.618     raeburn  16277: 
1.655     raeburn  16278: Returns: comma separated list of addresses to which to send e-mail.
                   16279: 
                   16280: =back
1.618     raeburn  16281: 
                   16282: =cut
                   16283: 
                   16284: ############################################################
                   16285: ############################################################
                   16286: sub build_recipient_list {
1.1297    raeburn  16287:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16288:     my @recipients;
1.1270    raeburn  16289:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16290:     my %domconfig =
1.1270    raeburn  16291:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16292:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16293:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16294:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16295:                 my @contacts = ('adminemail','supportemail');
                   16296:                 foreach my $item (@contacts) {
                   16297:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16298:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16299:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16300:                             push(@recipients,$addr);
                   16301:                         }
1.619     raeburn  16302:                     }
1.1270    raeburn  16303:                 }
                   16304:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16305:                 if ($mailing eq 'helpdeskmail') {
                   16306:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16307:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16308:                         my @ok_bccs;
                   16309:                         foreach my $bcc (@bccs) {
                   16310:                             $bcc =~ s/^\s+//g;
                   16311:                             $bcc =~ s/\s+$//g;
                   16312:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16313:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16314:                                     push(@ok_bccs,$bcc);
                   16315:                                 }
                   16316:                             }
                   16317:                         }
                   16318:                         if (@ok_bccs > 0) {
                   16319:                             $allbcc = join(', ',@ok_bccs);
                   16320:                         }
                   16321:                     }
                   16322:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16323:                 }
                   16324:             }
1.766     raeburn  16325:         } elsif ($origmail ne '') {
1.1270    raeburn  16326:             $lastresort = $origmail;
1.618     raeburn  16327:         }
1.1297    raeburn  16328:         if ($mailing eq 'helpdeskmail') {
                   16329:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16330:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16331:                 my ($inststatus,$inststatus_checked);
                   16332:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16333:                     ($env{'user.domain'} ne 'public')) {
                   16334:                     $inststatus_checked = 1;
                   16335:                     $inststatus = $env{'environment.inststatus'};
                   16336:                 }
                   16337:                 unless ($inststatus_checked) {
                   16338:                     if (($requname ne '') && ($requdom ne '')) {
                   16339:                         if (($requname =~ /^$match_username$/) &&
                   16340:                             ($requdom =~ /^$match_domain$/) &&
                   16341:                             (&Apache::lonnet::domain($requdom))) {
                   16342:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16343:                                                                       $requdom);
                   16344:                             unless ($requhome eq 'no_host') {
                   16345:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16346:                                 $inststatus = $userenv{'inststatus'};
                   16347:                                 $inststatus_checked = 1;
                   16348:                             }
                   16349:                         }
                   16350:                     }
                   16351:                 }
                   16352:                 unless ($inststatus_checked) {
                   16353:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16354:                         my %srch = (srchby     => 'email',
                   16355:                                     srchdomain => $defdom,
                   16356:                                     srchterm   => $reqemail,
                   16357:                                     srchtype   => 'exact');
                   16358:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16359:                         foreach my $uname (keys(%srch_results)) {
                   16360:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16361:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16362:                                 $inststatus_checked = 1;
                   16363:                                 last;
                   16364:                             }
                   16365:                         }
                   16366:                         unless ($inststatus_checked) {
                   16367:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16368:                             if ($dirsrchres eq 'ok') {
                   16369:                                 foreach my $uname (keys(%srch_results)) {
                   16370:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16371:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16372:                                         $inststatus_checked = 1;
                   16373:                                         last;
                   16374:                                     }
                   16375:                                 }
                   16376:                             }
                   16377:                         }
                   16378:                     }
                   16379:                 }
                   16380:                 if ($inststatus ne '') {
                   16381:                     foreach my $status (split(/\:/,$inststatus)) {
                   16382:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16383:                             my @contacts = ('adminemail','supportemail');
                   16384:                             foreach my $item (@contacts) {
                   16385:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16386:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16387:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16388:                                         push(@recipients,$addr);
                   16389:                                     }
                   16390:                                 }
                   16391:                             }
                   16392:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16393:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16394:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16395:                                 my @ok_bccs;
                   16396:                                 foreach my $bcc (@bccs) {
                   16397:                                     $bcc =~ s/^\s+//g;
                   16398:                                     $bcc =~ s/\s+$//g;
                   16399:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16400:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16401:                                             push(@ok_bccs,$bcc);
                   16402:                                         }
                   16403:                                     }
                   16404:                                 }
                   16405:                                 if (@ok_bccs > 0) {
                   16406:                                     $allbcc = join(', ',@ok_bccs);
                   16407:                                 }
                   16408:                             }
                   16409:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16410:                             last;
                   16411:                         }
                   16412:                     }
                   16413:                 }
                   16414:             }
                   16415:         }
1.619     raeburn  16416:     } elsif ($origmail ne '') {
1.1270    raeburn  16417:         $lastresort = $origmail;
                   16418:     }
1.1297    raeburn  16419:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16420:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16421:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16422:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16423:             my %what = (
                   16424:                           perlvar => 1,
                   16425:                        );
                   16426:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16427:             if ($primary) {
                   16428:                 my $gotaddr;
                   16429:                 my ($result,$returnhash) =
                   16430:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16431:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16432:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16433:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16434:                         $gotaddr = 1;
                   16435:                     }
                   16436:                 }
                   16437:                 unless ($gotaddr) {
                   16438:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16439:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16440:                     unless ($uintdom eq $intdom) {
                   16441:                         my %domconfig =
                   16442:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16443:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16444:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16445:                                 my @contacts = ('adminemail','supportemail');
                   16446:                                 foreach my $item (@contacts) {
                   16447:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16448:                                         my $addr = $domconfig{'contacts'}{$item};
                   16449:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16450:                                             push(@recipients,$addr);
                   16451:                                         }
                   16452:                                     }
                   16453:                                 }
                   16454:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16455:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16456:                                 }
                   16457:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16458:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16459:                                     my @ok_bccs;
                   16460:                                     foreach my $bcc (@bccs) {
                   16461:                                         $bcc =~ s/^\s+//g;
                   16462:                                         $bcc =~ s/\s+$//g;
                   16463:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16464:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16465:                                                 push(@ok_bccs,$bcc);
                   16466:                                             }
                   16467:                                         }
                   16468:                                     }
                   16469:                                     if (@ok_bccs > 0) {
                   16470:                                         $allbcc = join(', ',@ok_bccs);
                   16471:                                     }
                   16472:                                 }
                   16473:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16474:                             }
                   16475:                         }
                   16476:                     }
                   16477:                 }
                   16478:             }
                   16479:         }
1.618     raeburn  16480:     }
1.688     raeburn  16481:     if (defined($defmail)) {
                   16482:         if ($defmail ne '') {
                   16483:             push(@recipients,$defmail);
                   16484:         }
1.618     raeburn  16485:     }
                   16486:     if ($otheremails) {
1.619     raeburn  16487:         my @others;
                   16488:         if ($otheremails =~ /,/) {
                   16489:             @others = split(/,/,$otheremails);
1.618     raeburn  16490:         } else {
1.619     raeburn  16491:             push(@others,$otheremails);
                   16492:         }
                   16493:         foreach my $addr (@others) {
                   16494:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16495:                 push(@recipients,$addr);
                   16496:             }
1.618     raeburn  16497:         }
                   16498:     }
1.1298    raeburn  16499:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16500:         if ((!@recipients) && ($lastresort ne '')) {
                   16501:             push(@recipients,$lastresort);
                   16502:         }
                   16503:     } elsif ($lastresort ne '') {
                   16504:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16505:             push(@recipients,$lastresort);
                   16506:         }
                   16507:     }
1.1271    raeburn  16508:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16509:     if (wantarray) {
                   16510:         return ($recipientlist,$allbcc,$addtext);
                   16511:     } else {
                   16512:         return $recipientlist;
                   16513:     }
1.618     raeburn  16514: }
                   16515: 
1.127     matthew  16516: ############################################################
                   16517: ############################################################
1.154     albertel 16518: 
1.655     raeburn  16519: =pod
                   16520: 
1.1224    musolffc 16521: =over 4
                   16522: 
1.1223    musolffc 16523: =item * &mime_email()
                   16524: 
                   16525: Sends an email with a possible attachment
                   16526: 
                   16527: Inputs:
                   16528: 
                   16529: =over 4
                   16530: 
                   16531: from -              Sender's email address
                   16532: 
1.1343    raeburn  16533: replyto -           Reply-To email address
                   16534: 
1.1223    musolffc 16535: to -                Email address of recipient
                   16536: 
                   16537: subject -           Subject of email
                   16538: 
                   16539: body -              Body of email
                   16540: 
                   16541: cc_string -         Carbon copy email address
                   16542: 
                   16543: bcc -               Blind carbon copy email address
                   16544: 
                   16545: attachment_path -   Path of file to be attached
                   16546: 
                   16547: file_name -         Name of file to be attached
                   16548: 
                   16549: attachment_text -   The body of an attachment of type "TEXT"
                   16550: 
                   16551: =back
                   16552: 
                   16553: =back
                   16554: 
                   16555: =cut
                   16556: 
                   16557: ############################################################
                   16558: ############################################################
                   16559: 
                   16560: sub mime_email {
1.1343    raeburn  16561:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16562:         $file_name,$attachment_text) = @_;
                   16563:  
1.1223    musolffc 16564:     my $msg = MIME::Lite->new(
                   16565:              From    => $from,
                   16566:              To      => $to,
                   16567:              Subject => $subject,
                   16568:              Type    =>'TEXT',
                   16569:              Data    => $body,
                   16570:              );
1.1343    raeburn  16571:     if ($replyto ne '') {
                   16572:         $msg->add("Reply-To" => $replyto);
                   16573:     }
1.1223    musolffc 16574:     if ($cc_string ne '') {
                   16575:         $msg->add("Cc" => $cc_string);
                   16576:     }
                   16577:     if ($bcc ne '') {
                   16578:         $msg->add("Bcc" => $bcc);
                   16579:     }
                   16580:     $msg->attr("content-type"         => "text/plain");
                   16581:     $msg->attr("content-type.charset" => "UTF-8");
                   16582:     # Attach file if given
                   16583:     if ($attachment_path) {
                   16584:         unless ($file_name) {
                   16585:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16586:         }
                   16587:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16588:         $msg->attach(Type     => $type,
                   16589:                      Path     => $attachment_path,
                   16590:                      Filename => $file_name
                   16591:                      );
                   16592:     # Otherwise attach text if given
                   16593:     } elsif ($attachment_text) {
                   16594:         $msg->attach(Type => 'TEXT',
                   16595:                      Data => $attachment_text);
                   16596:     }
                   16597:     # Send it
                   16598:     $msg->send('sendmail');
                   16599: }
                   16600: 
                   16601: ############################################################
                   16602: ############################################################
                   16603: 
                   16604: =pod
                   16605: 
1.655     raeburn  16606: =head1 Course Catalog Routines
                   16607: 
                   16608: =over 4
                   16609: 
                   16610: =item * &gather_categories()
                   16611: 
                   16612: Converts category definitions - keys of categories hash stored in  
                   16613: coursecategories in configuration.db on the primary library server in a 
                   16614: domain - to an array.  Also generates javascript and idx hash used to 
                   16615: generate Domain Coordinator interface for editing Course Categories.
                   16616: 
                   16617: Inputs:
1.663     raeburn  16618: 
1.655     raeburn  16619: categories (reference to hash of category definitions).
1.663     raeburn  16620: 
1.655     raeburn  16621: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16622:       categories and subcategories).
1.663     raeburn  16623: 
1.655     raeburn  16624: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16625:       editing Course Categories).
1.663     raeburn  16626: 
1.655     raeburn  16627: jsarray (reference to array of categories used to create Javascript arrays for
                   16628:          Domain Coordinator interface for editing Course Categories).
                   16629: 
                   16630: Returns: nothing
                   16631: 
                   16632: Side effects: populates cats, idx and jsarray. 
                   16633: 
                   16634: =cut
                   16635: 
                   16636: sub gather_categories {
                   16637:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16638:     my %counters;
                   16639:     my $num = 0;
                   16640:     foreach my $item (keys(%{$categories})) {
                   16641:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16642:         if ($container eq '' && $depth == 0) {
                   16643:             $cats->[$depth][$categories->{$item}] = $cat;
                   16644:         } else {
                   16645:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16646:         }
                   16647:         my ($escitem,$tail) = split(/:/,$item,2);
                   16648:         if ($counters{$tail} eq '') {
                   16649:             $counters{$tail} = $num;
                   16650:             $num ++;
                   16651:         }
                   16652:         if (ref($idx) eq 'HASH') {
                   16653:             $idx->{$item} = $counters{$tail};
                   16654:         }
                   16655:         if (ref($jsarray) eq 'ARRAY') {
                   16656:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16657:         }
                   16658:     }
                   16659:     return;
                   16660: }
                   16661: 
                   16662: =pod
                   16663: 
                   16664: =item * &extract_categories()
                   16665: 
                   16666: Used to generate breadcrumb trails for course categories.
                   16667: 
                   16668: Inputs:
1.663     raeburn  16669: 
1.655     raeburn  16670: categories (reference to hash of category definitions).
1.663     raeburn  16671: 
1.655     raeburn  16672: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16673:       categories and subcategories).
1.663     raeburn  16674: 
1.655     raeburn  16675: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16676: 
1.655     raeburn  16677: allitems (reference to hash - key is category key 
                   16678:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16679: 
1.655     raeburn  16680: idx (reference to hash of counters used in Domain Coordinator interface for
                   16681:       editing Course Categories).
1.663     raeburn  16682: 
1.655     raeburn  16683: jsarray (reference to array of categories used to create Javascript arrays for
                   16684:          Domain Coordinator interface for editing Course Categories).
                   16685: 
1.665     raeburn  16686: subcats (reference to hash of arrays containing all subcategories within each 
                   16687:          category, -recursive)
                   16688: 
1.1321    raeburn  16689: maxd (reference to hash used to hold max depth for all top-level categories).
                   16690: 
1.655     raeburn  16691: Returns: nothing
                   16692: 
                   16693: Side effects: populates trails and allitems hash references.
                   16694: 
                   16695: =cut
                   16696: 
                   16697: sub extract_categories {
1.1321    raeburn  16698:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16699:     if (ref($categories) eq 'HASH') {
                   16700:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16701:         if (ref($cats->[0]) eq 'ARRAY') {
                   16702:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16703:                 my $name = $cats->[0][$i];
                   16704:                 my $item = &escape($name).'::0';
                   16705:                 my $trailstr;
                   16706:                 if ($name eq 'instcode') {
                   16707:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16708:                 } elsif ($name eq 'communities') {
                   16709:                     $trailstr = &mt('Communities');
1.1239    raeburn  16710:                 } elsif ($name eq 'placement') {
                   16711:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16712:                 } else {
                   16713:                     $trailstr = $name;
                   16714:                 }
                   16715:                 if ($allitems->{$item} eq '') {
                   16716:                     push(@{$trails},$trailstr);
                   16717:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16718:                 }
                   16719:                 my @parents = ($name);
                   16720:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16721:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16722:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16723:                         if (ref($subcats) eq 'HASH') {
                   16724:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16725:                         }
1.1321    raeburn  16726:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16727:                     }
                   16728:                 } else {
                   16729:                     if (ref($subcats) eq 'HASH') {
                   16730:                         $subcats->{$item} = [];
1.655     raeburn  16731:                     }
1.1321    raeburn  16732:                     if (ref($maxd) eq 'HASH') {
                   16733:                         $maxd->{$name} = 1;
                   16734:                     }
1.655     raeburn  16735:                 }
                   16736:             }
                   16737:         }
                   16738:     }
                   16739:     return;
                   16740: }
                   16741: 
                   16742: =pod
                   16743: 
1.1162    raeburn  16744: =item * &recurse_categories()
1.655     raeburn  16745: 
                   16746: Recursively used to generate breadcrumb trails for course categories.
                   16747: 
                   16748: Inputs:
1.663     raeburn  16749: 
1.655     raeburn  16750: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16751:       categories and subcategories).
1.663     raeburn  16752: 
1.655     raeburn  16753: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16754: 
                   16755: category (current course category, for which breadcrumb trail is being generated).
                   16756: 
                   16757: trails (reference to array of breadcrumb trails for each category).
                   16758: 
1.655     raeburn  16759: allitems (reference to hash - key is category key
                   16760:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16761: 
1.655     raeburn  16762: parents (array containing containers directories for current category, 
                   16763:          back to top level). 
                   16764: 
                   16765: Returns: nothing
                   16766: 
                   16767: Side effects: populates trails and allitems hash references
                   16768: 
                   16769: =cut
                   16770: 
                   16771: sub recurse_categories {
1.1321    raeburn  16772:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16773:     my $shallower = $depth - 1;
                   16774:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16775:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16776:             my $name = $cats->[$depth]{$category}[$k];
                   16777:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16778:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16779:             if ($allitems->{$item} eq '') {
                   16780:                 push(@{$trails},$trailstr);
                   16781:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16782:             }
                   16783:             my $deeper = $depth+1;
                   16784:             push(@{$parents},$category);
1.665     raeburn  16785:             if (ref($subcats) eq 'HASH') {
                   16786:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16787:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16788:                     my $higher;
                   16789:                     if ($j > 0) {
                   16790:                         $higher = &escape($parents->[$j]).':'.
                   16791:                                   &escape($parents->[$j-1]).':'.$j;
                   16792:                     } else {
                   16793:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16794:                     }
                   16795:                     push(@{$subcats->{$higher}},$subcat);
                   16796:                 }
                   16797:             }
                   16798:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16799:                                 $subcats,$maxd);
1.655     raeburn  16800:             pop(@{$parents});
                   16801:         }
                   16802:     } else {
                   16803:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16804:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16805:         if ($allitems->{$item} eq '') {
                   16806:             push(@{$trails},$trailstr);
                   16807:             $allitems->{$item} = scalar(@{$trails})-1;
                   16808:         }
1.1321    raeburn  16809:         if (ref($maxd) eq 'HASH') {
                   16810:             if ($depth > $maxd->{$parents->[0]}) {
                   16811:                 $maxd->{$parents->[0]} = $depth;
                   16812:             }
                   16813:         }
1.655     raeburn  16814:     }
                   16815:     return;
                   16816: }
                   16817: 
1.663     raeburn  16818: =pod
                   16819: 
1.1162    raeburn  16820: =item * &assign_categories_table()
1.663     raeburn  16821: 
                   16822: Create a datatable for display of hierarchical categories in a domain,
                   16823: with checkboxes to allow a course to be categorized. 
                   16824: 
                   16825: Inputs:
                   16826: 
                   16827: cathash - reference to hash of categories defined for the domain (from
                   16828:           configuration.db)
                   16829: 
                   16830: currcat - scalar with an & separated list of categories assigned to a course. 
                   16831: 
1.919     raeburn  16832: type    - scalar contains course type (Course or Community).
                   16833: 
1.1260    raeburn  16834: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16835:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16836: 
1.663     raeburn  16837: Returns: $output (markup to be displayed) 
                   16838: 
                   16839: =cut
                   16840: 
                   16841: sub assign_categories_table {
1.1259    raeburn  16842:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16843:     my $output;
                   16844:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16845:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16846:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16847:         $maxdepth = scalar(@cats);
                   16848:         if (@cats > 0) {
                   16849:             my $itemcount = 0;
                   16850:             if (ref($cats[0]) eq 'ARRAY') {
                   16851:                 my @currcategories;
                   16852:                 if ($currcat ne '') {
                   16853:                     @currcategories = split('&',$currcat);
                   16854:                 }
1.919     raeburn  16855:                 my $table;
1.663     raeburn  16856:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16857:                     my $parent = $cats[0][$i];
1.919     raeburn  16858:                     next if ($parent eq 'instcode');
                   16859:                     if ($type eq 'Community') {
                   16860:                         next unless ($parent eq 'communities');
1.1239    raeburn  16861:                     } elsif ($type eq 'Placement') {
                   16862:                         next unless ($parent eq 'placement');
1.919     raeburn  16863:                     } else {
1.1239    raeburn  16864:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16865:                     }
1.663     raeburn  16866:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16867:                     my $item = &escape($parent).'::0';
                   16868:                     my $checked = '';
                   16869:                     if (@currcategories > 0) {
                   16870:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16871:                             $checked = ' checked="checked"';
1.663     raeburn  16872:                         }
                   16873:                     }
1.919     raeburn  16874:                     my $parent_title = $parent;
                   16875:                     if ($parent eq 'communities') {
                   16876:                         $parent_title = &mt('Communities');
1.1239    raeburn  16877:                     } elsif ($parent eq 'placement') {
                   16878:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16879:                     }
                   16880:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16881:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16882:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16883:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16884:                     my $depth = 1;
                   16885:                     push(@path,$parent);
1.1259    raeburn  16886:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16887:                     pop(@path);
1.919     raeburn  16888:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16889:                     $itemcount ++;
                   16890:                 }
1.919     raeburn  16891:                 if ($itemcount) {
                   16892:                     $output = &Apache::loncommon::start_data_table().
                   16893:                               $table.
                   16894:                               &Apache::loncommon::end_data_table();
                   16895:                 }
1.663     raeburn  16896:             }
                   16897:         }
                   16898:     }
                   16899:     return $output;
                   16900: }
                   16901: 
                   16902: =pod
                   16903: 
1.1162    raeburn  16904: =item * &assign_category_rows()
1.663     raeburn  16905: 
                   16906: Create a datatable row for display of nested categories in a domain,
                   16907: with checkboxes to allow a course to be categorized,called recursively.
                   16908: 
                   16909: Inputs:
                   16910: 
                   16911: itemcount - track row number for alternating colors
                   16912: 
                   16913: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16914:       categories and subcategories.
                   16915: 
                   16916: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16917: 
                   16918: parent - parent of current category item
                   16919: 
                   16920: path - Array containing all categories back up through the hierarchy from the
                   16921:        current category to the top level.
                   16922: 
                   16923: currcategories - reference to array of current categories assigned to the course
                   16924: 
1.1260    raeburn  16925: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16926:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16927: 
1.663     raeburn  16928: Returns: $output (markup to be displayed).
                   16929: 
                   16930: =cut
                   16931: 
                   16932: sub assign_category_rows {
1.1259    raeburn  16933:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16934:     my ($text,$name,$item,$chgstr);
                   16935:     if (ref($cats) eq 'ARRAY') {
                   16936:         my $maxdepth = scalar(@{$cats});
                   16937:         if (ref($cats->[$depth]) eq 'HASH') {
                   16938:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16939:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16940:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16941:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16942:                 for (my $j=0; $j<$numchildren; $j++) {
                   16943:                     $name = $cats->[$depth]{$parent}[$j];
                   16944:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16945:                     my $deeper = $depth+1;
                   16946:                     my $checked = '';
                   16947:                     if (ref($currcategories) eq 'ARRAY') {
                   16948:                         if (@{$currcategories} > 0) {
                   16949:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16950:                                 $checked = ' checked="checked"';
1.663     raeburn  16951:                             }
                   16952:                         }
                   16953:                     }
1.664     raeburn  16954:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16955:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16956:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16957:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16958:                              '</td><td>';
1.663     raeburn  16959:                     if (ref($path) eq 'ARRAY') {
                   16960:                         push(@{$path},$name);
1.1259    raeburn  16961:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16962:                         pop(@{$path});
                   16963:                     }
                   16964:                     $text .= '</td></tr>';
                   16965:                 }
                   16966:                 $text .= '</table></td>';
                   16967:             }
                   16968:         }
                   16969:     }
                   16970:     return $text;
                   16971: }
                   16972: 
1.1181    raeburn  16973: =pod
                   16974: 
                   16975: =back
                   16976: 
                   16977: =cut
                   16978: 
1.655     raeburn  16979: ############################################################
                   16980: ############################################################
                   16981: 
                   16982: 
1.443     albertel 16983: sub commit_customrole {
1.1408    raeburn  16984:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16985:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16986:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16987:                      $context,$othdomby,$requester);
1.630     raeburn  16988:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16989:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16990:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16991:     if (wantarray) {
                   16992:         return ($output,$result);
                   16993:     } else {
                   16994:         return $output;
                   16995:     }
1.443     albertel 16996: }
                   16997: 
                   16998: sub commit_standardrole {
1.1408    raeburn  16999:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   17000:         $othdomby,$requester) = @_;
1.1399    raeburn  17001:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  17002:     if ($context eq 'auto') {
                   17003:         $linefeed = "\n";
                   17004:     } else {
                   17005:         $linefeed = "<br />\n";
                   17006:     }  
1.443     albertel 17007:     if ($three eq 'st') {
1.1399    raeburn  17008:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  17009:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   17010:                                       $requester);
1.541     raeburn  17011:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  17012:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   17013:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 17014:         } else {
1.541     raeburn  17015:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 17016:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17017:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   17018:             if ($context eq 'auto') {
                   17019:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   17020:             } else {
                   17021:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   17022:                &mt('Add to classlist').': <b>ok</b>';
                   17023:             }
                   17024:             $output .= $linefeed;
1.443     albertel 17025:         }
                   17026:     } else {
                   17027:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   17028:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  17029:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  17030:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   17031:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  17032:         if ($context eq 'auto') {
                   17033:             $output .= $result.$linefeed;
                   17034:         } else {
                   17035:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   17036:         }
1.443     albertel 17037:     }
1.1399    raeburn  17038:     if (wantarray) {
                   17039:         return ($output,$result);
                   17040:     } else {
                   17041:         return $output;
                   17042:     }
1.443     albertel 17043: }
                   17044: 
                   17045: sub commit_studentrole {
1.1116    raeburn  17046:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17047:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17048:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17049:     if ($context eq 'auto') {
                   17050:         $linefeed = "\n";
                   17051:     } else {
                   17052:         $linefeed = '<br />'."\n";
                   17053:     }
1.443     albertel 17054:     if (defined($one) && defined($two)) {
                   17055:         my $cid=$one.'_'.$two;
                   17056:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17057:         my $secchange = 0;
                   17058:         my $expire_role_result;
                   17059:         my $modify_section_result;
1.628     raeburn  17060:         if ($oldsec ne '-1') { 
                   17061:             if ($oldsec ne $sec) {
1.443     albertel 17062:                 $secchange = 1;
1.628     raeburn  17063:                 my $now = time;
1.443     albertel 17064:                 my $uurl='/'.$cid;
                   17065:                 $uurl=~s/\_/\//g;
                   17066:                 if ($oldsec) {
                   17067:                     $uurl.='/'.$oldsec;
                   17068:                 }
1.626     raeburn  17069:                 $oldsecurl = $uurl;
1.628     raeburn  17070:                 $expire_role_result = 
1.1408    raeburn  17071:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17072:                                                 '','','',$context,$othdomby,$requester);
                   17073:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17074:                     if ($expire_role_result eq 'refused') {
                   17075:                         my @roles = ('st');
                   17076:                         my @statuses = ('previous');
                   17077:                         my @roledoms = ($one);
                   17078:                         my $withsec = 1;
                   17079:                         my %roleshash = 
                   17080:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17081:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17082:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17083:                             my ($oldstart,$oldend) = 
                   17084:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17085:                             if ($oldend > 0 && $oldend <= $now) {
                   17086:                                 $expire_role_result = 'ok';
                   17087:                             }
                   17088:                         }
                   17089:                     }
                   17090:                 }
1.443     albertel 17091:                 $result = $expire_role_result;
                   17092:             }
                   17093:         }
                   17094:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17095:             $modify_section_result = 
                   17096:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17097:                                                            undef,undef,undef,$sec,
                   17098:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17099:                                                            '',$context,$credits,'',
                   17100:                                                            $othdomby,$requester);
1.443     albertel 17101:             if ($modify_section_result =~ /^ok/) {
                   17102:                 if ($secchange == 1) {
1.628     raeburn  17103:                     if ($sec eq '') {
                   17104:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17105:                     } else {
                   17106:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17107:                     }
1.443     albertel 17108:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17109:                     if ($sec eq '') {
                   17110:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17111:                     } else {
                   17112:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17113:                     }
1.443     albertel 17114:                 } else {
1.628     raeburn  17115:                     if ($sec eq '') {
                   17116:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17117:                     } else {
                   17118:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17119:                     }
1.443     albertel 17120:                 }
                   17121:             } else {
1.1115    raeburn  17122:                 if ($secchange) { 
1.628     raeburn  17123:                     $$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;
                   17124:                 } else {
                   17125:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17126:                 }
1.443     albertel 17127:             }
                   17128:             $result = $modify_section_result;
                   17129:         } elsif ($secchange == 1) {
1.628     raeburn  17130:             if ($oldsec eq '') {
1.1103    raeburn  17131:                 $$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  17132:             } else {
                   17133:                 $$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;
                   17134:             }
1.626     raeburn  17135:             if ($expire_role_result eq 'refused') {
                   17136:                 my $newsecurl = '/'.$cid;
                   17137:                 $newsecurl =~ s/\_/\//g;
                   17138:                 if ($sec ne '') {
                   17139:                     $newsecurl.='/'.$sec;
                   17140:                 }
                   17141:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17142:                     if ($sec eq '') {
                   17143:                         $$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;
                   17144:                     } else {
                   17145:                         $$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;
                   17146:                     }
                   17147:                 }
                   17148:             }
1.443     albertel 17149:         }
                   17150:     } else {
1.626     raeburn  17151:         $$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 17152:         $result = "error: incomplete course id\n";
                   17153:     }
                   17154:     return $result;
                   17155: }
                   17156: 
1.1108    raeburn  17157: sub show_role_extent {
                   17158:     my ($scope,$context,$role) = @_;
                   17159:     $scope =~ s{^/}{};
                   17160:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17161:     push(@courseroles,'co');
                   17162:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17163:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17164:         $scope =~ s{/}{_};
                   17165:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17166:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17167:         my ($audom,$auname) = split(/\//,$scope);
                   17168:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17169:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17170:     } else {
                   17171:         $scope =~ s{/$}{};
                   17172:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17173:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17174:     }
                   17175: }
                   17176: 
1.443     albertel 17177: ############################################################
                   17178: ############################################################
                   17179: 
1.566     albertel 17180: sub check_clone {
1.578     raeburn  17181:     my ($args,$linefeed) = @_;
1.566     albertel 17182:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17183:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17184:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17185:     my $clonetitle;
                   17186:     my @clonemsg;
1.566     albertel 17187:     my $can_clone = 0;
1.944     raeburn  17188:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17189:     if ($lctype ne 'community') {
                   17190:         $lctype = 'course';
                   17191:     }
1.566     albertel 17192:     if ($clonehome eq 'no_host') {
1.944     raeburn  17193:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17194:             push(@clonemsg,({
                   17195:                               mt => 'No new community created.',
                   17196:                               args => [],
                   17197:                             },
                   17198:                             {
                   17199:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17200:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17201:                             }));
1.908     raeburn  17202:         } else {
1.1344    raeburn  17203:             push(@clonemsg,({
                   17204:                               mt => 'No new course created.',
                   17205:                               args => [],
                   17206:                             },
                   17207:                             {
                   17208:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17209:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17210:                             }));
                   17211:         }
1.566     albertel 17212:     } else {
                   17213: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17214:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17215:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17216:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17217:                 push(@clonemsg,({
                   17218:                                   mt => 'No new community created.',
                   17219:                                   args => [],
                   17220:                                 },
                   17221:                                 {
                   17222:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17223:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17224:                                 }));
                   17225:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17226:             }
                   17227:         }
1.1262    raeburn  17228: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17229:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17230: 	    $can_clone = 1;
                   17231: 	} else {
1.1221    raeburn  17232: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17233: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17234:             if ($clonehash{'cloners'} eq '') {
                   17235:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17236:                 if ($domdefs{'canclone'}) {
                   17237:                     unless ($domdefs{'canclone'} eq 'none') {
                   17238:                         if ($domdefs{'canclone'} eq 'domain') {
                   17239:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17240:                                 $can_clone = 1;
                   17241:                             }
                   17242:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17243:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17244:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17245:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17246:                                 $can_clone = 1;
                   17247:                             }
                   17248:                         }
                   17249:                     }
                   17250:                 }
1.578     raeburn  17251:             } else {
1.1221    raeburn  17252: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17253:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17254:                     $can_clone = 1;
1.1221    raeburn  17255:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17256:                     $can_clone = 1;
1.1225    raeburn  17257:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17258:                     $can_clone = 1;
1.1221    raeburn  17259:                 }
                   17260:                 unless ($can_clone) {
1.1225    raeburn  17261:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17262:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17263:                         my (%gotdomdefaults,%gotcodedefaults);
                   17264:                         foreach my $cloner (@cloners) {
                   17265:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17266:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17267:                                 my (%codedefaults,@code_order);
                   17268:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17269:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17270:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17271:                                     }
                   17272:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17273:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17274:                                     }
                   17275:                                 } else {
                   17276:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17277:                                                                             \%codedefaults,
                   17278:                                                                             \@code_order);
                   17279:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17280:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17281:                                 }
                   17282:                                 if (@code_order > 0) {
                   17283:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17284:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17285:                                                                                 $args->{'crscode'})) {
                   17286:                                         $can_clone = 1;
                   17287:                                         last;
                   17288:                                     }
                   17289:                                 }
                   17290:                             }
                   17291:                         }
                   17292:                     }
1.1225    raeburn  17293:                 }
                   17294:             }
                   17295:             unless ($can_clone) {
                   17296:                 my $ccrole = 'cc';
                   17297:                 if ($args->{'crstype'} eq 'Community') {
                   17298:                     $ccrole = 'co';
                   17299:                 }
                   17300: 	        my %roleshash =
                   17301: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17302: 					          $args->{'ccdomain'},
                   17303:                                                   'userroles',['active'],[$ccrole],
                   17304: 					          [$args->{'clonedomain'}]);
                   17305: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17306:                     $can_clone = 1;
                   17307:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17308:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17309:                     $can_clone = 1;
1.1221    raeburn  17310:                 }
                   17311:             }
                   17312:             unless ($can_clone) {
                   17313:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17314:                     push(@clonemsg,({
                   17315:                                       mt => 'No new community created.',
                   17316:                                       args => [],
                   17317:                                     },
                   17318:                                     {
                   17319:                                       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]).',
                   17320:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17321:                                     }));
1.942     raeburn  17322:                 } else {
1.1344    raeburn  17323:                     push(@clonemsg,({
                   17324:                                       mt => 'No new course created.',
                   17325:                                       args => [],
                   17326:                                     },
                   17327:                                     {
                   17328:                                       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]).',
                   17329:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17330:                                     }));
1.1221    raeburn  17331:                 }
1.566     albertel 17332: 	    }
1.578     raeburn  17333:         }
1.566     albertel 17334:     }
1.1344    raeburn  17335:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17336: }
                   17337: 
1.444     albertel 17338: sub construct_course {
1.1262    raeburn  17339:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17340:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17341:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17342:     my $linefeed =  '<br />'."\n";
                   17343:     if ($context eq 'auto') {
                   17344:         $linefeed = "\n";
                   17345:     }
1.566     albertel 17346: 
                   17347: #
                   17348: # Are we cloning?
                   17349: #
1.1344    raeburn  17350:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17351:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17352: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17353:         if (!$can_clone) {
1.1344    raeburn  17354: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17355: 	}
                   17356:     }
                   17357: 
1.444     albertel 17358: #
                   17359: # Open course
                   17360: #
1.1239    raeburn  17361:     my $showncrstype;
                   17362:     if ($args->{'crstype'} eq 'Placement') {
                   17363:         $showncrstype = 'placement test'; 
                   17364:     } else {  
                   17365:         $showncrstype = lc($args->{'crstype'});
                   17366:     }
1.444     albertel 17367:     my %cenv=();
                   17368:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17369:                                              $args->{'cdescr'},
                   17370:                                              $args->{'curl'},
                   17371:                                              $args->{'course_home'},
                   17372:                                              $args->{'nonstandard'},
                   17373:                                              $args->{'crscode'},
                   17374:                                              $args->{'ccuname'}.':'.
                   17375:                                              $args->{'ccdomain'},
1.882     raeburn  17376:                                              $args->{'crstype'},
1.1344    raeburn  17377:                                              $cnum,$context,$category,
                   17378:                                              $callercontext);
1.444     albertel 17379: 
                   17380:     # Note: The testing routines depend on this being output; see 
                   17381:     # Utils::Course. This needs to at least be output as a comment
                   17382:     # if anyone ever decides to not show this, and Utils::Course::new
                   17383:     # will need to be suitably modified.
1.1344    raeburn  17384:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17385:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17386:     } else {
                   17387:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17388:     }
1.943     raeburn  17389:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17390:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17391:     }
                   17392: 
1.444     albertel 17393: #
                   17394: # Check if created correctly
                   17395: #
1.479     albertel 17396:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17397:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17398:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17399:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17400:             $outcome .= &mt_user($user_lh,
                   17401:                             'Course creation failed, unrecognized course home server.');
                   17402:         } else {
                   17403:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17404:         }
                   17405:         $outcome .= $linefeed;
                   17406:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17407:     }
1.541     raeburn  17408:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17409: 
1.444     albertel 17410: #
1.566     albertel 17411: # Do the cloning
                   17412: #   
1.1344    raeburn  17413:     my @clonemsg;
1.566     albertel 17414:     if ($can_clone && $cloneid) {
1.1344    raeburn  17415:         push(@clonemsg,
                   17416:                       {
                   17417:                           mt => 'Created [_1] by cloning from [_2]',
                   17418:                           args => [$showncrstype,$clonetitle],
                   17419:                       });
1.566     albertel 17420: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17421: # Copy all files
1.1344    raeburn  17422:         my @info =
                   17423: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17424: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17425:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17426:                                                      $args->{'tinyurls'});
                   17427:         if (@info) {
                   17428:             push(@clonemsg,@info);
                   17429:         }
1.444     albertel 17430: # Restore URL
1.566     albertel 17431: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17432: # Restore title
1.566     albertel 17433: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17434: # Restore creation date, creator and creation context.
                   17435:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17436:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17437:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17438: # Mark as cloned
1.566     albertel 17439: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17440: # Need to clone grading mode
                   17441:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17442:         $cenv{'grading'}=$newenv{'grading'};
                   17443: # Do not clone these environment entries
                   17444:         &Apache::lonnet::del('environment',
                   17445:                   ['default_enrollment_start_date',
                   17446:                    'default_enrollment_end_date',
                   17447:                    'question.email',
                   17448:                    'policy.email',
                   17449:                    'comment.email',
                   17450:                    'pch.users.denied',
1.725     raeburn  17451:                    'plc.users.denied',
                   17452:                    'hidefromcat',
1.1121    raeburn  17453:                    'checkforpriv',
1.1355    raeburn  17454:                    'categories'],
1.638     www      17455:                    $$crsudom,$$crsunum);
1.1170    raeburn  17456:         if ($args->{'textbook'}) {
                   17457:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17458:         }
1.444     albertel 17459:     }
1.566     albertel 17460: 
1.444     albertel 17461: #
                   17462: # Set environment (will override cloned, if existing)
                   17463: #
                   17464:     my @sections = ();
                   17465:     my @xlists = ();
                   17466:     if ($args->{'crstype'}) {
                   17467:         $cenv{'type'}=$args->{'crstype'};
                   17468:     }
1.1371    raeburn  17469:     if ($args->{'lti'}) {
                   17470:         $cenv{'internal.lti'}=$args->{'lti'};
                   17471:     }
1.444     albertel 17472:     if ($args->{'crsid'}) {
                   17473:         $cenv{'courseid'}=$args->{'crsid'};
                   17474:     }
                   17475:     if ($args->{'crscode'}) {
                   17476:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17477:     }
                   17478:     if ($args->{'crsquota'} ne '') {
                   17479:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17480:     } else {
                   17481:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17482:     }
                   17483:     if ($args->{'ccuname'}) {
                   17484:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17485:                                         ':'.$args->{'ccdomain'};
                   17486:     } else {
                   17487:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17488:     }
1.1116    raeburn  17489:     if ($args->{'defaultcredits'}) {
                   17490:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17491:     }
1.444     albertel 17492:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17493:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17494:     if ($args->{'crssections'}) {
                   17495:         $cenv{'internal.sectionnums'} = '';
                   17496:         if ($args->{'crssections'} =~ m/,/) {
                   17497:             @sections = split/,/,$args->{'crssections'};
                   17498:         } else {
                   17499:             $sections[0] = $args->{'crssections'};
                   17500:         }
                   17501:         if (@sections > 0) {
                   17502:             foreach my $item (@sections) {
                   17503:                 my ($sec,$gp) = split/:/,$item;
                   17504:                 my $class = $args->{'crscode'}.$sec;
                   17505:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17506:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17507:                 if ($addcheck eq 'ok') {
                   17508:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17509:                         push(@oklcsecs,$gp);
                   17510:                     }
                   17511:                 } else {
1.1263    raeburn  17512:                     push(@badclasses,$class);
1.444     albertel 17513:                 }
                   17514:             }
                   17515:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17516:         }
                   17517:     }
                   17518: # do not hide course coordinator from staff listing, 
                   17519: # even if privileged
                   17520:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17521: # add course coordinator's domain to domains to check for privileged users
                   17522: # if different to course domain
                   17523:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17524:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17525:     }
1.444     albertel 17526: # add crosslistings
                   17527:     if ($args->{'crsxlist'}) {
                   17528:         $cenv{'internal.crosslistings'}='';
                   17529:         if ($args->{'crsxlist'} =~ m/,/) {
                   17530:             @xlists = split/,/,$args->{'crsxlist'};
                   17531:         } else {
                   17532:             $xlists[0] = $args->{'crsxlist'};
                   17533:         }
                   17534:         if (@xlists > 0) {
                   17535:             foreach my $item (@xlists) {
                   17536:                 my ($xl,$gp) = split/:/,$item;
                   17537:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17538:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17539:                 if ($addcheck eq 'ok') {
                   17540:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17541:                         push(@oklcsecs,$gp);
                   17542:                     }
                   17543:                 } else {
1.1263    raeburn  17544:                     push(@badclasses,$xl);
1.444     albertel 17545:                 }
                   17546:             }
                   17547:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17548:         }
                   17549:     }
                   17550:     if ($args->{'autoadds'}) {
                   17551:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17552:     }
                   17553:     if ($args->{'autodrops'}) {
                   17554:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17555:     }
                   17556: # check for notification of enrollment changes
                   17557:     my @notified = ();
                   17558:     if ($args->{'notify_owner'}) {
                   17559:         if ($args->{'ccuname'} ne '') {
                   17560:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17561:         }
                   17562:     }
                   17563:     if ($args->{'notify_dc'}) {
                   17564:         if ($uname ne '') { 
1.630     raeburn  17565:             push(@notified,$uname.':'.$udom);
1.444     albertel 17566:         }
                   17567:     }
                   17568:     if (@notified > 0) {
                   17569:         my $notifylist;
                   17570:         if (@notified > 1) {
                   17571:             $notifylist = join(',',@notified);
                   17572:         } else {
                   17573:             $notifylist = $notified[0];
                   17574:         }
                   17575:         $cenv{'internal.notifylist'} = $notifylist;
                   17576:     }
                   17577:     if (@badclasses > 0) {
                   17578:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17579:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17580:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17581:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17582:         );
1.1264    raeburn  17583:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17584:                            &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  17585:         if ($context eq 'auto') {
                   17586:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17587:         } else {
1.566     albertel 17588:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17589:         }
                   17590:         foreach my $item (@badclasses) {
1.541     raeburn  17591:             if ($context eq 'auto') {
1.1261    raeburn  17592:                 $outcome .= " - $item\n";
1.541     raeburn  17593:             } else {
1.1261    raeburn  17594:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17595:             }
1.1261    raeburn  17596:         }
                   17597:         if ($context eq 'auto') {
                   17598:             $outcome .= $linefeed;
                   17599:         } else {
                   17600:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17601:         } 
1.444     albertel 17602:     }
                   17603:     if ($args->{'no_end_date'}) {
                   17604:         $args->{'endaccess'} = 0;
                   17605:     }
1.1412    raeburn  17606: #  If an official course with institutional sections is created by cloning 
                   17607: #  an existing course, section-specific hiding of course totals in student's
                   17608: #  view of grades as copied from cloned course, will be checked for valid 
                   17609: #  sections.
                   17610:     if (($can_clone && $cloneid) &&
                   17611:         ($cenv{'internal.coursecode'} ne '') &&
                   17612:         ($cenv{'grading'} eq 'standard') &&
                   17613:         ($cenv{'hidetotals'} ne '') &&
                   17614:         ($cenv{'hidetotals'} ne 'all')) {
                   17615:         my @hidesecs;
                   17616:         my $deletehidetotals;
                   17617:         if (@oklcsecs) {
                   17618:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17619:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17620:                     push(@hidesecs,$sec);
                   17621:                 }
                   17622:             }
                   17623:             if (@hidesecs) {
                   17624:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17625:             } else {
                   17626:                 $deletehidetotals = 1;
                   17627:             }
                   17628:         } else {
                   17629:             $deletehidetotals = 1;
                   17630:         }
                   17631:         if ($deletehidetotals) {
                   17632:             delete($cenv{'hidetotals'});
                   17633:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17634:         }
                   17635:     }
1.444     albertel 17636:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17637:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17638:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17639:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17640:     if ($args->{'showphotos'}) {
                   17641:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17642:     }
                   17643:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17644:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17645:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17646:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17647:             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'); 
                   17648:             if ($context eq 'auto') {
                   17649:                 $outcome .= $krb_msg;
                   17650:             } else {
1.566     albertel 17651:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17652:             }
                   17653:             $outcome .= $linefeed;
1.444     albertel 17654:         }
                   17655:     }
                   17656:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17657:        if ($args->{'setpolicy'}) {
                   17658:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17659:        }
                   17660:        if ($args->{'setcontent'}) {
                   17661:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17662:        }
1.1251    raeburn  17663:        if ($args->{'setcomment'}) {
                   17664:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17665:        }
1.444     albertel 17666:     }
                   17667:     if ($args->{'reshome'}) {
                   17668: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17669: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17670:     }
                   17671: #
                   17672: # course has keyed access
                   17673: #
                   17674:     if ($args->{'setkeys'}) {
                   17675:        $cenv{'keyaccess'}='yes';
                   17676:     }
                   17677: # if specified, key authority is not course, but user
                   17678: # only active if keyaccess is yes
                   17679:     if ($args->{'keyauth'}) {
1.487     albertel 17680: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17681: 	$user = &LONCAPA::clean_username($user);
                   17682: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17683: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17684: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17685: 	}
                   17686:     }
                   17687: 
1.1166    raeburn  17688: #
1.1167    raeburn  17689: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17690: #
                   17691:     if ($args->{'uniquecode'}) {
                   17692:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17693:         if ($code) {
                   17694:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17695:             my %crsinfo =
                   17696:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17697:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17698:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17699:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17700:             } 
1.1166    raeburn  17701:             if (ref($coderef)) {
                   17702:                 $$coderef = $code;
                   17703:             }
                   17704:         }
                   17705:     }
                   17706: 
1.444     albertel 17707:     if ($args->{'disresdis'}) {
                   17708:         $cenv{'pch.roles.denied'}='st';
                   17709:     }
                   17710:     if ($args->{'disablechat'}) {
                   17711:         $cenv{'plc.roles.denied'}='st';
                   17712:     }
                   17713: 
                   17714:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17715:     # course
                   17716:     $cenv{'course.helper.not.run'} = 1;
                   17717:     #
                   17718:     # Use new Randomseed
                   17719:     #
                   17720:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17721:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17722:     #
                   17723:     # The encryption code and receipt prefix for this course
                   17724:     #
                   17725:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17726:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17727:     #
                   17728:     # By default, use standard grading
                   17729:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17730: 
1.541     raeburn  17731:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17732:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17733: #
                   17734: # Open all assignments
                   17735: #
                   17736:     if ($args->{'openall'}) {
1.1341    raeburn  17737:        my $opendate = time;
                   17738:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17739:            $opendate = $args->{'openallfrom'};
                   17740:        }
1.444     albertel 17741:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17742:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17743:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17744:        $outcome .= &mt('All assignments open starting [_1]',
                   17745:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17746:                    &Apache::lonnet::cput
                   17747:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17748:    }
                   17749: #
                   17750: # Set first page
                   17751: #
                   17752:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17753: 	    || ($cloneid)) {
                   17754: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17755: 
                   17756: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17757:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17758: 
1.444     albertel 17759:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17760:         my $title; my $url;
                   17761:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17762: 	    $title=&mt('Syllabus');
1.444     albertel 17763:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17764:         } else {
1.963     raeburn  17765:             $title=&mt('Table of Contents');
1.444     albertel 17766:             $url='/adm/navmaps';
                   17767:         }
1.445     albertel 17768: 
                   17769:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17770: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17771: 
                   17772: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17773:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17774:     }
1.566     albertel 17775: 
1.1237    raeburn  17776: # 
                   17777: # Set params for Placement Tests
                   17778: #
1.1239    raeburn  17779:     if ($args->{'crstype'} eq 'Placement') {
                   17780:        my %storecontent; 
                   17781:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17782:        my %defaults = (
                   17783:                         buttonshide   => { value => 'yes',
                   17784:                                            type => 'string_yesno',},
                   17785:                         type          => { value => 'randomizetry',
                   17786:                                            type  => 'string_questiontype',},
                   17787:                         maxtries      => { value => 1,
                   17788:                                            type => 'int_pos',},
                   17789:                         problemstatus => { value => 'no',
                   17790:                                            type  => 'string_problemstatus',},
                   17791:                       );
                   17792:        foreach my $key (keys(%defaults)) {
                   17793:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17794:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17795:        }
1.1237    raeburn  17796:        &Apache::lonnet::cput
                   17797:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17798:     }
                   17799: 
1.1344    raeburn  17800:     return (1,$outcome,\@clonemsg);
1.444     albertel 17801: }
                   17802: 
1.1166    raeburn  17803: sub make_unique_code {
                   17804:     my ($cdom,$cnum) = @_;
                   17805:     # get lock on uniquecodes db
                   17806:     my $lockhash = {
                   17807:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17808:                                                   ':'.$env{'user.domain'},
                   17809:                    };
                   17810:     my $tries = 0;
                   17811:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17812:     my ($code,$error);
                   17813:   
                   17814:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17815:         $tries ++;
                   17816:         sleep 1;
                   17817:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17818:     }
                   17819:     if ($gotlock eq 'ok') {
                   17820:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17821:         my $gotcode;
                   17822:         my $attempts = 0;
                   17823:         while ((!$gotcode) && ($attempts < 100)) {
                   17824:             $code = &generate_code();
                   17825:             if (!exists($currcodes{$code})) {
                   17826:                 $gotcode = 1;
                   17827:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17828:                     $error = 'nostore';
                   17829:                 }
                   17830:             }
                   17831:             $attempts ++;
                   17832:         }
                   17833:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17834:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17835:     } else {
                   17836:         $error = 'nolock';
                   17837:     }
                   17838:     return ($code,$error);
                   17839: }
                   17840: 
                   17841: sub generate_code {
                   17842:     my $code;
                   17843:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17844:     for (my $i=0; $i<6; $i++) {
                   17845:         my $lettnum = int (rand 2);
                   17846:         my $item = '';
                   17847:         if ($lettnum) {
                   17848:             $item = $letts[int( rand(18) )];
                   17849:         } else {
                   17850:             $item = 1+int( rand(8) );
                   17851:         }
                   17852:         $code .= $item;
                   17853:     }
                   17854:     return $code;
                   17855: }
                   17856: 
1.444     albertel 17857: ############################################################
                   17858: ############################################################
                   17859: 
1.1237    raeburn  17860: # Community, Course and Placement Test
1.378     raeburn  17861: sub course_type {
                   17862:     my ($cid) = @_;
                   17863:     if (!defined($cid)) {
                   17864:         $cid = $env{'request.course.id'};
                   17865:     }
1.404     albertel 17866:     if (defined($env{'course.'.$cid.'.type'})) {
                   17867:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17868:     } else {
                   17869:         return 'Course';
1.377     raeburn  17870:     }
                   17871: }
1.156     albertel 17872: 
1.406     raeburn  17873: sub group_term {
                   17874:     my $crstype = &course_type();
                   17875:     my %names = (
                   17876:                   'Course' => 'group',
1.865     raeburn  17877:                   'Community' => 'group',
1.1237    raeburn  17878:                   'Placement' => 'group',
1.406     raeburn  17879:                 );
                   17880:     return $names{$crstype};
                   17881: }
                   17882: 
1.902     raeburn  17883: sub course_types {
1.1310    raeburn  17884:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17885:     my %typename = (
                   17886:                          official   => 'Official course',
                   17887:                          unofficial => 'Unofficial course',
                   17888:                          community  => 'Community',
1.1165    raeburn  17889:                          textbook   => 'Textbook course',
1.1237    raeburn  17890:                          placement  => 'Placement test',
1.1310    raeburn  17891:                          lti        => 'LTI provider',
1.902     raeburn  17892:                    );
                   17893:     return (\@types,\%typename);
                   17894: }
                   17895: 
1.156     albertel 17896: sub icon {
                   17897:     my ($file)=@_;
1.505     albertel 17898:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17899:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17900:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17901:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17902: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17903: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17904: 	            $curfext.".gif") {
                   17905: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17906: 		$curfext.".gif";
                   17907: 	}
                   17908:     }
1.249     albertel 17909:     return &lonhttpdurl($iconname);
1.154     albertel 17910: } 
1.84      albertel 17911: 
1.575     albertel 17912: sub lonhttpdurl {
1.692     www      17913: #
                   17914: # Had been used for "small fry" static images on separate port 8080.
                   17915: # Modify here if lightweight http functionality desired again.
                   17916: # Currently eliminated due to increasing firewall issues.
                   17917: #
1.575     albertel 17918:     my ($url)=@_;
1.692     www      17919:     return $url;
1.215     albertel 17920: }
                   17921: 
1.213     albertel 17922: sub connection_aborted {
                   17923:     my ($r)=@_;
                   17924:     $r->print(" ");$r->rflush();
                   17925:     my $c = $r->connection;
                   17926:     return $c->aborted();
                   17927: }
                   17928: 
1.221     foxr     17929: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17930: #    strings as 'strings'.
                   17931: sub escape_single {
1.221     foxr     17932:     my ($input) = @_;
1.223     albertel 17933:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17934:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17935:     return $input;
                   17936: }
1.223     albertel 17937: 
1.222     foxr     17938: #  Same as escape_single, but escape's "'s  This 
                   17939: #  can be used for  "strings"
                   17940: sub escape_double {
                   17941:     my ($input) = @_;
                   17942:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17943:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17944:     return $input;
                   17945: }
1.223     albertel 17946:  
1.222     foxr     17947: #   Escapes the last element of a full URL.
                   17948: sub escape_url {
                   17949:     my ($url)   = @_;
1.238     raeburn  17950:     my @urlslices = split(/\//, $url,-1);
1.369     www      17951:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17952:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17953: }
1.462     albertel 17954: 
1.820     raeburn  17955: sub compare_arrays {
                   17956:     my ($arrayref1,$arrayref2) = @_;
                   17957:     my (@difference,%count);
                   17958:     @difference = ();
                   17959:     %count = ();
                   17960:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17961:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17962:         foreach my $element (keys(%count)) {
                   17963:             if ($count{$element} == 1) {
                   17964:                 push(@difference,$element);
                   17965:             }
                   17966:         }
                   17967:     }
                   17968:     return @difference;
                   17969: }
                   17970: 
1.1322    raeburn  17971: sub lon_status_items {
                   17972:     my %defaults = (
                   17973:                      E         => 100,
                   17974:                      W         => 4,
                   17975:                      N         => 1,
1.1324    raeburn  17976:                      U         => 5,
1.1322    raeburn  17977:                      threshold => 200,
                   17978:                      sysmail   => 2500,
                   17979:                    );
                   17980:     my %names = (
                   17981:                    E => 'Errors',
                   17982:                    W => 'Warnings',
                   17983:                    N => 'Notices',
1.1324    raeburn  17984:                    U => 'Unsent',
1.1322    raeburn  17985:                 );
                   17986:     return (\%defaults,\%names);
                   17987: }
                   17988: 
1.817     bisitz   17989: # -------------------------------------------------------- Initialize user login
1.462     albertel 17990: sub init_user_environment {
1.463     albertel 17991:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17992:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17993: 
                   17994:     my $public=($username eq 'public' && $domain eq 'public');
                   17995: 
1.1415    raeburn  17996:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17997:         $coauthorenv);
1.462     albertel 17998:     my $now=time;
                   17999: 
                   18000:     if ($public) {
                   18001: 	my $max_public=100;
                   18002: 	my $oldest;
                   18003: 	my $oldest_time=0;
                   18004: 	for(my $next=1;$next<=$max_public;$next++) {
                   18005: 	    if (-e $lonids."/publicuser_$next.id") {
                   18006: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   18007: 		if ($mtime<$oldest_time || !$oldest_time) {
                   18008: 		    $oldest_time=$mtime;
                   18009: 		    $oldest=$next;
                   18010: 		}
                   18011: 	    } else {
                   18012: 		$cookie="publicuser_$next";
                   18013: 		last;
                   18014: 	    }
                   18015: 	}
                   18016: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   18017:     } else {
1.1275    raeburn  18018: 	# See if old ID present, if so, remove if this isn't a robot,
                   18019: 	# killing any existing non-robot sessions
1.463     albertel 18020: 	if (!$args->{'robot'}) {
                   18021: 	    opendir(DIR,$lonids);
                   18022: 	    while ($filename=readdir(DIR)) {
                   18023: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  18024:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   18025:                             &GDBM_READER(),0640)) {
1.1295    raeburn  18026:                         my $linkedfile;
1.1320    raeburn  18027:                         if (exists($oldenv{'user.linkedenv'})) {
                   18028:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  18029:                         }
1.1320    raeburn  18030:                         untie(%oldenv);
                   18031:                         if (unlink("$lonids/$filename")) {
                   18032:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   18033:                                 if (-l "$lonids/$linkedfile.id") {
                   18034:                                     unlink("$lonids/$linkedfile.id");
                   18035:                                 }
1.1295    raeburn  18036:                             }
                   18037:                         }
                   18038:                     } else {
                   18039:                         unlink($lonids.'/'.$filename);
                   18040:                     }
1.463     albertel 18041: 		}
1.462     albertel 18042: 	    }
1.463     albertel 18043: 	    closedir(DIR);
1.1204    raeburn  18044: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18045:             my $namespace = 'nohist_courseeditor';
                   18046:             my $lockingkey = 'paste'."\0".'locked_num';
                   18047:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18048:                                                 $domain,$username);
                   18049:             if (exists($lockhash{$lockingkey})) {
                   18050:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18051:                 unless ($delresult eq 'ok') {
                   18052:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18053:                 }
                   18054:             }
1.462     albertel 18055: 	}
                   18056: # Give them a new cookie
1.463     albertel 18057: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18058: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18059: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18060:     
                   18061: # Initialize roles
                   18062: 
1.1414    raeburn  18063: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18064:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18065:     }
                   18066: # ------------------------------------ Check browser type and MathML capability
                   18067: 
1.1194    raeburn  18068:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18069:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18070: 
                   18071: # ------------------------------------------------------------- Get environment
                   18072: 
                   18073:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18074:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18075:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18076: 	undef(%userenv);
                   18077:     }
                   18078:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18079: 	$form->{'interface'}=$userenv{'interface'};
                   18080:     }
                   18081:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18082: 
                   18083: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18084:     foreach my $option ('interface','localpath','localres') {
                   18085:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18086:     }
                   18087: # --------------------------------------------------------- Write first profile
                   18088: 
                   18089:     {
1.1350    raeburn  18090:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18091: 	my %initial_env = 
                   18092: 	    ("user.name"          => $username,
                   18093: 	     "user.domain"        => $domain,
                   18094: 	     "user.home"          => $authhost,
                   18095: 	     "browser.type"       => $clientbrowser,
                   18096: 	     "browser.version"    => $clientversion,
                   18097: 	     "browser.mathml"     => $clientmathml,
                   18098: 	     "browser.unicode"    => $clientunicode,
                   18099: 	     "browser.os"         => $clientos,
1.1137    raeburn  18100:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18101:              "browser.info"       => $clientinfo,
1.1194    raeburn  18102:              "browser.osversion"  => $clientosversion,
1.462     albertel 18103: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18104: 	     "request.course.fn"  => '',
                   18105: 	     "request.course.uri" => '',
                   18106: 	     "request.course.sec" => '',
                   18107: 	     "request.role"       => 'cm',
                   18108: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18109: 	     "request.host"       => $ip,);
1.462     albertel 18110: 
                   18111:         if ($form->{'localpath'}) {
                   18112: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18113: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18114:         }
                   18115: 	
                   18116: 	if ($form->{'interface'}) {
                   18117: 	    $form->{'interface'}=~s/\W//gs;
                   18118: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18119: 	    $env{'browser.interface'}=$form->{'interface'};
                   18120: 	}
                   18121: 
1.1157    raeburn  18122:         if ($form->{'iptoken'}) {
                   18123:             my $lonhost = $r->dir_config('lonHostID');
                   18124:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18125:             $env{'user.noloadbalance'} = $lonhost;
                   18126:         }
                   18127: 
1.1268    raeburn  18128:         if ($form->{'noloadbalance'}) {
                   18129:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18130:             my $hosthere = $form->{'noloadbalance'};
                   18131:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18132:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18133:                 $env{'user.noloadbalance'} = $hosthere;
                   18134:             }
                   18135:         }
                   18136: 
1.1016    raeburn  18137:         unless ($domain eq 'public') {
1.1273    raeburn  18138:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18139:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18140: 
1.1414    raeburn  18141:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18142:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18143:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18144:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18145:             }
1.980     raeburn  18146: 
1.1311    raeburn  18147:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18148:                 $userenv{'canrequest.'.$crstype} =
                   18149:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18150:                                                       'reload','requestcourses',
                   18151:                                                       \%userenv,\%domdef,\%is_adv);
                   18152:             }
1.724     raeburn  18153: 
1.1418    raeburn  18154:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18155:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18156:                 if ($userenv{'authoreditors'}) {
                   18157:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18158:                 } elsif ($domdef{'editors'} ne '') {
                   18159:                     $userenv{'editors'} = $domdef{'editors'};
                   18160:                 } else {
                   18161:                     $userenv{'editors'} = 'edit,xml';
                   18162:                 }
1.1431    raeburn  18163:                 if ($userenv{'authorarchive'}) {
                   18164:                     $userenv{'canarchive'} = 1;
                   18165:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18166:                          ($domdef{'archive'})) {
                   18167:                     $userenv{'canarchive'} = 1;
                   18168:                 }
1.1418    raeburn  18169:             }
                   18170: 
1.1273    raeburn  18171:             $userenv{'canrequest.author'} =
                   18172:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18173:                                                   'reload','requestauthor',
1.980     raeburn  18174:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18175:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18176:                                                  $domain,$username);
                   18177:             my $reqstatus = $reqauthor{'author_status'};
                   18178:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18179:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18180:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18181:                                                       $reqauthor{'author'}{'timestamp'};
                   18182:                 }
1.1092    raeburn  18183:             }
1.1287    raeburn  18184:             my ($types,$typename) = &course_types();
                   18185:             if (ref($types) eq 'ARRAY') {
                   18186:                 my @options = ('approval','validate','autolimit');
                   18187:                 my $optregex = join('|',@options);
                   18188:                 my (%willtrust,%trustchecked);
                   18189:                 foreach my $type (@{$types}) {
                   18190:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18191:                     if ($dom_str ne '') {
                   18192:                         my $updatedstr = '';
                   18193:                         my @possdomains = split(',',$dom_str);
                   18194:                         foreach my $entry (@possdomains) {
                   18195:                             my ($extdom,$extopt) = split(':',$entry);
                   18196:                             unless ($trustchecked{$extdom}) {
                   18197:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18198:                                 $trustchecked{$extdom} = 1;
                   18199:                             }
                   18200:                             if ($willtrust{$extdom}) {
                   18201:                                 $updatedstr .= $entry.',';
                   18202:                             }
                   18203:                         }
                   18204:                         $updatedstr =~ s/,$//;
                   18205:                         if ($updatedstr) {
                   18206:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18207:                         } else {
                   18208:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18209:                         }
                   18210:                     }
                   18211:                 }
                   18212:             }
1.1092    raeburn  18213:         }
1.462     albertel 18214: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18215: 
1.462     albertel 18216: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18217: 		 &GDBM_WRCREAT(),0640)) {
                   18218: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18219: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18220: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18221:             if (ref($firstaccenv) eq 'HASH') {
                   18222:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18223:             }
                   18224:             if (ref($timerintenv) eq 'HASH') {
                   18225:                 &_add_to_env(\%disk_env,$timerintenv);
                   18226:             }
1.1414    raeburn  18227:             if (ref($coauthorenv) eq 'HASH') {
                   18228:                 if (keys(%{$coauthorenv})) {
                   18229:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18230:                 }
                   18231:             }
1.463     albertel 18232: 	    if (ref($args->{'extra_env'})) {
                   18233: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18234: 	    }
1.462     albertel 18235: 	    untie(%disk_env);
                   18236: 	} else {
1.705     tempelho 18237: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18238: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18239: 	    return 'error: '.$!;
                   18240: 	}
                   18241:     }
                   18242:     $env{'request.role'}='cm';
                   18243:     $env{'request.role.adv'}=$env{'user.adv'};
                   18244:     $env{'browser.type'}=$clientbrowser;
                   18245: 
                   18246:     return $cookie;
                   18247: 
                   18248: }
                   18249: 
                   18250: sub _add_to_env {
                   18251:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18252:     if (ref($env_data) eq 'HASH') {
                   18253:         while (my ($key,$value) = each(%$env_data)) {
                   18254: 	    $idf->{$prefix.$key} = $value;
                   18255: 	    $env{$prefix.$key}   = $value;
                   18256:         }
1.462     albertel 18257:     }
                   18258: }
                   18259: 
1.685     tempelho 18260: # --- Get the symbolic name of a problem and the url
                   18261: sub get_symb {
                   18262:     my ($request,$silent) = @_;
1.726     raeburn  18263:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18264:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18265:     if ($symb eq '') {
                   18266:         if (!$silent) {
1.1071    raeburn  18267:             if (ref($request)) { 
                   18268:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18269:             }
1.685     tempelho 18270:             return ();
                   18271:         }
                   18272:     }
                   18273:     &Apache::lonenc::check_decrypt(\$symb);
                   18274:     return ($symb);
                   18275: }
                   18276: 
                   18277: # --------------------------------------------------------------Get annotation
                   18278: 
                   18279: sub get_annotation {
                   18280:     my ($symb,$enc) = @_;
                   18281: 
                   18282:     my $key = $symb;
                   18283:     if (!$enc) {
                   18284:         $key =
                   18285:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18286:     }
                   18287:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18288:     return $annotation{$key};
                   18289: }
                   18290: 
                   18291: sub clean_symb {
1.731     raeburn  18292:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18293: 
                   18294:     &Apache::lonenc::check_decrypt(\$symb);
                   18295:     my $enc = $env{'request.enc'};
1.731     raeburn  18296:     if ($delete_enc) {
1.730     raeburn  18297:         delete($env{'request.enc'});
                   18298:     }
1.685     tempelho 18299: 
                   18300:     return ($symb,$enc);
                   18301: }
1.462     albertel 18302: 
1.1181    raeburn  18303: ############################################################
                   18304: ############################################################
                   18305: 
                   18306: =pod
                   18307: 
                   18308: =head1 Routines for building display used to search for courses
                   18309: 
                   18310: 
                   18311: =over 4
                   18312: 
                   18313: =item * &build_filters()
                   18314: 
                   18315: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18316: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18317: and quotacheck.pl
                   18318: 
1.1181    raeburn  18319: 
                   18320: Inputs:
                   18321: 
                   18322: filterlist - anonymous array of fields to include as potential filters 
                   18323: 
                   18324: crstype - course type
                   18325: 
                   18326: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18327:               to pop-open a course selector (will contain "extra element"). 
                   18328: 
                   18329: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18330: 
                   18331: filter - anonymous hash of criteria and their values
                   18332: 
                   18333: action - form action
                   18334: 
                   18335: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18336: 
1.1182    raeburn  18337: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18338: 
                   18339: cloneruname - username of owner of new course who wants to clone
                   18340: 
                   18341: clonerudom - domain of owner of new course who wants to clone
                   18342: 
                   18343: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18344: 
                   18345: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18346: 
                   18347: codedom - domain
                   18348: 
                   18349: formname - value of form element named "form". 
                   18350: 
                   18351: fixeddom - domain, if fixed.
                   18352: 
                   18353: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18354: 
                   18355: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18356: 
                   18357: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18358: 
                   18359: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18360: 
                   18361: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18362: 
                   18363: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18364: 
                   18365: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18366: 
1.1182    raeburn  18367: 
1.1181    raeburn  18368: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18369: 
1.1182    raeburn  18370: 
1.1181    raeburn  18371: Side Effects: None
                   18372: 
                   18373: =cut
                   18374: 
                   18375: # ---------------------------------------------- search for courses based on last activity etc.
                   18376: 
                   18377: sub build_filters {
                   18378:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18379:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18380:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18381:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18382:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18383:     my ($list,$jscript);
1.1181    raeburn  18384:     my $onchange = 'javascript:updateFilters(this)';
                   18385:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18386:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18387:         $typeselectform,$instcodetitle);
                   18388:     if ($formname eq '') {
                   18389:         $formname = $caller;
                   18390:     }
                   18391:     foreach my $item (@{$filterlist}) {
                   18392:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18393:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18394:             if ($item eq 'domainfilter') {
                   18395:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18396:             } elsif ($item eq 'coursefilter') {
                   18397:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18398:             } elsif ($item eq 'ownerfilter') {
                   18399:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18400:             } elsif ($item eq 'ownerdomfilter') {
                   18401:                 $filter->{'ownerdomfilter'} =
                   18402:                     &LONCAPA::clean_domain($filter->{$item});
                   18403:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18404:                                                        'ownerdomfilter',1);
                   18405:             } elsif ($item eq 'personfilter') {
                   18406:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18407:             } elsif ($item eq 'persondomfilter') {
                   18408:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18409:                                                         'persondomfilter',1);
                   18410:             } else {
                   18411:                 $filter->{$item} =~ s/\W//g;
                   18412:             }
                   18413:             if (!$filter->{$item}) {
                   18414:                 $filter->{$item} = '';
                   18415:             }
                   18416:         }
                   18417:         if ($item eq 'domainfilter') {
                   18418:             my $allow_blank = 1;
                   18419:             if ($formname eq 'portform') {
                   18420:                 $allow_blank=0;
                   18421:             } elsif ($formname eq 'studentform') {
                   18422:                 $allow_blank=0;
                   18423:             }
                   18424:             if ($fixeddom) {
                   18425:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18426:                                     ' value="'.$codedom.'" />'.
                   18427:                                     &Apache::lonnet::domain($codedom,'description');
                   18428:             } else {
                   18429:                 $domainselectform = &select_dom_form($filter->{$item},
                   18430:                                                      'domainfilter',
                   18431:                                                       $allow_blank,'',$onchange);
                   18432:             }
                   18433:         } else {
                   18434:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18435:         }
                   18436:     }
                   18437: 
                   18438:     # last course activity filter and selection
                   18439:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18440: 
                   18441:     # course created filter and selection
                   18442:     if (exists($filter->{'createdfilter'})) {
                   18443:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18444:     }
                   18445: 
1.1239    raeburn  18446:     my $prefix = $crstype;
                   18447:     if ($crstype eq 'Placement') {
                   18448:         $prefix = 'Placement Test'
                   18449:     }
1.1181    raeburn  18450:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18451:                 'cac' => "$prefix Activity",
                   18452:                 'ccr' => "$prefix Created",
                   18453:                 'cde' => "$prefix Title",
                   18454:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18455:                 'ins' => 'Institutional Code',
                   18456:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18457:                 'cow' => "$prefix Owner/Co-owner",
                   18458:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18459:                 'cog' => 'Type',
                   18460:              );
                   18461: 
                   18462:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18463:         my $typeval = 'Course';
                   18464:         if ($crstype eq 'Community') {
                   18465:             $typeval = 'Community';
1.1239    raeburn  18466:         } elsif ($crstype eq 'Placement') {
                   18467:             $typeval = 'Placement';
1.1181    raeburn  18468:         }
                   18469:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18470:     } else {
                   18471:         $typeselectform =  '<select name="type" size="1"';
                   18472:         if ($onchange) {
                   18473:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18474:         }
                   18475:         $typeselectform .= '>'."\n";
1.1237    raeburn  18476:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18477:             my $shown;
                   18478:             if ($posstype eq 'Placement') {
                   18479:                 $shown = &mt('Placement Test');
                   18480:             } else {
                   18481:                 $shown = &mt($posstype);
                   18482:             }
1.1181    raeburn  18483:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18484:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18485:         }
                   18486:         $typeselectform.="</select>";
                   18487:     }
                   18488: 
                   18489:     my ($cloneableonlyform,$cloneabletitle);
                   18490:     if (exists($filter->{'cloneableonly'})) {
                   18491:         my $cloneableon = '';
                   18492:         my $cloneableoff = ' checked="checked"';
                   18493:         if ($filter->{'cloneableonly'}) {
                   18494:             $cloneableon = $cloneableoff;
                   18495:             $cloneableoff = '';
                   18496:         }
                   18497:         $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>';
                   18498:         if ($formname eq 'ccrs') {
1.1187    bisitz   18499:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18500:         } else {
                   18501:             $cloneabletitle = &mt('Cloneable by you');
                   18502:         }
                   18503:     }
                   18504:     my $officialjs;
                   18505:     if ($crstype eq 'Course') {
                   18506:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18507: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18508: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18509:             if ($codedom) { 
1.1181    raeburn  18510:                 $officialjs = 1;
                   18511:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18512:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18513:                                                                   $officialjs,$codetitlesref);
                   18514:                 if ($jscript) {
1.1182    raeburn  18515:                     $jscript = '<script type="text/javascript">'."\n".
                   18516:                                '// <![CDATA['."\n".
                   18517:                                $jscript."\n".
                   18518:                                '// ]]>'."\n".
                   18519:                                '</script>'."\n";
1.1181    raeburn  18520:                 }
                   18521:             }
                   18522:             if ($instcodeform eq '') {
                   18523:                 $instcodeform =
                   18524:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18525:                     $list->{'instcodefilter'}.'" />';
                   18526:                 $instcodetitle = $lt{'ins'};
                   18527:             } else {
                   18528:                 $instcodetitle = $lt{'inc'};
                   18529:             }
                   18530:             if ($fixeddom) {
                   18531:                 $instcodetitle .= '<br />('.$codedom.')';
                   18532:             }
                   18533:         }
                   18534:     }
                   18535:     my $output = qq|
                   18536: <form method="post" name="filterpicker" action="$action">
                   18537: <input type="hidden" name="form" value="$formname" />
                   18538: |;
                   18539:     if ($formname eq 'modifycourse') {
                   18540:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18541:                    '<input type="hidden" name="prevphase" value="'.
                   18542:                    $prevphase.'" />'."\n";
1.1198    musolffc 18543:     } elsif ($formname eq 'quotacheck') {
                   18544:         $output .= qq|
                   18545: <input type="hidden" name="sortby" value="" />
                   18546: <input type="hidden" name="sortorder" value="" />
                   18547: |;
                   18548:     } else {
1.1181    raeburn  18549:         my $name_input;
                   18550:         if ($cnameelement ne '') {
                   18551:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18552:                           $cnameelement.'" />';
                   18553:         }
                   18554:         $output .= qq|
1.1182    raeburn  18555: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18556: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18557: $name_input
                   18558: $roleelement
                   18559: $multelement
                   18560: $typeelement
                   18561: |;
                   18562:         if ($formname eq 'portform') {
                   18563:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18564:         }
                   18565:     }
                   18566:     if ($fixeddom) {
                   18567:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18568:     }
                   18569:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18570:     if ($sincefilterform) {
                   18571:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18572:                   .$sincefilterform
                   18573:                   .&Apache::lonhtmlcommon::row_closure();
                   18574:     }
                   18575:     if ($createdfilterform) {
                   18576:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18577:                   .$createdfilterform
                   18578:                   .&Apache::lonhtmlcommon::row_closure();
                   18579:     }
                   18580:     if ($domainselectform) {
                   18581:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18582:                   .$domainselectform
                   18583:                   .&Apache::lonhtmlcommon::row_closure();
                   18584:     }
                   18585:     if ($typeselectform) {
                   18586:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18587:             $output .= $typeselectform;
                   18588:         } else {
                   18589:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18590:                       .$typeselectform
                   18591:                       .&Apache::lonhtmlcommon::row_closure();
                   18592:         }
                   18593:     }
                   18594:     if ($instcodeform) {
                   18595:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18596:                   .$instcodeform
                   18597:                   .&Apache::lonhtmlcommon::row_closure();
                   18598:     }
                   18599:     if (exists($filter->{'ownerfilter'})) {
                   18600:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18601:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18602:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18603:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18604:                    $ownerdomselectform.'</td></tr></table>'.
                   18605:                    &Apache::lonhtmlcommon::row_closure();
                   18606:     }
                   18607:     if (exists($filter->{'personfilter'})) {
                   18608:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18609:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18610:                    '<input type="text" name="personfilter" size="20" value="'.
                   18611:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18612:                    $persondomselectform.'</td></tr></table>'.
                   18613:                    &Apache::lonhtmlcommon::row_closure();
                   18614:     }
                   18615:     if (exists($filter->{'coursefilter'})) {
                   18616:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18617:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18618:                   .$list->{'coursefilter'}.'" />'
                   18619:                   .&Apache::lonhtmlcommon::row_closure();
                   18620:     }
                   18621:     if ($cloneableonlyform) {
                   18622:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18623:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18624:     }
                   18625:     if (exists($filter->{'descriptfilter'})) {
                   18626:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18627:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18628:                   .$list->{'descriptfilter'}.'" />'
                   18629:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18630:     }
                   18631:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18632:                '<input type="hidden" name="updater" value="" />'."\n".
                   18633:                '<input type="submit" name="gosearch" value="'.
                   18634:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18635:     return $jscript.$clonewarning.$output;
                   18636: }
                   18637: 
                   18638: =pod 
                   18639: 
                   18640: =item * &timebased_select_form()
                   18641: 
1.1182    raeburn  18642: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18643: filter e.g., Course Activity, Course Created, when searching for courses
                   18644: or communities
                   18645: 
                   18646: Inputs:
                   18647: 
                   18648: item - name of form element (sincefilter or createdfilter)
                   18649: 
                   18650: filter - anonymous hash of criteria and their values
                   18651: 
                   18652: Returns: HTML for a select box contained a blank, then six time selections,
                   18653:          with value set in incoming form variables currently selected. 
                   18654: 
                   18655: Side Effects: None
                   18656: 
                   18657: =cut
                   18658: 
                   18659: sub timebased_select_form {
                   18660:     my ($item,$filter) = @_;
                   18661:     if (ref($filter) eq 'HASH') {
                   18662:         $filter->{$item} =~ s/[^\d-]//g;
                   18663:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18664:         return &select_form(
                   18665:                             $filter->{$item},
                   18666:                             $item,
                   18667:                             {      '-1' => '',
                   18668:                                 '86400' => &mt('today'),
                   18669:                                '604800' => &mt('last week'),
                   18670:                               '2592000' => &mt('last month'),
                   18671:                               '7776000' => &mt('last three months'),
                   18672:                              '15552000' => &mt('last six months'),
                   18673:                              '31104000' => &mt('last year'),
                   18674:                     'select_form_order' =>
                   18675:                            ['-1','86400','604800','2592000','7776000',
                   18676:                             '15552000','31104000']});
                   18677:     }
                   18678: }
                   18679: 
                   18680: =pod
                   18681: 
                   18682: =item * &js_changer()
                   18683: 
                   18684: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18685: when course type or domain is changed, and also to hide 'Searching ...' on
                   18686: page load completion for page showing search result.
1.1181    raeburn  18687: 
                   18688: Inputs: None
                   18689: 
1.1183    raeburn  18690: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18691: 
                   18692: Side Effects: None
                   18693: 
                   18694: =cut
                   18695: 
                   18696: sub js_changer {
                   18697:     return <<ENDJS;
                   18698: <script type="text/javascript">
                   18699: // <![CDATA[
                   18700: function updateFilters(caller) {
                   18701:     if (typeof(caller) != "undefined") {
                   18702:         document.filterpicker.updater.value = caller.name;
                   18703:     }
                   18704:     document.filterpicker.submit();
                   18705: }
1.1183    raeburn  18706: 
                   18707: function hideSearching() {
                   18708:     if (document.getElementById('searching')) {
                   18709:         document.getElementById('searching').style.display = 'none';
                   18710:     }
                   18711:     return;
                   18712: }
                   18713: 
1.1181    raeburn  18714: // ]]>
                   18715: </script>
                   18716: 
                   18717: ENDJS
                   18718: }
                   18719: 
                   18720: =pod
                   18721: 
1.1182    raeburn  18722: =item * &search_courses()
                   18723: 
                   18724: Process selected filters form course search form and pass to lonnet::courseiddump
                   18725: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18726: 
                   18727: Inputs:
                   18728: 
                   18729: dom - domain being searched 
                   18730: 
                   18731: type - course type ('Course' or 'Community' or '.' if any).
                   18732: 
                   18733: filter - anonymous hash of criteria and their values
                   18734: 
                   18735: numtitles - for institutional codes - number of categories
                   18736: 
                   18737: cloneruname - optional username of new course owner
                   18738: 
                   18739: clonerudom - optional domain of new course owner
                   18740: 
1.1221    raeburn  18741: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18742:             (used when DC is using course creation form)
                   18743: 
                   18744: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18745: 
1.1221    raeburn  18746: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18747:            (and so can clone automatically)
                   18748: 
                   18749: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18750: 
                   18751: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18752:               courses to clone 
1.1182    raeburn  18753: 
                   18754: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18755: 
                   18756: 
                   18757: Side Effects: None
                   18758: 
                   18759: =cut
                   18760: 
                   18761: 
                   18762: sub search_courses {
1.1221    raeburn  18763:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18764:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18765:     my (%courses,%showcourses,$cloner);
                   18766:     if (($filter->{'ownerfilter'} ne '') ||
                   18767:         ($filter->{'ownerdomfilter'} ne '')) {
                   18768:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18769:                                        $filter->{'ownerdomfilter'};
                   18770:     }
                   18771:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18772:         if (!$filter->{$item}) {
                   18773:             $filter->{$item}='.';
                   18774:         }
                   18775:     }
                   18776:     my $now = time;
                   18777:     my $timefilter =
                   18778:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18779:     my ($createdbefore,$createdafter);
                   18780:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18781:         $createdbefore = $now;
                   18782:         $createdafter = $now-$filter->{'createdfilter'};
                   18783:     }
                   18784:     my ($instcodefilter,$regexpok);
                   18785:     if ($numtitles) {
                   18786:         if ($env{'form.official'} eq 'on') {
                   18787:             $instcodefilter =
                   18788:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18789:             $regexpok = 1;
                   18790:         } elsif ($env{'form.official'} eq 'off') {
                   18791:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18792:             unless ($instcodefilter eq '') {
                   18793:                 $regexpok = -1;
                   18794:             }
                   18795:         }
                   18796:     } else {
                   18797:         $instcodefilter = $filter->{'instcodefilter'};
                   18798:     }
                   18799:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18800:     if ($type eq '') { $type = '.'; }
                   18801: 
                   18802:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18803:         $cloner = $cloneruname.':'.$clonerudom;
                   18804:     }
                   18805:     %courses = &Apache::lonnet::courseiddump($dom,
                   18806:                                              $filter->{'descriptfilter'},
                   18807:                                              $timefilter,
                   18808:                                              $instcodefilter,
                   18809:                                              $filter->{'combownerfilter'},
                   18810:                                              $filter->{'coursefilter'},
                   18811:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18812:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18813:                                              $filter->{'cloneableonly'},
                   18814:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18815:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18816:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18817:         my $ccrole;
                   18818:         if ($type eq 'Community') {
                   18819:             $ccrole = 'co';
                   18820:         } else {
                   18821:             $ccrole = 'cc';
                   18822:         }
                   18823:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18824:                                                      $filter->{'persondomfilter'},
                   18825:                                                      'userroles',undef,
                   18826:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18827:                                                      $dom);
                   18828:         foreach my $role (keys(%rolehash)) {
                   18829:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18830:             my $cid = $cdom.'_'.$cnum;
                   18831:             if (exists($courses{$cid})) {
                   18832:                 if (ref($courses{$cid}) eq 'HASH') {
                   18833:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18834:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18835:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18836:                         }
                   18837:                     } else {
                   18838:                         $courses{$cid}{roles} = [$courserole];
                   18839:                     }
                   18840:                     $showcourses{$cid} = $courses{$cid};
                   18841:                 }
                   18842:             }
                   18843:         }
                   18844:         %courses = %showcourses;
                   18845:     }
                   18846:     return %courses;
                   18847: }
                   18848: 
                   18849: =pod
                   18850: 
1.1181    raeburn  18851: =back
                   18852: 
1.1207    raeburn  18853: =head1 Routines for version requirements for current course.
                   18854: 
                   18855: =over 4
                   18856: 
                   18857: =item * &check_release_required()
                   18858: 
                   18859: Compares required LON-CAPA version with version on server, and
                   18860: if required version is newer looks for a server with the required version.
                   18861: 
                   18862: Looks first at servers in user's owen domain; if none suitable, looks at
                   18863: servers in course's domain are permitted to host sessions for user's domain.
                   18864: 
                   18865: Inputs:
                   18866: 
                   18867: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18868: 
                   18869: $courseid - Course ID of current course
                   18870: 
                   18871: $rolecode - User's current role in course (for switchserver query string).
                   18872: 
                   18873: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18874: 
                   18875: 
                   18876: Returns:
                   18877: 
                   18878: $switchserver - query string tp append to /adm/switchserver call (if 
                   18879:                 current server's LON-CAPA version is too old. 
                   18880: 
                   18881: $warning - Message is displayed if no suitable server could be found.
                   18882: 
                   18883: =cut
                   18884: 
                   18885: sub check_release_required {
                   18886:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18887:     my ($switchserver,$warning);
                   18888:     if ($required ne '') {
                   18889:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18890:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18891:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18892:             my $otherserver;
                   18893:             if (($major eq '' && $minor eq '') ||
                   18894:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18895:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18896:                 my $switchlcrev =
                   18897:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18898:                                                            $userdomserver);
                   18899:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18900:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18901:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18902:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18903:                     if ($cdom ne $env{'user.domain'}) {
                   18904:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18905:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18906:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18907:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18908:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18909:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18910:                         my $canhost =
                   18911:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18912:                                                               $coursedomserver,
                   18913:                                                               $remoterev,
                   18914:                                                               $udomdefaults{'remotesessions'},
                   18915:                                                               $defdomdefaults{'hostedsessions'});
                   18916: 
                   18917:                         if ($canhost) {
                   18918:                             $otherserver = $coursedomserver;
                   18919:                         } else {
                   18920:                             $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.");
                   18921:                         }
                   18922:                     } else {
                   18923:                         $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).");
                   18924:                     }
                   18925:                 } else {
                   18926:                     $otherserver = $userdomserver;
                   18927:                 }
                   18928:             }
                   18929:             if ($otherserver ne '') {
                   18930:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18931:             }
                   18932:         }
                   18933:     }
                   18934:     return ($switchserver,$warning);
                   18935: }
                   18936: 
                   18937: =pod
                   18938: 
                   18939: =item * &check_release_result()
                   18940: 
                   18941: Inputs:
                   18942: 
                   18943: $switchwarning - Warning message if no suitable server found to host session.
                   18944: 
                   18945: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18946:                 and current role.
                   18947: 
                   18948: Returns: HTML to display with information about requirement to switch server.
                   18949:          Either displaying warning with link to Roles/Courses screen or
                   18950:          display link to switchserver.
                   18951: 
1.1181    raeburn  18952: =cut
                   18953: 
1.1207    raeburn  18954: sub check_release_result {
                   18955:     my ($switchwarning,$switchserver) = @_;
                   18956:     my $output = &start_page('Selected course unavailable on this server').
                   18957:                  '<p class="LC_warning">';
                   18958:     if ($switchwarning) {
                   18959:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18960:         if (&show_course()) {
                   18961:             $output .= &mt('Display courses');
                   18962:         } else {
                   18963:             $output .= &mt('Display roles');
                   18964:         }
                   18965:         $output .= '</a>';
                   18966:     } elsif ($switchserver) {
                   18967:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18968:                    '<br />'.
                   18969:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18970:                    &mt('Switch Server').
                   18971:                    '</a>';
                   18972:     }
                   18973:     $output .= '</p>'.&end_page();
                   18974:     return $output;
                   18975: }
                   18976: 
                   18977: =pod
                   18978: 
                   18979: =item * &needs_coursereinit()
                   18980: 
                   18981: Determine if course contents stored for user's session needs to be
                   18982: refreshed, because content has changed since "Big Hash" last tied.
                   18983: 
                   18984: Check for change is made if time last checked is more than 10 minutes ago
                   18985: (by default).
                   18986: 
                   18987: Inputs:
                   18988: 
                   18989: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18990: 
                   18991: $interval (optional) - Time which may elapse (in s) between last check for content
                   18992:                        change in current course. (default: 600 s).  
                   18993: 
                   18994: Returns: an array; first element is:
                   18995: 
                   18996: =over 4
                   18997: 
                   18998: 'switch' - if content updates mean user's session
                   18999:            needs to be switched to a server running a newer LON-CAPA version
                   19000:  
                   19001: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   19002:            on current server hosting user's session                
                   19003: 
                   19004: ''       - if no action required.
                   19005: 
                   19006: =back
                   19007: 
                   19008: If first item element is 'switch':
                   19009: 
                   19010: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   19011: 
                   19012: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   19013:                               and current role. 
                   19014: 
                   19015: otherwise: no other elements returned.
                   19016: 
                   19017: =back
                   19018: 
                   19019: =cut
                   19020: 
                   19021: sub needs_coursereinit {
                   19022:     my ($loncaparev,$interval) = @_;
                   19023:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   19024:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19025:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   19026:     my $now = time;
                   19027:     if ($interval eq '') {
                   19028:         $interval = 600;
                   19029:     }
                   19030:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  19031:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  19032:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19033:         if ($blocked) {
                   19034:             return ();
                   19035:         }
1.1391    raeburn  19036:         my $update;
                   19037:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19038:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19039:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19040:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19041:             if ($needswitch) {
                   19042:                 return ('switch',$switchwarning,$switchserver);
                   19043:             }
                   19044:             $update = 'main';
                   19045:         }
                   19046:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19047:             if ($update) {
                   19048:                 $update = 'both';
                   19049:             } else {
                   19050:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19051:                 if ($needswitch) {
                   19052:                     return ('switch',$switchwarning,$switchserver);
                   19053:                 } else {
                   19054:                     $update = 'supp';
1.1207    raeburn  19055:                 }
                   19056:             }
1.1391    raeburn  19057:             return ($update);
                   19058:         }
                   19059:     }
                   19060:     return ();
                   19061: }
                   19062: 
                   19063: sub switch_for_update {
                   19064:     my ($loncaparev,$cdom,$cnum) = @_;
                   19065:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19066:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19067:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19068:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19069:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19070:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19071:             my ($switchserver,$switchwarning) =
                   19072:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19073:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19074:             if ($switchwarning ne '' || $switchserver ne '') {
                   19075:                 return ('switch',$switchwarning,$switchserver);
                   19076:             }
1.1207    raeburn  19077:         }
                   19078:     }
                   19079:     return ();
                   19080: }
1.1181    raeburn  19081: 
1.1083    raeburn  19082: sub update_content_constraints {
1.1395    raeburn  19083:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19084:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19085:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19086:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19087:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19088:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19089:         if ($item eq 'resourcetag') {
                   19090:             if ($name eq 'responsetype') {
                   19091:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19092:             }
1.1307    raeburn  19093:         } elsif ($item eq 'course') {
                   19094:             if ($name eq 'courserestype') {
                   19095:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19096:             }
1.1083    raeburn  19097:         }
                   19098:     }
                   19099:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19100:     if (defined($navmap)) {
1.1307    raeburn  19101:         my (%allresponses,%allcrsrestypes);
                   19102:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19103:             if ($res->is_tool()) {
                   19104:                 if ($allcrsrestypes{'exttool'}) {
                   19105:                     $allcrsrestypes{'exttool'} ++;
                   19106:                 } else {
                   19107:                     $allcrsrestypes{'exttool'} = 1;
                   19108:                 }
                   19109:                 next;
                   19110:             }
1.1083    raeburn  19111:             my %responses = $res->responseTypes();
                   19112:             foreach my $key (keys(%responses)) {
                   19113:                 next unless(exists($checkresponsetypes{$key}));
                   19114:                 $allresponses{$key} += $responses{$key};
                   19115:             }
                   19116:         }
                   19117:         foreach my $key (keys(%allresponses)) {
                   19118:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19119:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19120:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19121:             }
                   19122:         }
1.1307    raeburn  19123:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19124:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19125:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19126:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19127:             }
                   19128:         }
1.1083    raeburn  19129:         undef($navmap);
                   19130:     }
1.1391    raeburn  19131:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19132:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19133:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19134:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19135:         }
                   19136:     }
1.1083    raeburn  19137:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19138:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19139:     }
                   19140:     return;
                   19141: }
                   19142: 
1.1110    raeburn  19143: sub allmaps_incourse {
                   19144:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19145:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19146:         $cid = $env{'request.course.id'};
                   19147:         $cdom = $env{'course.'.$cid.'.domain'};
                   19148:         $cnum = $env{'course.'.$cid.'.num'};
                   19149:         $chome = $env{'course.'.$cid.'.home'};
                   19150:     }
                   19151:     my %allmaps = ();
                   19152:     my $lastchange =
                   19153:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19154:     if ($lastchange > $env{'request.course.tied'}) {
                   19155:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19156:         unless ($ferr) {
1.1395    raeburn  19157:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19158:         }
                   19159:     }
                   19160:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19161:     if (defined($navmap)) {
                   19162:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19163:             $allmaps{$res->src()} = 1;
                   19164:         }
                   19165:     }
                   19166:     return \%allmaps;
                   19167: }
                   19168: 
1.1083    raeburn  19169: sub parse_supplemental_title {
                   19170:     my ($title) = @_;
                   19171: 
                   19172:     my ($foldertitle,$renametitle);
                   19173:     if ($title =~ /&amp;&amp;&amp;/) {
                   19174:         $title = &HTML::Entites::decode($title);
                   19175:     }
                   19176:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19177:         $renametitle=$4;
                   19178:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19179:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19180:         my $name =  &plainname($uname,$udom);
                   19181:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19182:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19183:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19184:         if ($foldertitle ne '') {
1.1401    raeburn  19185:             $title .= ': <br />'.$foldertitle;
                   19186:         }
1.1083    raeburn  19187:     }
                   19188:     if (wantarray) {
                   19189:         return ($title,$foldertitle,$renametitle);
                   19190:     }
                   19191:     return $title;
                   19192: }
                   19193: 
1.1395    raeburn  19194: sub get_supplemental {
                   19195:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19196:     my $hashid=$cnum.':'.$cdom;
                   19197:     my ($supplemental,$cached,$set_httprefs);
                   19198:     unless ($ignorecache) {
                   19199:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19200:     }
                   19201:     unless (defined($cached)) {
                   19202:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19203:         unless ($chome eq 'no_host') {
                   19204:             my @order = @LONCAPA::map::order;
                   19205:             my @resources = @LONCAPA::map::resources;
                   19206:             my @resparms = @LONCAPA::map::resparms;
                   19207:             my @zombies = @LONCAPA::map::zombies;
                   19208:             my ($errors,%ids,%hidden);
                   19209:             $errors =
                   19210:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19211:                                       $errors,$possdel,\%ids,\%hidden);
                   19212:             @LONCAPA::map::order = @order;
                   19213:             @LONCAPA::map::resources = @resources;
                   19214:             @LONCAPA::map::resparms = @resparms;
                   19215:             @LONCAPA::map::zombies = @zombies;
                   19216:             $set_httprefs = 1;
                   19217:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19218:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19219:             }
                   19220:             $supplemental = {
                   19221:                                ids => \%ids,
                   19222:                                hidden => \%hidden,
                   19223:                             };
                   19224:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19225:         }
                   19226:     }
                   19227:     return ($supplemental,$set_httprefs);
                   19228: }
                   19229: 
1.1143    raeburn  19230: sub recurse_supplemental {
1.1391    raeburn  19231:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19232:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19233:         my $mapnum;
                   19234:         if ($suppmap eq 'supplemental.sequence') {
                   19235:             $mapnum = 0;
                   19236:         } else {
                   19237:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19238:         }
1.1143    raeburn  19239:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19240:         if ($fatal) {
                   19241:             $errors ++;
                   19242:         } else {
1.1389    raeburn  19243:             my @order = @LONCAPA::map::order;
                   19244:             if (@order > 0) {
                   19245:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19246:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19247:                 foreach my $idx (@order) {
                   19248:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19249:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19250:                         my $id = $mapnum.':'.$idx;
                   19251:                         push(@{$suppids->{$src}},$id);
                   19252:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19253:                             $hiddensupp->{$id} = 1;
                   19254:                         }
1.1146    raeburn  19255:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19256:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19257:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19258:                         } else {
1.1391    raeburn  19259:                             my $allowed;
                   19260:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19261:                                 $allowed = 1;
                   19262:                             } elsif ($possdel) {
                   19263:                                 foreach my $item (@{$suppids->{$src}}) {
                   19264:                                     next if ($item eq $id);
                   19265:                                     unless ($hiddensupp->{$item}) {
                   19266:                                        $allowed = 1;
                   19267:                                        last;
                   19268:                                     }
                   19269:                                 }
                   19270:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19271:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19272:                                 }
                   19273:                             }
                   19274:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19275:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19276:                             }
1.1143    raeburn  19277:                         }
                   19278:                     }
                   19279:                 }
                   19280:             }
                   19281:         }
                   19282:     }
1.1391    raeburn  19283:     return $errors;
                   19284: }
                   19285: 
                   19286: sub set_supp_httprefs {
                   19287:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19288:     if (ref($supplemental) eq 'HASH') {
                   19289:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19290:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19291:                 next if ($src =~ /\.sequence$/);
                   19292:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19293:                     my $allowed;
                   19294:                     if ($env{'request.role.adv'}) {
                   19295:                         $allowed = 1;
                   19296:                     } else {
                   19297:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19298:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19299:                                 $allowed = 1;
                   19300:                                 last;
                   19301:                             }
                   19302:                         }
                   19303:                     }
                   19304:                     if (exists($env{'httpref.'.$src})) {
                   19305:                         if ($possdel) {
                   19306:                             unless ($allowed) {
                   19307:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19308:                             }
                   19309:                         }
                   19310:                     } elsif ($allowed) {
                   19311:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19312:                     }
                   19313:                 }
                   19314:             }
                   19315:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19316:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19317:             }
                   19318:         }
                   19319:     }
                   19320: }
                   19321: 
                   19322: sub get_supp_parameter {
                   19323:     my ($resparm,$name)=@_;
                   19324:     return if ($resparm eq '');
                   19325:     my $value=undef;
                   19326:     my $ptype=undef;
                   19327:     foreach (split('&&&',$resparm)) {
                   19328:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19329:         if ($thisname eq $name) {
                   19330:             $value=$thisvalue;
                   19331:             $ptype=$thistype;
                   19332:         }
                   19333:     }
                   19334:     return $value;
1.1143    raeburn  19335: }
                   19336: 
1.1101    raeburn  19337: sub symb_to_docspath {
1.1267    raeburn  19338:     my ($symb,$navmapref) = @_;
                   19339:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19340:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19341:     if ($resurl=~/\.(sequence|page)$/) {
                   19342:         $mapurl=$resurl;
                   19343:     } elsif ($resurl eq 'adm/navmaps') {
                   19344:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19345:     }
                   19346:     my $mapresobj;
1.1267    raeburn  19347:     unless (ref($$navmapref)) {
                   19348:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19349:     }
                   19350:     if (ref($$navmapref)) {
                   19351:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19352:     }
                   19353:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19354:     my $type=$2;
                   19355:     my $path;
                   19356:     if (ref($mapresobj)) {
                   19357:         my $pcslist = $mapresobj->map_hierarchy();
                   19358:         if ($pcslist ne '') {
                   19359:             foreach my $pc (split(/,/,$pcslist)) {
                   19360:                 next if ($pc <= 1);
1.1267    raeburn  19361:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19362:                 if (ref($res)) {
                   19363:                     my $thisurl = $res->src();
                   19364:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19365:                     my $thistitle = $res->title();
                   19366:                     $path .= '&'.
                   19367:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19368:                              &escape($thistitle).
1.1101    raeburn  19369:                              ':'.$res->randompick().
                   19370:                              ':'.$res->randomout().
                   19371:                              ':'.$res->encrypted().
                   19372:                              ':'.$res->randomorder().
                   19373:                              ':'.$res->is_page();
                   19374:                 }
                   19375:             }
                   19376:         }
                   19377:         $path =~ s/^\&//;
                   19378:         my $maptitle = $mapresobj->title();
                   19379:         if ($mapurl eq 'default') {
1.1129    raeburn  19380:             $maptitle = 'Main Content';
1.1101    raeburn  19381:         }
                   19382:         $path .= (($path ne '')? '&' : '').
                   19383:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19384:                  &escape($maptitle).
1.1101    raeburn  19385:                  ':'.$mapresobj->randompick().
                   19386:                  ':'.$mapresobj->randomout().
                   19387:                  ':'.$mapresobj->encrypted().
                   19388:                  ':'.$mapresobj->randomorder().
                   19389:                  ':'.$mapresobj->is_page();
                   19390:     } else {
                   19391:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19392:         my $ispage = (($type eq 'page')? 1 : '');
                   19393:         if ($mapurl eq 'default') {
1.1129    raeburn  19394:             $maptitle = 'Main Content';
1.1101    raeburn  19395:         }
                   19396:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19397:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19398:     }
                   19399:     unless ($mapurl eq 'default') {
                   19400:         $path = 'default&'.
1.1146    raeburn  19401:                 &escape('Main Content').
1.1101    raeburn  19402:                 ':::::&'.$path;
                   19403:     }
                   19404:     return $path;
                   19405: }
                   19406: 
1.1393    raeburn  19407: sub validate_folderpath {
                   19408:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19409:     if ($env{'form.folderpath'} ne '') {
                   19410:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19411:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19412:         for (my $i=0; $i<@items; $i++) {
                   19413:             my $odd = $i%2;
                   19414:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19415:                 $badpath = 1;
1.1394    raeburn  19416:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19417:                 my $idx = $i-1;
1.1394    raeburn  19418:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19419:                     my $esc_name = $1;
                   19420:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19421:                         $supppath .= '&'.$esc_name;
                   19422:                         $changed = 1;
                   19423:                     } else {
                   19424:                         $supppath .= '&'.$items[$i];
                   19425:                     }
                   19426:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19427:                     $changed = 1;
1.1393    raeburn  19428:                     my $is_hidden;
                   19429:                     unless ($got_supp) {
1.1395    raeburn  19430:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19431:                         if (ref($supplemental) eq 'HASH') {
                   19432:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19433:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19434:                             }
                   19435:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19436:                                 %suppids = %{$supplemental->{'ids'}};
                   19437:                             }
                   19438:                         }
                   19439:                         $got_supp = 1;
                   19440:                     }
                   19441:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19442:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19443:                         if ($supphidden{$mapid}) {
                   19444:                             $is_hidden = 1;
                   19445:                         }
                   19446:                     }
1.1394    raeburn  19447:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19448:                 } else {
                   19449:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19450:                 }
                   19451:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19452:                 $badpath = 1;
1.1394    raeburn  19453:             } elsif ($supplementalflag) {
1.1393    raeburn  19454:                 $supppath .= '&'.$items[$i];
                   19455:             }
                   19456:             last if ($badpath);
                   19457:         }
                   19458:         if ($badpath) {
                   19459:             delete($env{'form.folderpath'});
1.1394    raeburn  19460:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19461:             $supppath =~ s/^\&//;
                   19462:             $env{'form.folderpath'} = $supppath;
                   19463:         }
                   19464:     }
                   19465:     return;
                   19466: }
                   19467: 
1.1094    raeburn  19468: sub captcha_display {
1.1327    raeburn  19469:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19470:     my ($output,$error);
1.1234    raeburn  19471:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19472:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19473:     if ($captcha eq 'original') {
1.1094    raeburn  19474:         $output = &create_captcha();
                   19475:         unless ($output) {
1.1172    raeburn  19476:             $error = 'captcha';
1.1094    raeburn  19477:         }
                   19478:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19479:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19480:         unless ($output) {
1.1172    raeburn  19481:             $error = 'recaptcha';
1.1094    raeburn  19482:         }
                   19483:     }
1.1234    raeburn  19484:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19485: }
                   19486: 
                   19487: sub captcha_response {
1.1327    raeburn  19488:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19489:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19490:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19491:     if ($captcha eq 'original') {
1.1094    raeburn  19492:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19493:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19494:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19495:     } else {
                   19496:         $captcha_chk = 1;
                   19497:     }
                   19498:     return ($captcha_chk,$captcha_error);
                   19499: }
                   19500: 
                   19501: sub get_captcha_config {
1.1327    raeburn  19502:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19503:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19504:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19505:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19506:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19507:     if ($context eq 'usercreation') {
                   19508:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19509:         if (ref($domconfig{$context}) eq 'HASH') {
                   19510:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19511:             if (ref($hashtocheck) eq 'HASH') {
                   19512:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19513:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19514:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19515:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19516:                     }
                   19517:                     if ($privkey && $pubkey) {
                   19518:                         $captcha = 'recaptcha';
1.1234    raeburn  19519:                         $version = $hashtocheck->{'recaptchaversion'};
                   19520:                         if ($version ne '2') {
                   19521:                             $version = 1;
                   19522:                         }
1.1095    raeburn  19523:                     } else {
                   19524:                         $captcha = 'original';
                   19525:                     }
                   19526:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19527:                     $captcha = 'original';
                   19528:                 }
1.1094    raeburn  19529:             }
1.1095    raeburn  19530:         } else {
                   19531:             $captcha = 'captcha';
                   19532:         }
                   19533:     } elsif ($context eq 'login') {
                   19534:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19535:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19536:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19537:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19538:             if ($privkey && $pubkey) {
                   19539:                 $captcha = 'recaptcha';
1.1234    raeburn  19540:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19541:                 if ($version ne '2') {
                   19542:                     $version = 1; 
                   19543:                 }
1.1095    raeburn  19544:             } else {
                   19545:                 $captcha = 'original';
1.1094    raeburn  19546:             }
1.1095    raeburn  19547:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19548:             $captcha = 'original';
1.1094    raeburn  19549:         }
1.1327    raeburn  19550:     } elsif ($context eq 'passwords') {
                   19551:         if ($dom_in_effect) {
                   19552:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19553:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19554:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19555:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19556:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19557:                 }
                   19558:                 if ($privkey && $pubkey) {
                   19559:                     $captcha = 'recaptcha';
                   19560:                     $version = $passwdconf{'recaptchaversion'};
                   19561:                     if ($version ne '2') {
                   19562:                         $version = 1;
                   19563:                     }
                   19564:                 } else {
                   19565:                     $captcha = 'original';
                   19566:                 }
                   19567:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19568:                 $captcha = 'original';
                   19569:             }
                   19570:         }
                   19571:     } 
1.1234    raeburn  19572:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19573: }
                   19574: 
                   19575: sub create_captcha {
                   19576:     my %captcha_params = &captcha_settings();
                   19577:     my ($output,$maxtries,$tries) = ('',10,0);
                   19578:     while ($tries < $maxtries) {
                   19579:         $tries ++;
                   19580:         my $captcha = Authen::Captcha->new (
                   19581:                                            output_folder => $captcha_params{'output_dir'},
                   19582:                                            data_folder   => $captcha_params{'db_dir'},
                   19583:                                           );
                   19584:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19585: 
                   19586:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19587:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19588:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19589:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19590:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19591:                       '</span><br />'.
1.1176    raeburn  19592:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19593:             last;
                   19594:         }
                   19595:     }
1.1323    raeburn  19596:     if ($output eq '') {
                   19597:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19598:     }
1.1094    raeburn  19599:     return $output;
                   19600: }
                   19601: 
                   19602: sub captcha_settings {
                   19603:     my %captcha_params = (
                   19604:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19605:                            www_output_dir => "/captchaspool",
                   19606:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19607:                            numchars       => '5',
                   19608:                          );
                   19609:     return %captcha_params;
                   19610: }
                   19611: 
                   19612: sub check_captcha {
                   19613:     my ($captcha_chk,$captcha_error);
                   19614:     my $code = $env{'form.code'};
                   19615:     my $md5sum = $env{'form.crypt'};
                   19616:     my %captcha_params = &captcha_settings();
                   19617:     my $captcha = Authen::Captcha->new(
                   19618:                       output_folder => $captcha_params{'output_dir'},
                   19619:                       data_folder   => $captcha_params{'db_dir'},
                   19620:                   );
1.1109    raeburn  19621:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19622:     my %captcha_hash = (
                   19623:                         0       => 'Code not checked (file error)',
                   19624:                        -1      => 'Failed: code expired',
                   19625:                        -2      => 'Failed: invalid code (not in database)',
                   19626:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19627:     );
                   19628:     if ($captcha_chk != 1) {
                   19629:         $captcha_error = $captcha_hash{$captcha_chk}
                   19630:     }
                   19631:     return ($captcha_chk,$captcha_error);
                   19632: }
                   19633: 
                   19634: sub create_recaptcha {
1.1234    raeburn  19635:     my ($pubkey,$version) = @_;
                   19636:     if ($version >= 2) {
1.1367    raeburn  19637:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19638:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19639:     } else {
                   19640:         my $use_ssl;
                   19641:         if ($ENV{'SERVER_PORT'} == 443) {
                   19642:             $use_ssl = 1;
                   19643:         }
                   19644:         my $captcha = Captcha::reCAPTCHA->new;
                   19645:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19646:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19647:                &mt('If the text is hard to read, [_1] will replace them.',
                   19648:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19649:                '<br /><br />';
                   19650:     }
1.1094    raeburn  19651: }
                   19652: 
                   19653: sub check_recaptcha {
1.1234    raeburn  19654:     my ($privkey,$version) = @_;
1.1094    raeburn  19655:     my $captcha_chk;
1.1350    raeburn  19656:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19657:     if ($version >= 2) {
                   19658:         my %info = (
                   19659:                      secret   => $privkey, 
                   19660:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19661:                      remoteip => $ip,
1.1234    raeburn  19662:                    );
1.1280    raeburn  19663:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19664:         $request->content(join('&',map {
                   19665:                          my $name = escape($_);
                   19666:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19667:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19668:                          : &escape($info{$_}) );
                   19669:         } keys(%info)));
                   19670:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19671:         if ($response->is_success)  {
                   19672:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19673:             if (ref($data) eq 'HASH') {
                   19674:                 if ($data->{'success'}) {
                   19675:                     $captcha_chk = 1;
                   19676:                 }
                   19677:             }
                   19678:         }
                   19679:     } else {
                   19680:         my $captcha = Captcha::reCAPTCHA->new;
                   19681:         my $captcha_result =
                   19682:             $captcha->check_answer(
                   19683:                                     $privkey,
1.1350    raeburn  19684:                                     $ip,
1.1234    raeburn  19685:                                     $env{'form.recaptcha_challenge_field'},
                   19686:                                     $env{'form.recaptcha_response_field'},
                   19687:                                   );
                   19688:         if ($captcha_result->{is_valid}) {
                   19689:             $captcha_chk = 1;
                   19690:         }
1.1094    raeburn  19691:     }
                   19692:     return $captcha_chk;
                   19693: }
                   19694: 
1.1174    raeburn  19695: sub emailusername_info {
1.1244    raeburn  19696:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19697:     my %titles = &Apache::lonlocal::texthash (
                   19698:                      lastname      => 'Last Name',
                   19699:                      firstname     => 'First Name',
                   19700:                      institution   => 'School/college/university',
                   19701:                      location      => "School's city, state/province, country",
                   19702:                      web           => "School's web address",
                   19703:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19704:                      id            => 'Student/Employee ID',
1.1174    raeburn  19705:                  );
                   19706:     return (\@fields,\%titles);
                   19707: }
                   19708: 
1.1161    raeburn  19709: sub cleanup_html {
                   19710:     my ($incoming) = @_;
                   19711:     my $outgoing;
                   19712:     if ($incoming ne '') {
                   19713:         $outgoing = $incoming;
                   19714:         $outgoing =~ s/;/&#059;/g;
                   19715:         $outgoing =~ s/\#/&#035;/g;
                   19716:         $outgoing =~ s/\&/&#038;/g;
                   19717:         $outgoing =~ s/</&#060;/g;
                   19718:         $outgoing =~ s/>/&#062;/g;
                   19719:         $outgoing =~ s/\(/&#040/g;
                   19720:         $outgoing =~ s/\)/&#041;/g;
                   19721:         $outgoing =~ s/"/&#034;/g;
                   19722:         $outgoing =~ s/'/&#039;/g;
                   19723:         $outgoing =~ s/\$/&#036;/g;
                   19724:         $outgoing =~ s{/}{&#047;}g;
                   19725:         $outgoing =~ s/=/&#061;/g;
                   19726:         $outgoing =~ s/\\/&#092;/g
                   19727:     }
                   19728:     return $outgoing;
                   19729: }
                   19730: 
1.1190    musolffc 19731: # Checks for critical messages and returns a redirect url if one exists.
                   19732: # $interval indicates how often to check for messages.
1.1282    raeburn  19733: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19734: sub critical_redirect {
1.1282    raeburn  19735:     my ($interval,$context) = @_;
1.1356    raeburn  19736:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19737:         return ();
                   19738:     }
1.1190    musolffc 19739:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19740:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19741:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19742:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19743:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19744:             if ($blocked) {
                   19745:                 my $checkrole = "cm./$cdom/$cnum";
                   19746:                 if ($env{'request.course.sec'} ne '') {
                   19747:                     $checkrole .= "/$env{'request.course.sec'}";
                   19748:                 }
                   19749:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19750:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19751:                     return;
                   19752:                 }
                   19753:             }
                   19754:         }
1.1190    musolffc 19755:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19756:                                         $env{'user.name'});
                   19757:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19758:         my $redirecturl;
1.1190    musolffc 19759:         if ($what[0]) {
1.1356    raeburn  19760: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19761: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19762: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19763:                 return (1, $url);
1.1190    musolffc 19764:             }
1.1191    raeburn  19765:         }
                   19766:     } 
                   19767:     return ();
1.1190    musolffc 19768: }
                   19769: 
1.1174    raeburn  19770: # Use:
                   19771: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19772: #
                   19773: ##################################################
                   19774: #          password associated functions         #
                   19775: ##################################################
                   19776: sub des_keys {
                   19777:     # Make a new key for DES encryption.
                   19778:     # Each key has two parts which are returned separately.
                   19779:     # Please note:  Each key must be passed through the &hex function
                   19780:     # before it is output to the web browser.  The hex versions cannot
                   19781:     # be used to decrypt.
                   19782:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19783:                 '8','9','a','b','c','d','e','f');
                   19784:     my $lkey='';
                   19785:     for (0..7) {
                   19786:         $lkey.=$hexstr[rand(15)];
                   19787:     }
                   19788:     my $ukey='';
                   19789:     for (0..7) {
                   19790:         $ukey.=$hexstr[rand(15)];
                   19791:     }
                   19792:     return ($lkey,$ukey);
                   19793: }
                   19794: 
                   19795: sub des_decrypt {
                   19796:     my ($key,$cyphertext) = @_;
                   19797:     my $keybin=pack("H16",$key);
                   19798:     my $cypher;
                   19799:     if ($Crypt::DES::VERSION>=2.03) {
                   19800:         $cypher=new Crypt::DES $keybin;
                   19801:     } else {
                   19802:         $cypher=new DES $keybin;
                   19803:     }
1.1233    raeburn  19804:     my $plaintext='';
                   19805:     my $cypherlength = length($cyphertext);
                   19806:     my $numchunks = int($cypherlength/32);
                   19807:     for (my $j=0; $j<$numchunks; $j++) {
                   19808:         my $start = $j*32;
                   19809:         my $cypherblock = substr($cyphertext,$start,32);
                   19810:         my $chunk =
                   19811:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19812:         $chunk .=
                   19813:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19814:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19815:         $plaintext .= $chunk;
                   19816:     }
1.1174    raeburn  19817:     return $plaintext;
                   19818: }
                   19819: 
1.1344    raeburn  19820: sub get_requested_shorturls {
1.1309    raeburn  19821:     my ($cdom,$cnum,$navmap) = @_;
                   19822:     return unless (ref($navmap));
1.1344    raeburn  19823:     my ($numnew,$errors);
1.1309    raeburn  19824:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19825:     if (@toshorten) {
                   19826:         my (%maps,%resources,%titles);
                   19827:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19828:                                                                'shorturls',$cdom,$cnum);
                   19829:         if (keys(%resources)) {
1.1344    raeburn  19830:             my %tocreate;
1.1309    raeburn  19831:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19832:                 my $symb = $resources{$item};
                   19833:                 if ($symb) {
                   19834:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19835:                 }
                   19836:             }
1.1344    raeburn  19837:             if (keys(%tocreate)) {
                   19838:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19839:                                                       \%tocreate);
                   19840:             }
1.1309    raeburn  19841:         }
1.1344    raeburn  19842:     }
                   19843:     return ($numnew,$errors);
                   19844: }
                   19845: 
                   19846: sub make_short_symbs {
                   19847:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19848:     my ($numnew,@errors);
                   19849:     if (ref($tocreateref) eq 'HASH') {
                   19850:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19851:         if (keys(%tocreate)) {
                   19852:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19853:             my $su = Short::URL->new(no_vowels => 1);
                   19854:             my $init = '';
                   19855:             my (%newunique,%addcourse,%courseonly,%failed);
                   19856:             # get lock on tiny db
                   19857:             my $now = time;
1.1344    raeburn  19858:             if ($lockuser eq '') {
                   19859:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19860:             }
1.1309    raeburn  19861:             my $lockhash = {
1.1344    raeburn  19862:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19863:                             };
                   19864:             my $tries = 0;
                   19865:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19866:             my ($code,$error);
                   19867:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19868:                 $tries ++;
                   19869:                 sleep 1;
1.1319    raeburn  19870:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19871:             }
                   19872:             if ($gotlock eq 'ok') {
                   19873:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19874:                                        \%addcourse,\%courseonly,\%failed);
                   19875:                 if (keys(%failed)) {
                   19876:                     my $numfailed = scalar(keys(%failed));
                   19877:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19878:                 }
                   19879:                 if (keys(%newunique)) {
                   19880:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19881:                     if ($putres eq 'ok') {
                   19882:                         $numnew = scalar(keys(%newunique));
                   19883:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19884:                         unless ($newputres eq 'ok') {
                   19885:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19886:                         }
                   19887:                     } else {
                   19888:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19889:                     }
                   19890:                 }
                   19891:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19892:                 unless ($dellockres eq 'ok') {
                   19893:                     push(@errors,&mt('error: could not release lockfile'));
                   19894:                 }
                   19895:             } else {
                   19896:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19897:             }
                   19898:             if (keys(%courseonly)) {
                   19899:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19900:                 if ($result ne 'ok') {
                   19901:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19902:                 }
                   19903:             }
                   19904:         }
                   19905:     }
                   19906:     return ($numnew,\@errors);
                   19907: }
                   19908: 
                   19909: sub shorten_symbs {
                   19910:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19911:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19912:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19913:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19914:     my (%possibles,%collisions);
                   19915:     foreach my $key (keys(%{$tocreate})) {
                   19916:         my $num = String::CRC32::crc32($key);
                   19917:         my $tiny = $su->encode($num,$init);
                   19918:         if ($tiny) {
                   19919:             $possibles{$tiny} = $key;
                   19920:         }
                   19921:     }
                   19922:     if (!$init) {
                   19923:         $init = 1;
                   19924:     } else {
                   19925:         $init ++;
                   19926:     }
                   19927:     if (keys(%possibles)) {
                   19928:         my @posstiny = keys(%possibles);
                   19929:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19930:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19931:         if (keys(%currtiny)) {
                   19932:             foreach my $key (keys(%currtiny)) {
                   19933:                 next if ($currtiny{$key} eq '');
                   19934:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19935:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19936:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19937:                         $courseonly->{$tsymb} = $key;
                   19938:                     }
                   19939:                 } else {
                   19940:                     $collisions{$possibles{$key}} = 1;
                   19941:                 }
                   19942:                 delete($possibles{$key});
                   19943:             }
                   19944:         }
                   19945:         foreach my $key (keys(%possibles)) {
                   19946:             $newunique->{$key} = $possibles{$key};
                   19947:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19948:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19949:                 $addcourse->{$tsymb} = $key;
                   19950:             }
                   19951:         }
                   19952:     }
                   19953:     if (keys(%collisions)) {
                   19954:         if ($init <5) {
                   19955:             if (!$init) {
                   19956:                 $init = 1;
                   19957:             } else {
                   19958:                 $init ++;
                   19959:             }
                   19960:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19961:                                    $newunique,$addcourse,$courseonly,$failed);
                   19962:         } else {
                   19963:             foreach my $key (keys(%collisions)) {
                   19964:                 $failed->{$key} = 1;
                   19965:             }
                   19966:         }
                   19967:     }
                   19968:     return $init;
                   19969: }
                   19970: 
1.1328    raeburn  19971: sub is_nonframeable {
1.1329    raeburn  19972:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19973:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19974:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19975: 
                   19976:     $remprotocol = lc($remprotocol);
                   19977:     $remhost = lc($remhost);
                   19978:     my $remport = 80;
                   19979:     if ($remprotocol eq 'https') {
                   19980:         $remport = 443;
                   19981:     }
1.1330    raeburn  19982:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19983:     if ($cached) {
                   19984:         unless ($nocache) {
                   19985:             if ($result) {
                   19986:                 return 1;
                   19987:             } else {
                   19988:                 return 0;
                   19989:             }
                   19990:         }
                   19991:     }
1.1328    raeburn  19992:     my $uselink;
                   19993:     my $request = new HTTP::Request('HEAD',$url);
                   19994:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19995:     if ($response->is_success()) {
                   19996:         my $secpolicy = lc($response->header('content-security-policy'));
                   19997:         my $xframeop = lc($response->header('x-frame-options'));
                   19998:         $secpolicy =~ s/^\s+|\s+$//g;
                   19999:         $xframeop =~ s/^\s+|\s+$//g;
                   20000:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  20001:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  20002:             my ($origin,$protocol,$port);
                   20003:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   20004:                 $port = $ENV{'SERVER_PORT'};
                   20005:             } else {
                   20006:                 $port = 80;
                   20007:             }
                   20008:             if ($absolute eq '') {
                   20009:                 $protocol = 'http:';
                   20010:                 if ($port == 443) {
                   20011:                     $protocol = 'https:';
                   20012:                 }
                   20013:                 $origin = $protocol.'//'.lc($hostname);
                   20014:             } else {
                   20015:                 $origin = lc($absolute);
                   20016:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   20017:             }
                   20018:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   20019:                 my $framepolicy = $1;
                   20020:                 $framepolicy =~ s/^\s+|\s+$//g;
                   20021:                 my @policies = split(/\s+/,$framepolicy);
                   20022:                 if (@policies) {
                   20023:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   20024:                         $uselink = 1;
                   20025:                     } else {
                   20026:                         $uselink = 1;
                   20027:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   20028:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   20029:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   20030:                             undef($uselink);
                   20031:                         }
                   20032:                         if ($uselink) {
                   20033:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   20034:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   20035:                                     undef($uselink);
                   20036:                                 }
                   20037:                             }
                   20038:                         }
                   20039:                         if ($uselink) {
                   20040:                             my @possok;
                   20041:                             if ($ip ne '') {
                   20042:                                 push(@possok,$ip);
                   20043:                             }
                   20044:                             my $hoststr = '';
                   20045:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20046:                                 if ($hoststr eq '') {
                   20047:                                     $hoststr = $part;
                   20048:                                 } else {
                   20049:                                     $hoststr = "$part.$hoststr";
                   20050:                                 }
                   20051:                                 if ($hoststr eq $hostname) {
                   20052:                                     push(@possok,$hostname);
                   20053:                                 } else {
                   20054:                                     push(@possok,"*.$hoststr");
                   20055:                                 }
                   20056:                             }
                   20057:                             if (@possok) {
                   20058:                                 foreach my $poss (@possok) {
                   20059:                                     last if (!$uselink);
                   20060:                                     foreach my $policy (@policies) {
                   20061:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20062:                                             undef($uselink);
                   20063:                                             last;
                   20064:                                         }
                   20065:                                     }
                   20066:                                 }
                   20067:                             }
                   20068:                         }
                   20069:                     }
                   20070:                 }
                   20071:             } elsif ($xframeop ne '') {
                   20072:                 $uselink = 1;
                   20073:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20074:                 if (@policies) {
                   20075:                     unless (grep(/^deny$/,@policies)) {
                   20076:                         if ($origin ne '') {
                   20077:                             if (grep(/^sameorigin$/,@policies)) {
                   20078:                                 if ($remotehost eq $origin) {
                   20079:                                     undef($uselink);
                   20080:                                 }
                   20081:                             }
                   20082:                             if ($uselink) {
                   20083:                                 foreach my $policy (@policies) {
                   20084:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20085:                                         my $allowfrom = $1;
                   20086:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20087:                                             undef($uselink);
                   20088:                                             last;
                   20089:                                         }
                   20090:                                     }
                   20091:                                 }
                   20092:                             }
                   20093:                         }
                   20094:                     }
                   20095:                 }
                   20096:             }
                   20097:         }
                   20098:     }
1.1329    raeburn  20099:     if ($nocache) {
                   20100:         if ($cached) {
                   20101:             my $devalidate;
                   20102:             if ($uselink && !$result) {
                   20103:                 $devalidate = 1;
                   20104:             } elsif (!$uselink && $result) {
                   20105:                 $devalidate = 1;
                   20106:             }
                   20107:             if ($devalidate) {
                   20108:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20109:             }
                   20110:         }
                   20111:     } else {
                   20112:         if ($uselink) {
                   20113:             $result = 1;
                   20114:         } else {
                   20115:             $result = 0;
                   20116:         }
                   20117:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20118:     }
1.1328    raeburn  20119:     return $uselink;
                   20120: }
                   20121: 
1.1359    raeburn  20122: sub page_menu {
                   20123:     my ($menucolls,$menunum) = @_;
                   20124:     my %menu;
                   20125:     foreach my $item (split(/;/,$menucolls)) {
                   20126:         my ($num,$value) = split(/\%/,$item);
                   20127:         if ($num eq $menunum) {
                   20128:             my @entries = split(/\&/,$value);
                   20129:             foreach my $entry (@entries) {
                   20130:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20131:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20132:                     $menu{$name} = $fields;
                   20133:                 } else {
                   20134:                     my @shown;
                   20135:                     if ($fields =~ /,/) {
                   20136:                         @shown = split(/,/,$fields);
                   20137:                     } else {
                   20138:                         @shown = ($fields);
                   20139:                     }
                   20140:                     if (@shown) {
                   20141:                         foreach my $field (@shown) {
                   20142:                             next if ($field eq '');
                   20143:                             $menu{$field} = 1;
                   20144:                         }
                   20145:                     }
                   20146:                 }
                   20147:             }
                   20148:         }
                   20149:     }
                   20150:     return %menu;
                   20151: }
                   20152: 
1.112     bowersj2 20153: 1;
                   20154: __END__;
1.41      ng       20155: 

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