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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1443  ! raeburn     4: # $Id: loncommon.pm,v 1.1442 2024/10/12 21:41:25 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>
                   2479: <language>notset </language>
                   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') ||
                   5694:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5695:                     if ($udom eq $cdom) {
                   5696:                         $check_ipaccess = 1;
                   5697:                     }
                   5698:                 }
                   5699:             }
1.1375    raeburn  5700:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5701:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5702:             my $checkrole;
                   5703:             if ($env{'request.role.domain'} eq '') {
                   5704:                 $checkrole = "cm./$env{'user.domain'}/";
                   5705:             } else {
                   5706:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5707:             }
                   5708:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5709:                 $has_evb = 1;
                   5710:             }
1.1372    raeburn  5711:         }
                   5712:         unless ($has_evb || $check_ipaccess) {
                   5713:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5714:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5715:                 $dom = $udom;
                   5716:             }
                   5717:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5718:                 $check_ipaccess = 1;
                   5719:             } else {
                   5720:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5721:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5722:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5723:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5724:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5725:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5726:                         $check_ipaccess = 1;
                   5727:                     }
                   5728:                 }
                   5729:             }
                   5730:         }
                   5731:         if ($check_ipaccess) {
                   5732:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5733:             unless (defined($cached)) {
                   5734:                 my %domconfig =
                   5735:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5736:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5737:             }
                   5738:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5739:                 foreach my $id (keys(%{$ipaccessref})) {
                   5740:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5741:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5742:                         if ($range) {
                   5743:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5744:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5745:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5746:                                         return ('','','',$id,$dom);
                   5747:                                         last;
                   5748:                                     }
                   5749:                                 }
                   5750:                             }
                   5751:                         }
                   5752:                     }
                   5753:                 }
                   5754:             }
                   5755:         }
1.1373    raeburn  5756:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5757:             return ();
                   5758:         }
1.1372    raeburn  5759:     }
1.1189    raeburn  5760:     if (defined($udom) && defined($uname)) {
                   5761:         # If uname and udom are for a course, check for blocks in the course.
                   5762:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5763:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5764:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5765:             return ($startblock,$endblock,$triggerblock);
                   5766:         }
                   5767:     } else {
1.490     raeburn  5768:         $udom = $env{'user.domain'};
                   5769:         $uname = $env{'user.name'};
                   5770:     }
                   5771: 
1.502     raeburn  5772:     my $startblock = 0;
                   5773:     my $endblock = 0;
1.1062    raeburn  5774:     my $triggerblock = '';
1.1373    raeburn  5775:     my %live_courses;
                   5776:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5777:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5778:     }
1.474     raeburn  5779: 
1.490     raeburn  5780:     # If uname is for a user, and activity is course-specific, i.e.,
                   5781:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5782: 
1.490     raeburn  5783:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5784:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5785:          $activity eq 'search' || $activity eq 'reinit' ||
                   5786:          $activity eq 'alert') &&
1.1189    raeburn  5787:         ($env{'request.course.id'})) {
1.490     raeburn  5788:         foreach my $key (keys(%live_courses)) {
                   5789:             if ($key ne $env{'request.course.id'}) {
                   5790:                 delete($live_courses{$key});
                   5791:             }
                   5792:         }
                   5793:     }
                   5794: 
                   5795:     my $otheruser = 0;
                   5796:     my %own_courses;
                   5797:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5798:         # Resource belongs to user other than current user.
                   5799:         $otheruser = 1;
                   5800:         # Gather courses for current user
                   5801:         %own_courses = 
                   5802:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5803:     }
                   5804: 
                   5805:     # Gather active course roles - course coordinator, instructor, 
                   5806:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5807: 
                   5808:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5809:         my ($cdom,$cnum);
                   5810:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5811:             $cdom = $env{'course.'.$course.'.domain'};
                   5812:             $cnum = $env{'course.'.$course.'.num'};
                   5813:         } else {
1.490     raeburn  5814:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5815:         }
                   5816:         my $no_ownblock = 0;
                   5817:         my $no_userblock = 0;
1.533     raeburn  5818:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5819:             # Check if current user has 'evb' priv for this
                   5820:             if (defined($own_courses{$course})) {
                   5821:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5822:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5823:                     if ($sec ne 'none') {
                   5824:                         $checkrole .= '/'.$sec;
                   5825:                     }
                   5826:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5827:                         $no_ownblock = 1;
                   5828:                         last;
                   5829:                     }
                   5830:                 }
                   5831:             }
                   5832:             # if they have 'evb' priv and are currently not playing student
                   5833:             next if (($no_ownblock) &&
                   5834:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5835:         }
1.474     raeburn  5836:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5837:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5838:             if ($sec ne 'none') {
1.482     raeburn  5839:                 $checkrole .= '/'.$sec;
1.474     raeburn  5840:             }
1.490     raeburn  5841:             if ($otheruser) {
                   5842:                 # Resource belongs to user other than current user.
                   5843:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5844:                 my (%allroles,%userroles);
                   5845:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5846:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5847:                         my ($trole,$tdom,$tnum,$tsec);
                   5848:                         if ($entry =~ /^cr/) {
                   5849:                             ($trole,$tdom,$tnum,$tsec) = 
                   5850:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5851:                         } else {
                   5852:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5853:                         }
                   5854:                         my ($spec,$area,$trest);
                   5855:                         $area = '/'.$tdom.'/'.$tnum;
                   5856:                         $trest = $tnum;
                   5857:                         if ($tsec ne '') {
                   5858:                             $area .= '/'.$tsec;
                   5859:                             $trest .= '/'.$tsec;
                   5860:                         }
                   5861:                         $spec = $trole.'.'.$area;
                   5862:                         if ($trole =~ /^cr/) {
                   5863:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5864:                                                               $tdom,$spec,$trest,$area);
                   5865:                         } else {
                   5866:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5867:                                                                 $tdom,$spec,$trest,$area);
                   5868:                         }
                   5869:                     }
1.1276    raeburn  5870:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5871:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5872:                         if ($1) {
                   5873:                             $no_userblock = 1;
                   5874:                             last;
                   5875:                         }
1.486     raeburn  5876:                     }
                   5877:                 }
1.490     raeburn  5878:             } else {
                   5879:                 # Resource belongs to current user
                   5880:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5881:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5882:                     $no_ownblock = 1;
                   5883:                     last;
                   5884:                 }
1.474     raeburn  5885:             }
                   5886:         }
                   5887:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5888:         next if (($no_ownblock) &&
1.491     albertel 5889:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5890:         next if ($no_userblock);
1.474     raeburn  5891: 
1.1303    raeburn  5892:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5893:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5894: 
1.1062    raeburn  5895:         my ($start,$end,$trigger) = 
1.1347    raeburn  5896:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5897:         if (($start != 0) && 
                   5898:             (($startblock == 0) || ($startblock > $start))) {
                   5899:             $startblock = $start;
1.1062    raeburn  5900:             if ($trigger ne '') {
                   5901:                 $triggerblock = $trigger;
                   5902:             }
1.502     raeburn  5903:         }
                   5904:         if (($end != 0)  &&
                   5905:             (($endblock == 0) || ($endblock < $end))) {
                   5906:             $endblock = $end;
1.1062    raeburn  5907:             if ($trigger ne '') {
                   5908:                 $triggerblock = $trigger;
                   5909:             }
1.502     raeburn  5910:         }
1.490     raeburn  5911:     }
1.1062    raeburn  5912:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5913: }
                   5914: 
                   5915: sub get_blocks {
1.1347    raeburn  5916:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5917:     my $startblock = 0;
                   5918:     my $endblock = 0;
1.1062    raeburn  5919:     my $triggerblock = '';
1.490     raeburn  5920:     my $course = $cdom.'_'.$cnum;
                   5921:     $setters->{$course} = {};
                   5922:     $setters->{$course}{'staff'} = [];
                   5923:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5924:     $setters->{$course}{'triggers'} = [];
                   5925:     my (@blockers,%triggered);
                   5926:     my $now = time;
                   5927:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5928:     if ($activity eq 'docs') {
1.1348    raeburn  5929:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5930:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5931:             $blocked = 1;
                   5932:             $nosymbcache = 1;
1.1348    raeburn  5933:             $noenccheck = 1;
1.1347    raeburn  5934:         }
1.1348    raeburn  5935:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5936:         foreach my $block (@blockers) {
                   5937:             if ($block =~ /^firstaccess____(.+)$/) {
                   5938:                 my $item = $1;
                   5939:                 my $type = 'map';
                   5940:                 my $timersymb = $item;
                   5941:                 if ($item eq 'course') {
                   5942:                     $type = 'course';
                   5943:                 } elsif ($item =~ /___\d+___/) {
                   5944:                     $type = 'resource';
                   5945:                 } else {
                   5946:                     $timersymb = &Apache::lonnet::symbread($item);
                   5947:                 }
                   5948:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5949:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5950:                 $triggered{$block} = {
                   5951:                                        start => $start,
                   5952:                                        end   => $end,
                   5953:                                        type  => $type,
                   5954:                                      };
                   5955:             }
                   5956:         }
                   5957:     } else {
                   5958:         foreach my $block (keys(%commblocks)) {
                   5959:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5960:                 my ($start,$end) = ($1,$2);
                   5961:                 if ($start <= time && $end >= time) {
                   5962:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5963:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5964:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5965:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5966:                                     push(@blockers,$block);
                   5967:                                 }
                   5968:                             }
                   5969:                         }
                   5970:                     }
                   5971:                 }
                   5972:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5973:                 my $item = $1;
                   5974:                 my $timersymb = $item; 
                   5975:                 my $type = 'map';
                   5976:                 if ($item eq 'course') {
                   5977:                     $type = 'course';
                   5978:                 } elsif ($item =~ /___\d+___/) {
                   5979:                     $type = 'resource';
                   5980:                 } else {
                   5981:                     $timersymb = &Apache::lonnet::symbread($item);
                   5982:                 }
                   5983:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5984:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5985:                 if ($start && $end) {
                   5986:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5987:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5988:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5989:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5990:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5991:                                         push(@blockers,$block);
                   5992:                                         $triggered{$block} = {
                   5993:                                                                start => $start,
                   5994:                                                                end   => $end,
                   5995:                                                                type  => $type,
                   5996:                                                              };
                   5997:                                     }
                   5998:                                 }
                   5999:                             }
1.1062    raeburn  6000:                         }
                   6001:                     }
1.490     raeburn  6002:                 }
1.1062    raeburn  6003:             }
                   6004:         }
                   6005:     }
                   6006:     foreach my $blocker (@blockers) {
                   6007:         my ($staff_name,$staff_dom,$title,$blocks) =
                   6008:             &parse_block_record($commblocks{$blocker});
                   6009:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   6010:         my ($start,$end,$triggertype);
                   6011:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   6012:             ($start,$end) = ($1,$2);
                   6013:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   6014:             $start = $triggered{$blocker}{'start'};
                   6015:             $end = $triggered{$blocker}{'end'};
                   6016:             $triggertype = $triggered{$blocker}{'type'};
                   6017:         }
                   6018:         if ($start) {
                   6019:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   6020:             if ($triggertype) {
                   6021:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   6022:             } else {
                   6023:                 push(@{$$setters{$course}{'triggers'}},0);
                   6024:             }
                   6025:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   6026:                 $startblock = $start;
                   6027:                 if ($triggertype) {
                   6028:                     $triggerblock = $blocker;
1.474     raeburn  6029:                 }
                   6030:             }
1.1062    raeburn  6031:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   6032:                $endblock = $end;
                   6033:                if ($triggertype) {
                   6034:                    $triggerblock = $blocker;
                   6035:                }
                   6036:             }
1.474     raeburn  6037:         }
                   6038:     }
1.1062    raeburn  6039:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  6040: }
                   6041: 
                   6042: sub parse_block_record {
                   6043:     my ($record) = @_;
                   6044:     my ($setuname,$setudom,$title,$blocks);
                   6045:     if (ref($record) eq 'HASH') {
                   6046:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   6047:         $title = &unescape($record->{'event'});
                   6048:         $blocks = $record->{'blocks'};
                   6049:     } else {
                   6050:         my @data = split(/:/,$record,3);
                   6051:         if (scalar(@data) eq 2) {
                   6052:             $title = $data[1];
                   6053:             ($setuname,$setudom) = split(/@/,$data[0]);
                   6054:         } else {
                   6055:             ($setuname,$setudom,$title) = @data;
                   6056:         }
                   6057:         $blocks = { 'com' => 'on' };
                   6058:     }
                   6059:     return ($setuname,$setudom,$title,$blocks);
                   6060: }
                   6061: 
1.854     kalberla 6062: sub blocking_status {
1.1372    raeburn  6063:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  6064:     my %setters;
1.890     droeschl 6065: 
1.1061    raeburn  6066: # check for active blocking
1.1372    raeburn  6067:     if ($clientip eq '') {
                   6068:         $clientip = &Apache::lonnet::get_requestor_ip();
                   6069:     }
                   6070:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   6071:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  6072:     my $blocked = 0;
1.1372    raeburn  6073:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  6074:         $blocked = 1;
                   6075:     }
1.890     droeschl 6076: 
1.1061    raeburn  6077: # caller just wants to know whether a block is active
                   6078:     if (!wantarray) { return $blocked; }
                   6079: 
                   6080: # build a link to a popup window containing the details
                   6081:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6082: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6083:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6084:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6085:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6086:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6087:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6088:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6089:         if ($symb) {
                   6090:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6091:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6092:         }
1.1062    raeburn  6093:     }
1.1061    raeburn  6094: 
                   6095:     my $output .= <<'END_MYBLOCK';
                   6096: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6097:     var options = "width=" + w + ",height=" + h + ",";
                   6098:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6099:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6100:     var newWin = window.open(url, wdwName, options);
                   6101:     newWin.focus();
                   6102: }
1.890     droeschl 6103: END_MYBLOCK
1.854     kalberla 6104: 
1.1061    raeburn  6105:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6106:   
1.1061    raeburn  6107:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6108:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6109:     my $class = 'LC_comblock';
1.1062    raeburn  6110:     if ($activity eq 'docs') {
                   6111:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6112:         $class = '';
1.1063    raeburn  6113:     } elsif ($activity eq 'printout') {
                   6114:         $text = &mt('Printing Blocked');
1.1232    raeburn  6115:     } elsif ($activity eq 'passwd') {
                   6116:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6117:     } elsif ($activity eq 'grades') {
                   6118:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6119:     } elsif ($activity eq 'search') {
                   6120:         $text = &mt('Search Blocked');
1.1282    raeburn  6121:     } elsif ($activity eq 'alert') {
                   6122:         $text = &mt('Checking Critical Messages Blocked');
                   6123:     } elsif ($activity eq 'reinit') {
                   6124:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6125:     } elsif ($activity eq 'about') {
                   6126:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6127:     } elsif ($activity eq 'wishlist') {
                   6128:         $text = &mt('Access to Stored Links Blocked');
                   6129:     } elsif ($activity eq 'annotate') {
                   6130:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6131:     }
1.1061    raeburn  6132:     $output .= <<"END_BLOCK";
1.1217    raeburn  6133: <div class='$class'>
1.869     kalberla 6134:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6135:   title='$text'>
                   6136:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
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'>$text</a>
1.867     kalberla 6139: </div>
                   6140: 
                   6141: END_BLOCK
1.474     raeburn  6142: 
1.1061    raeburn  6143:     return ($blocked, $output);
1.854     kalberla 6144: }
1.490     raeburn  6145: 
1.60      matthew  6146: ###############################################
                   6147: 
1.682     raeburn  6148: sub check_ip_acc {
1.1201    raeburn  6149:     my ($acc,$clientip)=@_;
1.682     raeburn  6150:     &Apache::lonxml::debug("acc is $acc");
                   6151:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6152:         return 1;
                   6153:     }
1.1339    raeburn  6154:     my ($ip,$allowed);
                   6155:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6156:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6157:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6158:     } else {
1.1350    raeburn  6159:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6160:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6161:     }
1.682     raeburn  6162: 
                   6163:     my $name;
1.1219    raeburn  6164:     my %access = (
                   6165:                      allowfrom => 1,
                   6166:                      denyfrom  => 0,
                   6167:                  );
                   6168:     my @allows;
                   6169:     my @denies;
                   6170:     foreach my $item (split(',',$acc)) {
                   6171:         $item =~ s/^\s*//;
                   6172:         $item =~ s/\s*$//;
                   6173:         my $pattern;
                   6174:         if ($item =~ /^\!(.+)$/) {
                   6175:             push(@denies,$1);
                   6176:         } else {
                   6177:             push(@allows,$item);
                   6178:         }
                   6179:    }
                   6180:    my $numdenies = scalar(@denies);
                   6181:    my $numallows = scalar(@allows);
                   6182:    my $count = 0;
                   6183:    foreach my $pattern (@denies,@allows) {
                   6184:         $count ++; 
                   6185:         my $acctype = 'allowfrom';
                   6186:         if ($count <= $numdenies) {
                   6187:             $acctype = 'denyfrom';
                   6188:         }
1.682     raeburn  6189:         if ($pattern =~ /\*$/) {
                   6190:             #35.8.*
                   6191:             $pattern=~s/\*//;
1.1219    raeburn  6192:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6193:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6194:             #35.8.3.[34-56]
                   6195:             my $low=$2;
                   6196:             my $high=$3;
                   6197:             $pattern=$1;
                   6198:             if ($ip =~ /^\Q$pattern\E/) {
                   6199:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6200:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6201:             }
                   6202:         } elsif ($pattern =~ /^\*/) {
                   6203:             #*.msu.edu
                   6204:             $pattern=~s/\*//;
                   6205:             if (!defined($name)) {
                   6206:                 use Socket;
                   6207:                 my $netaddr=inet_aton($ip);
                   6208:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6209:             }
1.1219    raeburn  6210:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6211:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6212:             #127.0.0.1
1.1219    raeburn  6213:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6214:         } else {
                   6215:             #some.name.com
                   6216:             if (!defined($name)) {
                   6217:                 use Socket;
                   6218:                 my $netaddr=inet_aton($ip);
                   6219:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6220:             }
1.1219    raeburn  6221:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6222:         }
                   6223:         if ($allowed =~ /^(0|1)$/) { last; }
                   6224:     }
                   6225:     if ($allowed eq '') {
                   6226:         if ($numdenies && !$numallows) {
                   6227:             $allowed = 1;
                   6228:         } else {
                   6229:             $allowed = 0;
1.682     raeburn  6230:         }
                   6231:     }
                   6232:     return $allowed;
                   6233: }
                   6234: 
                   6235: ###############################################
                   6236: 
1.60      matthew  6237: =pod
                   6238: 
1.112     bowersj2 6239: =head1 Domain Template Functions
                   6240: 
                   6241: =over 4
                   6242: 
                   6243: =item * &determinedomain()
1.60      matthew  6244: 
                   6245: Inputs: $domain (usually will be undef)
                   6246: 
1.63      www      6247: Returns: Determines which domain should be used for designs
1.60      matthew  6248: 
                   6249: =cut
1.54      www      6250: 
1.60      matthew  6251: ###############################################
1.63      www      6252: sub determinedomain {
                   6253:     my $domain=shift;
1.531     albertel 6254:     if (! $domain) {
1.60      matthew  6255:         # Determine domain if we have not been given one
1.893     raeburn  6256:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6257:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6258:         if ($env{'request.role.domain'}) { 
                   6259:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6260:         }
                   6261:     }
1.63      www      6262:     return $domain;
                   6263: }
                   6264: ###############################################
1.517     raeburn  6265: 
1.518     albertel 6266: sub devalidate_domconfig_cache {
                   6267:     my ($udom)=@_;
                   6268:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6269: }
                   6270: 
                   6271: # ---------------------- Get domain configuration for a domain
                   6272: sub get_domainconf {
                   6273:     my ($udom) = @_;
                   6274:     my $cachetime=1800;
                   6275:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6276:     if (defined($cached)) { return %{$result}; }
                   6277: 
                   6278:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6279: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6280:     my (%designhash,%legacy);
1.518     albertel 6281:     if (keys(%domconfig) > 0) {
                   6282:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6283:             if (keys(%{$domconfig{'login'}})) {
                   6284:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6285:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6286:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6287:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6288:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6289:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6290:                                         if ($key eq 'loginvia') {
                   6291:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6292:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6293:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6294:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6295: 
                   6296:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6297:                                                 } else {
                   6298:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6299:                                                 }
1.948     raeburn  6300:                                             }
1.1208    raeburn  6301:                                         } elsif ($key eq 'headtag') {
                   6302:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6303:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6304:                                             }
1.946     raeburn  6305:                                         }
1.1208    raeburn  6306:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6307:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6308:                                         }
1.946     raeburn  6309:                                     }
                   6310:                                 }
                   6311:                             }
1.1366    raeburn  6312:                         } elsif ($key eq 'saml') {
                   6313:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6314:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6315:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6316:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6317:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6318:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6319:                                         }
                   6320:                                     }
                   6321:                                 }
                   6322:                             }
1.946     raeburn  6323:                         } else {
                   6324:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6325:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6326:                                     $domconfig{'login'}{$key}{$img};
                   6327:                             }
1.699     raeburn  6328:                         }
                   6329:                     } else {
                   6330:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6331:                     }
1.632     raeburn  6332:                 }
                   6333:             } else {
                   6334:                 $legacy{'login'} = 1;
1.518     albertel 6335:             }
1.632     raeburn  6336:         } else {
                   6337:             $legacy{'login'} = 1;
1.518     albertel 6338:         }
                   6339:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6340:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6341:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6342:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6343:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6344:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6345:                         }
1.518     albertel 6346:                     }
                   6347:                 }
1.632     raeburn  6348:             } else {
                   6349:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6350:             }
1.632     raeburn  6351:         } else {
                   6352:             $legacy{'rolecolors'} = 1;
1.518     albertel 6353:         }
1.948     raeburn  6354:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6355:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6356:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6357:             }
                   6358:         }
1.632     raeburn  6359:         if (keys(%legacy) > 0) {
                   6360:             my %legacyhash = &get_legacy_domconf($udom);
                   6361:             foreach my $item (keys(%legacyhash)) {
                   6362:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6363:                     if ($legacy{'login'}) { 
                   6364:                         $designhash{$item} = $legacyhash{$item};
                   6365:                     }
                   6366:                 } else {
                   6367:                     if ($legacy{'rolecolors'}) {
                   6368:                         $designhash{$item} = $legacyhash{$item};
                   6369:                     }
1.518     albertel 6370:                 }
                   6371:             }
                   6372:         }
1.632     raeburn  6373:     } else {
                   6374:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6375:     }
                   6376:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6377: 				  $cachetime);
                   6378:     return %designhash;
                   6379: }
                   6380: 
1.632     raeburn  6381: sub get_legacy_domconf {
                   6382:     my ($udom) = @_;
                   6383:     my %legacyhash;
                   6384:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6385:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6386:     if (-e $designfile) {
1.1317    raeburn  6387:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6388:             while (my $line = <$fh>) {
                   6389:                 next if ($line =~ /^\#/);
                   6390:                 chomp($line);
                   6391:                 my ($key,$val)=(split(/\=/,$line));
                   6392:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6393:             }
                   6394:             close($fh);
                   6395:         }
                   6396:     }
1.1026    raeburn  6397:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6398:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6399:     }
                   6400:     return %legacyhash;
                   6401: }
                   6402: 
1.63      www      6403: =pod
                   6404: 
1.112     bowersj2 6405: =item * &domainlogo()
1.63      www      6406: 
                   6407: Inputs: $domain (usually will be undef)
                   6408: 
                   6409: Returns: A link to a domain logo, if the domain logo exists.
                   6410: If the domain logo does not exist, a description of the domain.
                   6411: 
                   6412: =cut
1.112     bowersj2 6413: 
1.63      www      6414: ###############################################
                   6415: sub domainlogo {
1.517     raeburn  6416:     my $domain = &determinedomain(shift);
1.518     albertel 6417:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6418:     # See if there is a logo
                   6419:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6420:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6421:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6422: 	    if ($imgsrc =~ m{^/res/}) {
                   6423: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6424: 		&Apache::lonnet::repcopy($local_name);
                   6425: 	    }
                   6426: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6427:         }
                   6428:         my $alttext = $domain;
                   6429:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6430:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6431:         }
                   6432:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6433:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6434:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6435:     } else {
1.60      matthew  6436:         return '';
1.59      www      6437:     }
                   6438: }
1.63      www      6439: ##############################################
                   6440: 
                   6441: =pod
                   6442: 
1.112     bowersj2 6443: =item * &designparm()
1.63      www      6444: 
                   6445: Inputs: $which parameter; $domain (usually will be undef)
                   6446: 
                   6447: Returns: value of designparamter $which
                   6448: 
                   6449: =cut
1.112     bowersj2 6450: 
1.397     albertel 6451: 
1.400     albertel 6452: ##############################################
1.397     albertel 6453: sub designparm {
                   6454:     my ($which,$domain)=@_;
                   6455:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6456:         return $env{'environment.color.'.$which};
1.96      www      6457:     }
1.63      www      6458:     $domain=&determinedomain($domain);
1.1016    raeburn  6459:     my %domdesign;
                   6460:     unless ($domain eq 'public') {
                   6461:         %domdesign = &get_domainconf($domain);
                   6462:     }
1.520     raeburn  6463:     my $output;
1.517     raeburn  6464:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6465:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6466:     } else {
1.520     raeburn  6467:         $output = $defaultdesign{$which};
                   6468:     }
                   6469:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6470:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6471:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6472:             if ($output =~ m{^/res/}) {
                   6473:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6474:                 &Apache::lonnet::repcopy($local_name);
                   6475:             }
1.520     raeburn  6476:             $output = &lonhttpdurl($output);
                   6477:         }
1.63      www      6478:     }
1.520     raeburn  6479:     return $output;
1.63      www      6480: }
1.59      www      6481: 
1.822     bisitz   6482: ##############################################
                   6483: =pod
                   6484: 
1.832     bisitz   6485: =item * &authorspace()
                   6486: 
1.1028    raeburn  6487: Inputs: $url (usually will be undef).
1.832     bisitz   6488: 
1.1132    raeburn  6489: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6490:          directory being viewed (or for which action is being taken). 
                   6491:          If $url is provided, and begins /priv/<domain>/<uname>
                   6492:          the path will be that portion of the $context argument.
                   6493:          Otherwise the path will be for the author space of the current
                   6494:          user when the current role is author, or for that of the 
                   6495:          co-author/assistant co-author space when the current role 
                   6496:          is co-author or assistant co-author.
1.832     bisitz   6497: 
                   6498: =cut
                   6499: 
                   6500: sub authorspace {
1.1028    raeburn  6501:     my ($url) = @_;
                   6502:     if ($url ne '') {
                   6503:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6504:            return $1;
                   6505:         }
                   6506:     }
1.832     bisitz   6507:     my $caname = '';
1.1024    www      6508:     my $cadom = '';
1.1028    raeburn  6509:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6510:         ($cadom,$caname) =
1.832     bisitz   6511:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6512:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6513:         $caname = $env{'user.name'};
1.1024    www      6514:         $cadom = $env{'user.domain'};
1.832     bisitz   6515:     }
1.1028    raeburn  6516:     if (($caname ne '') && ($cadom ne '')) {
                   6517:         return "/priv/$cadom/$caname/";
                   6518:     }
                   6519:     return;
1.832     bisitz   6520: }
                   6521: 
                   6522: ##############################################
                   6523: =pod
                   6524: 
1.822     bisitz   6525: =item * &head_subbox()
                   6526: 
                   6527: Inputs: $content (contains HTML code with page functions, etc.)
                   6528: 
                   6529: Returns: HTML div with $content
                   6530:          To be included in page header
                   6531: 
                   6532: =cut
                   6533: 
                   6534: sub head_subbox {
                   6535:     my ($content)=@_;
                   6536:     my $output =
1.993     raeburn  6537:         '<div class="LC_head_subbox">'
1.822     bisitz   6538:        .$content
                   6539:        .'</div>'
                   6540: }
                   6541: 
                   6542: ##############################################
                   6543: =pod
                   6544: 
                   6545: =item * &CSTR_pageheader()
                   6546: 
1.1026    raeburn  6547: Input: (optional) filename from which breadcrumb trail is built.
                   6548:        In most cases no input as needed, as $env{'request.filename'}
                   6549:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6550:        frameset flag
                   6551:        If page header is being requested for use in a frameset, then
                   6552:        the second (option) argument -- frameset will be true, and
                   6553:        the target attribute set for links should be target="_parent".
1.1433    raeburn  6554:        If $title is supplied as the third arg, that will be used to 
1.1407    raeburn  6555:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6556: 
                   6557: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6558:          To be included on Authoring Space pages
1.822     bisitz   6559: 
                   6560: =cut
                   6561: 
                   6562: sub CSTR_pageheader {
1.1407    raeburn  6563:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6564:     if ($trailfile eq '') {
                   6565:         $trailfile = $env{'request.filename'};
                   6566:     }
                   6567: 
                   6568: # this is for resources; directories have customtitle, and crumbs
                   6569: # and select recent are created in lonpubdir.pm
                   6570: 
                   6571:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6572:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6573:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6574:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6575:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6576: 
                   6577:     my $parentpath = '';
                   6578:     my $lastitem = '';
                   6579:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6580:         $parentpath = $1;
                   6581:         $lastitem = $2;
                   6582:     } else {
                   6583:         $lastitem = $thisdisfn;
                   6584:     }
1.921     bisitz   6585: 
1.1406    raeburn  6586:     my $crsauthor;
1.1246    raeburn  6587:     if (($env{'request.course.id'}) &&
                   6588:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6589:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6590:         $crsauthor = 1;
1.1406    raeburn  6591:         if ($title eq '') {
                   6592:             $title = &mt('Course Authoring Space');
                   6593:         }
                   6594:     } elsif ($title eq '') {
1.1246    raeburn  6595:         $title = &mt('Authoring Space');
                   6596:     }
                   6597: 
1.1379    raeburn  6598:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6599:     if ($frameset) {
                   6600:         $target = ' target="_parent"';
                   6601:         $crumbtarget = '_parent';
                   6602:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6603:         $target = '';
                   6604:         $crumbtarget = '';
1.1379    raeburn  6605:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6606:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6607:         $crumbtarget = $env{'request.deeplink.target'};
                   6608:     }
1.1313    raeburn  6609: 
1.921     bisitz   6610:     my $output =
1.1407    raeburn  6611:          '<div>'
1.822     bisitz   6612:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6613:         .'<b>'.$title.'</b> '
1.1314    raeburn  6614:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6615:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6616: 
                   6617:     if ($lastitem) {
                   6618:         $output .=
                   6619:              '<span class="LC_filename">'
                   6620:             .$lastitem
                   6621:             .'</span>';
                   6622:     }
1.1245    raeburn  6623: 
1.1246    raeburn  6624:     if ($crsauthor) {
1.1379    raeburn  6625:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6626:     } else {
                   6627:         $output .=
                   6628:              '<br />'
1.1314    raeburn  6629:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6630:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6631:             .'</form>'
1.1379    raeburn  6632:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6633:     }
1.1407    raeburn  6634:     $output .= '</div>';
1.921     bisitz   6635: 
                   6636:     return $output;
1.822     bisitz   6637: }
                   6638: 
1.1419    raeburn  6639: ##############################################
                   6640: =pod
                   6641: 
                   6642: =item * &nocodemirror()
                   6643: 
                   6644: Input: None
                   6645: 
                   6646: Returns: 1 if CodeMirror is deactivated based on
                   6647:          user's preference, or domain default,
                   6648:          if user indicated use of default.
                   6649: 
                   6650: =cut
                   6651: 
1.1416    raeburn  6652: sub nocodemirror {
                   6653:     my $nocodem = $env{'environment.nocodemirror'};
                   6654:     unless ($nocodem) {
                   6655:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6656:         if ($domdefs{'nocodemirror'}) {
                   6657:             $nocodem = 'yes';
                   6658:         }
                   6659:     }
1.1417    raeburn  6660:     if ($nocodem eq 'yes') {
                   6661:         return 1;
                   6662:     }
                   6663:     return;
1.1416    raeburn  6664: }
                   6665: 
1.1419    raeburn  6666: ##############################################
                   6667: =pod
                   6668: 
                   6669: =item * &permitted_editors()
                   6670: 
1.1422    raeburn  6671: Input: $uri (optional)
1.1419    raeburn  6672: 
                   6673: Returns: %editors hash in which keys are editors
1.1429    raeburn  6674:          permitted in current Authoring Space,
                   6675:          or in current course for web pages
                   6676:          created in a course.
                   6677: 
1.1419    raeburn  6678:          Value for each key is 1. Possible keys
1.1429    raeburn  6679:          are: edit, xml, and daxe.
                   6680: 
                   6681:          For a regular Authoring Space, if no specific
1.1419    raeburn  6682:          set of editors has been set for the Author
                   6683:          who owns the Authoring Space, then the
                   6684:          domain default will be used.  If no domain
                   6685:          default has been set, then the keys will be
                   6686:          edit and xml.
                   6687: 
1.1429    raeburn  6688:          For a course author, or for web pages created
                   6689:          in a course, if no specific set of editors has
                   6690:          been set for the course, then the domain
                   6691:          course default will be used. If no domain
                   6692:          course default has been set, then the keys
                   6693:          will be edit and xml.
                   6694: 
1.1419    raeburn  6695: =cut
                   6696: 
1.1418    raeburn  6697: sub permitted_editors {
1.1422    raeburn  6698:     my ($uri) = @_;
1.1429    raeburn  6699:     my ($is_author,$is_coauthor,$is_course,$auname,$audom,%editors);
1.1418    raeburn  6700:     if ($env{'request.role'} =~ m{^au\./}) {
                   6701:         $is_author = 1;
                   6702:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6703:         ($audom,$auname) = ($1,$2);
                   6704:         if (($audom ne '') && ($auname ne '')) {
                   6705:             if (($env{'user.domain'} eq $audom) &&
                   6706:                 ($env{'user.name'} eq $auname)) {
                   6707:                 $is_author = 1;
                   6708:             } else {
                   6709:                 $is_coauthor = 1;
                   6710:             }
                   6711:         }
                   6712:     } elsif ($env{'request.course.id'}) {
1.1429    raeburn  6713:         my ($cdom,$cnum);
                   6714:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6715:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6716:         if (($env{'request.editurl'} =~ m{^/priv/\Q$cdom/$cnum\E/}) ||
1.1430    raeburn  6717:             ($env{'request.editurl'} =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}) ||
                   6718:             ($uri =~ m{^/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/})) {
1.1429    raeburn  6719:             $is_course = 1;
                   6720:         } elsif ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
1.1418    raeburn  6721:             ($audom,$auname) = ($1,$2);
                   6722:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6723:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6724:         } elsif (($uri eq '/daxesave') &&
1.1429    raeburn  6725:                  (($env{'form.path'} =~ m{^/daxeopen/priv/\Q$cdom/$cnum\E/}) ||
                   6726:                   ($env{'form.path'} =~ m{^/daxeopen/uploaded/\Q$cdom/$cnum\E/(docs|supplemental)/}))) {
                   6727:             $is_course = 1;
                   6728:         } elsif (($uri eq '/daxesave') &&
1.1422    raeburn  6729:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6730:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6731:         }
1.1429    raeburn  6732:         unless ($is_course) {
                   6733:             if (($audom ne '') && ($auname ne '')) {
                   6734:                 if (($env{'user.domain'} eq $audom) &&
                   6735:                     ($env{'user.name'} eq $auname)) {
                   6736:                     $is_author = 1;
                   6737:                 } else {
                   6738:                     $is_coauthor = 1;
                   6739:                 }
1.1418    raeburn  6740:             }
                   6741:         }
                   6742:     }
                   6743:     if ($is_author) {
                   6744:         if (exists($env{'environment.editors'})) {
                   6745:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6746:         } else {
                   6747:             %editors = ( edit => 1,
                   6748:                          xml => 1,
                   6749:                        );
                   6750:         }
                   6751:     } elsif ($is_coauthor) {
                   6752:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6753:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6754:         } else {
                   6755:             %editors = ( edit => 1,
                   6756:                          xml => 1,
                   6757:                        );
                   6758:         }
1.1429    raeburn  6759:     } elsif ($is_course) {
                   6760:         if (exists($env{'course.'.$env{'request.course.id'}.'.internal.crseditors'})) {
                   6761:             map { $editors{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.crseditors'});
                   6762:         } else {
                   6763:             my %domdefaults = &Apache::lonnet::get_domain_defaults($env{'course.'.$env{'request.course.id'}.'.domain'});
                   6764:             if (exists($domdefaults{'crseditors'})) {
                   6765:                 map { $editors{$_} = 1; } split(/,/,$domdefaults{'crseditors'});
                   6766:             } else {
                   6767:                 %editors = ( edit => 1,
                   6768:                              xml => 1,
                   6769:                            );
                   6770:             }
                   6771:         }
1.1418    raeburn  6772:     } else {
                   6773:         %editors = ( edit => 1,
                   6774:                      xml => 1,
                   6775:                    );
                   6776:     }
                   6777:     return %editors;
                   6778: }
                   6779: 
1.60      matthew  6780: ###############################################
                   6781: ###############################################
                   6782: 
                   6783: =pod
                   6784: 
1.112     bowersj2 6785: =back
                   6786: 
1.549     albertel 6787: =head1 HTML Helpers
1.112     bowersj2 6788: 
                   6789: =over 4
                   6790: 
                   6791: =item * &bodytag()
1.60      matthew  6792: 
                   6793: Returns a uniform header for LON-CAPA web pages.
                   6794: 
                   6795: Inputs: 
                   6796: 
1.112     bowersj2 6797: =over 4
                   6798: 
                   6799: =item * $title, A title to be displayed on the page.
                   6800: 
                   6801: =item * $function, the current role (can be undef).
                   6802: 
                   6803: =item * $addentries, extra parameters for the <body> tag.
                   6804: 
                   6805: =item * $bodyonly, if defined, only return the <body> tag.
                   6806: 
                   6807: =item * $domain, if defined, force a given domain.
                   6808: 
                   6809: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6810:             text interface only)
1.60      matthew  6811: 
1.814     bisitz   6812: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6813:                      navigational links
1.317     albertel 6814: 
1.338     albertel 6815: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6816: 
1.460     albertel 6817: =item * $args, optional argument valid values are
                   6818:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6819:             use_absolute     -> for external resource or syllabus, this will
                   6820:                                 contain https://<hostname> if server uses
                   6821:                                 https (as per hosts.tab), but request is for http
                   6822:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6823: 
1.1096    raeburn  6824: =item * $advtoolsref, optional argument, ref to an array containing
                   6825:             inlineremote items to be added in "Functions" menu below
                   6826:             breadcrumbs.
                   6827: 
1.1316    raeburn  6828: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6829:             course, if LON-CAPA is in LTI Provider context. Value is
                   6830:             the scope of use, i.e., launch was for access to a single, a map
                   6831:             or the entire course.
                   6832: 
                   6833: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6834:             context, this will contain the URL for the landing item in
                   6835:             the course, after launch from an LTI Consumer
                   6836: 
1.1318    raeburn  6837: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6838:             context, this will contain a reference to hash of items
                   6839:             to be included in the page header and/or inline menu.
                   6840: 
1.1385    raeburn  6841: =item * $menucoll, optional argument, if specific menu collection is in
                   6842:             effect, either set as the default for the course, or set for
                   6843:             the deeplink paramater for $env{'request.deeplink.login'}
                   6844:             then $menucoll will be the number of that collection. 
                   6845: 
                   6846: =item * $menuref, optional argument, reference to a hash, containing the
                   6847:             menu options included for the menu in effect, based on the
                   6848:             configuration for the numbered menu collection in use.  
                   6849: 
                   6850: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6851:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6852:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6853:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6854:             being called a second time.
                   6855: 
1.112     bowersj2 6856: =back
                   6857: 
1.60      matthew  6858: Returns: A uniform header for LON-CAPA web pages.  
                   6859: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6860: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6861: other decorations will be returned.
                   6862: 
                   6863: =cut
                   6864: 
1.54      www      6865: sub bodytag {
1.831     bisitz   6866:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6867:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6868:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6869: 
1.954     raeburn  6870:     my $public;
                   6871:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6872:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6873:         $public = 1;
                   6874:     }
1.460     albertel 6875:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6876:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6877:     my $hostname = $args->{'hostname'};
1.339     albertel 6878: 
1.183     matthew  6879:     $function = &get_users_function() if (!$function);
1.339     albertel 6880:     my $font =   &designparm($function.'.font',$domain);
                   6881:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6882: 
1.803     bisitz   6883:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6884: 		   'bgcolor' => $pgbg,
1.339     albertel 6885: 		   'text'    => $font,
                   6886:                    'alink'   => &designparm($function.'.alink',$domain),
                   6887: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6888: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6889:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6890: 
1.63      www      6891:  # role and realm
1.1178    raeburn  6892:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6893:     if ($realm) {
                   6894:         $realm = '/'.$realm;
                   6895:     }
1.1357    raeburn  6896:     if ($role eq 'ca') {
1.479     albertel 6897:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6898:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6899:     } 
1.55      www      6900: # realm
1.1357    raeburn  6901:     my ($cid,$sec);
1.258     albertel 6902:     if ($env{'request.course.id'}) {
1.1357    raeburn  6903:         $cid = $env{'request.course.id'};
                   6904:         if ($env{'request.course.sec'}) {
                   6905:             $sec = $env{'request.course.sec'};
                   6906:         }
                   6907:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6908:         if (&Apache::lonnet::is_course($1,$2)) {
                   6909:             $cid = $1.'_'.$2;
                   6910:             $sec = $3;
                   6911:         }
                   6912:     }
                   6913:     if ($cid) {
1.378     raeburn  6914:         if ($env{'request.role'} !~ /^cr/) {
                   6915:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6916:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6917:             if ($env{'request.role.desc'}) {
                   6918:                 $role = $env{'request.role.desc'};
                   6919:             } else {
                   6920:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6921:             }
1.1257    raeburn  6922:         } else {
                   6923:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6924:         }
1.1357    raeburn  6925:         if ($sec) {
                   6926:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6927:         }   
1.1357    raeburn  6928: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6929:     } else {
                   6930:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6931:     }
1.433     albertel 6932: 
1.359     albertel 6933:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6934: 
1.438     albertel 6935:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6936: 
1.101     www      6937: # construct main body tag
1.359     albertel 6938:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6939: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6940: 
1.1131    raeburn  6941:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6942: 
1.1130    raeburn  6943:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6944:         return $bodytag;
1.1130    raeburn  6945:     }
1.359     albertel 6946: 
1.954     raeburn  6947:     if ($public) {
1.433     albertel 6948: 	undef($role);
                   6949:     }
1.1318    raeburn  6950: 
1.1359    raeburn  6951:     my $showcrstitle = 1;
1.1357    raeburn  6952:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6953:         if (ref($ltimenu) eq 'HASH') {
                   6954:             unless ($ltimenu->{'role'}) {
                   6955:                 undef($role);
                   6956:             }
                   6957:             unless ($ltimenu->{'coursetitle'}) {
                   6958:                 $realm='&nbsp;';
1.1359    raeburn  6959:                 $showcrstitle = 0;
                   6960:             }
                   6961:         }
                   6962:     } elsif (($cid) && ($menucoll)) {
                   6963:         if (ref($menuref) eq 'HASH') {
                   6964:             unless ($menuref->{'role'}) {
                   6965:                 undef($role);
                   6966:             }
                   6967:             unless ($menuref->{'crs'}) {
                   6968:                 $realm='&nbsp;';
                   6969:                 $showcrstitle = 0;
1.1318    raeburn  6970:             }
                   6971:         }
                   6972:     }
                   6973: 
1.762     bisitz   6974:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6975:     #
                   6976:     # Extra info if you are the DC
                   6977:     my $dc_info = '';
1.1359    raeburn  6978:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6979:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6980:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6981:         $dc_info =~ s/\s+$//;
1.359     albertel 6982:     }
                   6983: 
1.1237    raeburn  6984:     my $crstype;
1.1357    raeburn  6985:     if ($cid) {
                   6986:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6987:     } elsif ($args->{'crstype'}) {
                   6988:         $crstype = $args->{'crstype'};
                   6989:     }
                   6990:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6991:         undef($role);
                   6992:     } else {
1.1242    raeburn  6993:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6994:     }
1.853     droeschl 6995: 
1.903     droeschl 6996:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6997: 
                   6998:         #    if ($env{'request.state'} eq 'construct') {
                   6999:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   7000:         #    }
                   7001: 
1.1440    raeburn  7002:         my $need_endlcint;
                   7003:         unless ($args->{'switchserver'}) {
                   7004:             $bodytag .= Apache::lonhtmlcommon::scripttag(
                   7005:                 Apache::lonmenu::utilityfunctions($httphost), 'start');
                   7006:             $need_endlcint = 1;
                   7007:         }
1.359     albertel 7008: 
1.1427    raeburn  7009:         my $collapsible;
1.1423    raeburn  7010:         if ($args->{'collapsible_header'} ne '') {
1.1427    raeburn  7011:             $collapsible = 1;
                   7012:             my ($menustate,$tiptext,$divclass);
                   7013:             if ($args->{'start_collapsed'}) {
                   7014:                 $menustate = 'collapsed';
                   7015:                 $tiptext = 'display';
                   7016:                 $divclass = 'hidden';
                   7017:             } else {
                   7018:                 $menustate = 'expanded';
                   7019:                 $tiptext = 'hide';
                   7020:                 $divclass = 'shown';
                   7021:             }
                   7022:             my $alttext = &mt('menu state: '.$menustate);
                   7023:             my $tooltip = &mt($tiptext.' standard menus');
1.1421    raeburn  7024:             $bodytag .= <<"END";
                   7025: <div id="LC_expandingContainer" style="display:inline;">
                   7026: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
1.1427    raeburn  7027: <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>
                   7028: <div class="LC_menus_content $divclass">
1.1421    raeburn  7029: END
                   7030:         }
1.1318    raeburn  7031:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  7032:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  7033:                                                               $args->{'links_disabled'},
1.1421    raeburn  7034:                                                               $args->{'links_target'},
1.1427    raeburn  7035:                                                               $collapsible);
1.359     albertel 7036: 
1.1318    raeburn  7037:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   7038:                 if ($dc_info) {
                   7039:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   7040:                 }
                   7041:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   7042:                                <em>$realm</em> $dc_info</div>|;
1.1440    raeburn  7043:                 if ($need_endlcint) {
                   7044:                     $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7045:                 }
1.1318    raeburn  7046:                 return $bodytag;
                   7047:             }
1.894     droeschl 7048: 
1.1318    raeburn  7049:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   7050:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   7051:             }
1.916     droeschl 7052: 
1.1318    raeburn  7053:             $bodytag .= $right;
1.852     droeschl 7054: 
1.1318    raeburn  7055:             if ($dc_info) {
                   7056:                 $dc_info = &dc_courseid_toggle($dc_info);
                   7057:             }
                   7058:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  7059:         }
1.916     droeschl 7060: 
1.1169    raeburn  7061:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  7062:         if ($args->{'no_secondary_menu'}) {
1.1440    raeburn  7063:             if ($need_endlcint) {
                   7064:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7065:             }
1.1168    raeburn  7066:             return $bodytag;
                   7067:         }
1.1169    raeburn  7068:         #don't show menus for public users
1.954     raeburn  7069:         if (!$public){
1.1318    raeburn  7070:             unless ($args->{'no_inline_menu'}) {
                   7071:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  7072:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  7073:                                                             $menucoll,$menuref,
1.1380    raeburn  7074:                                                             $args->{'links_disabled'},
                   7075:                                                             $args->{'links_target'});
1.1318    raeburn  7076:             }
1.903     droeschl 7077:             $bodytag .= Apache::lonmenu::serverform();
1.1440    raeburn  7078:             if ($need_endlcint) {
                   7079:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7080:             }
1.920     raeburn  7081:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 7082:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  7083:                                 $args->{'bread_crumbs'},'','',$hostname,
                   7084:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7085:             } elsif ($forcereg) {
                   7086:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  7087:                                 $args->{'group'},$args->{'hide_buttons'},
                   7088:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  7089:             } else {
                   7090:                 $bodytag .= 
                   7091:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   7092:                                                         $forcereg,$args->{'group'},
                   7093:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  7094:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  7095:             }
1.1440    raeburn  7096:         } else {
                   7097:             # this is to separate menu from content when there's no secondary
1.1441    raeburn  7098:             # menu. Especially needed for publicly accessible resources.
1.903     droeschl 7099:             $bodytag .= '<hr style="clear:both" />';
1.1440    raeburn  7100:             if ($need_endlcint) {
                   7101:                 $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   7102:             }
1.235     raeburn  7103:         }
1.1423    raeburn  7104:         if ($args->{'collapsible_header'} ne '') {
                   7105:             $bodytag .= $args->{'collapsible_header'}.
                   7106:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  7107:                         '</div></div>';
                   7108:         }
1.235     raeburn  7109:         return $bodytag;
1.182     matthew  7110: }
                   7111: 
1.917     raeburn  7112: sub dc_courseid_toggle {
                   7113:     my ($dc_info) = @_;
1.980     raeburn  7114:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  7115:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  7116:            &mt('(More ...)').'</a></span>'.
                   7117:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   7118: }
                   7119: 
1.330     albertel 7120: sub make_attr_string {
                   7121:     my ($register,$attr_ref) = @_;
                   7122: 
                   7123:     if ($attr_ref && !ref($attr_ref)) {
                   7124: 	die("addentries Must be a hash ref ".
                   7125: 	    join(':',caller(1))." ".
                   7126: 	    join(':',caller(0))." ");
                   7127:     }
                   7128: 
                   7129:     if ($register) {
1.339     albertel 7130: 	my ($on_load,$on_unload);
                   7131: 	foreach my $key (keys(%{$attr_ref})) {
                   7132: 	    if      (lc($key) eq 'onload') {
                   7133: 		$on_load.=$attr_ref->{$key}.';';
                   7134: 		delete($attr_ref->{$key});
                   7135: 
                   7136: 	    } elsif (lc($key) eq 'onunload') {
                   7137: 		$on_unload.=$attr_ref->{$key}.';';
                   7138: 		delete($attr_ref->{$key});
                   7139: 	    }
                   7140: 	}
1.953     droeschl 7141: 	$attr_ref->{'onload'}  = $on_load;
                   7142: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7143:     }
1.339     albertel 7144: 
1.330     albertel 7145:     my $attr_string;
1.1159    raeburn  7146:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7147: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7148:     }
                   7149:     return $attr_string;
                   7150: }
                   7151: 
                   7152: 
1.182     matthew  7153: ###############################################
1.251     albertel 7154: ###############################################
                   7155: 
                   7156: =pod
                   7157: 
                   7158: =item * &endbodytag()
                   7159: 
                   7160: Returns a uniform footer for LON-CAPA web pages.
                   7161: 
1.635     raeburn  7162: Inputs: 1 - optional reference to an args hash
                   7163: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7164: a 'Continue' link is not displayed if the page contains an
                   7165: internal redirect in the <head></head> section,
                   7166: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7167: 
                   7168: =cut
                   7169: 
                   7170: sub endbodytag {
1.635     raeburn  7171:     my ($args) = @_;
1.1080    raeburn  7172:     my $endbodytag;
                   7173:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7174:         $endbodytag='</body>';
                   7175:     }
1.315     albertel 7176:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7177:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7178:             my ($endbodyjs,$idattr);
                   7179:             if ($env{'internal.head.to_opener'}) {
                   7180:                 my $linkid = 'LC_continue_link';
                   7181:                 $idattr = ' id="'.$linkid.'"';
                   7182:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7183:                 $endbodyjs=<<ENDJS;
                   7184: <script type="text/javascript">
                   7185: // <![CDATA[
                   7186: function ebFunction(evt) {
                   7187:     evt.preventDefault();
                   7188:     var dest = '$redirect_for_js';
                   7189:     if (window.opener != null && !window.opener.closed) {
                   7190:         window.opener.location.href=dest;
                   7191:         window.close();
                   7192:     } else {
                   7193:         window.location.href=dest;
                   7194:     }
                   7195:     return false;
                   7196: }
                   7197: 
                   7198: \$(document).ready(function () {
                   7199:   if (document.getElementById('$linkid')) {
                   7200:     var clickelem = document.getElementById('$linkid');
                   7201:     clickelem.addEventListener('click',ebFunction,false);
                   7202:   }
                   7203: });
                   7204: // ]]>
                   7205: </script>
                   7206: ENDJS
                   7207:             }
1.635     raeburn  7208: 	    $endbodytag=
1.1386    raeburn  7209: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7210: 	        &mt('Continue').'</a>'.
                   7211: 	        $endbodytag;
                   7212:         }
1.315     albertel 7213:     }
1.1411    raeburn  7214:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7215:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7216:     }
1.251     albertel 7217:     return $endbodytag;
                   7218: }
                   7219: 
1.352     albertel 7220: =pod
                   7221: 
                   7222: =item * &standard_css()
                   7223: 
                   7224: Returns a style sheet
                   7225: 
                   7226: Inputs: (all optional)
                   7227:             domain         -> force to color decorate a page for a specific
                   7228:                                domain
                   7229:             function       -> force usage of a specific rolish color scheme
                   7230:             bgcolor        -> override the default page bgcolor
                   7231: 
                   7232: =cut
                   7233: 
1.343     albertel 7234: sub standard_css {
1.345     albertel 7235:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7236:     $function  = &get_users_function() if (!$function);
                   7237:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7238:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7239:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7240: #second colour for later usage
1.345     albertel 7241:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7242:     my $pgbg_or_bgcolor =
                   7243: 	         $bgcolor ||
1.352     albertel 7244: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7245:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7246:     my $alink  = &designparm($function.'.alink', $domain);
                   7247:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7248:     my $link   = &designparm($function.'.link',  $domain);
                   7249: 
1.602     albertel 7250:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7251:     my $mono                 = 'monospace';
1.850     bisitz   7252:     my $data_table_head      = $sidebg;
                   7253:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7254:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7255:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7256:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7257:     my $mail_new             = '#FFBB77';
                   7258:     my $mail_new_hover       = '#DD9955';
                   7259:     my $mail_read            = '#BBBB77';
                   7260:     my $mail_read_hover      = '#999944';
                   7261:     my $mail_replied         = '#AAAA88';
                   7262:     my $mail_replied_hover   = '#888855';
                   7263:     my $mail_other           = '#99BBBB';
                   7264:     my $mail_other_hover     = '#669999';
1.391     albertel 7265:     my $table_header         = '#DDDDDD';
1.489     raeburn  7266:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7267:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7268:     my $button_hover         = '#BF2317';
1.392     albertel 7269: 
1.608     albertel 7270:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7271:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7272:                                              : '0 3px 0 4px';
1.448     albertel 7273: 
1.523     albertel 7274: 
1.343     albertel 7275:     return <<END;
1.947     droeschl 7276: 
                   7277: /* needed for iframe to allow 100% height in FF */
                   7278: body, html { 
                   7279:     margin: 0;
                   7280:     padding: 0 0.5%;
                   7281:     height: 99%; /* to avoid scrollbars */
                   7282: }
                   7283: 
1.795     www      7284: body {
1.911     bisitz   7285:   font-family: $sans;
                   7286:   line-height:130%;
                   7287:   font-size:0.83em;
                   7288:   color:$font;
1.1436    raeburn  7289:   background-color: $pgbg_or_bgcolor;
1.795     www      7290: }
                   7291: 
1.959     onken    7292: a:focus,
                   7293: a:focus img {
1.795     www      7294:   color: red;
                   7295: }
1.698     harmsja  7296: 
1.911     bisitz   7297: form, .inline {
                   7298:   display: inline;
1.795     www      7299: }
1.721     harmsja  7300: 
1.1443  ! raeburn  7301: .LC_visually_hidden:not(:focus):not(:active) {
        !          7302:     clip-path: inset(50%);
        !          7303:     height: 1px;
        !          7304:     overflow: hidden;
        !          7305:     position: absolute;
        !          7306:     white-space: nowrap;
        !          7307:     width: 1px;
        !          7308:     display: inline;
        !          7309: }
        !          7310: 
1.1421    raeburn  7311: .LC_menus_content.shown{
1.1428    raeburn  7312:   display: block;
1.1421    raeburn  7313: }
                   7314: 
                   7315: .LC_menus_content.hidden {
                   7316:   display: none;
                   7317: }
                   7318: 
1.795     www      7319: .LC_right {
1.911     bisitz   7320:   text-align:right;
1.795     www      7321: }
                   7322: 
                   7323: .LC_middle {
1.911     bisitz   7324:   vertical-align:middle;
1.795     www      7325: }
1.721     harmsja  7326: 
1.1130    raeburn  7327: .LC_floatleft {
                   7328:   float: left;
                   7329: }
                   7330: 
                   7331: .LC_floatright {
                   7332:   float: right;
                   7333: }
                   7334: 
1.911     bisitz   7335: .LC_400Box {
                   7336:   width:400px;
                   7337: }
1.721     harmsja  7338: 
1.1421    raeburn  7339: #LC_collapsible_separator {
                   7340:     border: 1px solid black;
                   7341:     width: 99.9%;
                   7342:     height: 0px;
                   7343: }
                   7344: 
1.947     droeschl 7345: .LC_iframecontainer {
                   7346:     width: 98%;
                   7347:     margin: 0;
                   7348:     position: fixed;
                   7349:     top: 8.5em;
                   7350:     bottom: 0;
                   7351: }
                   7352: 
                   7353: .LC_iframecontainer iframe{
                   7354:     border: none;
                   7355:     width: 100%;
                   7356:     height: 100%;
                   7357: }
                   7358: 
1.778     bisitz   7359: .LC_filename {
                   7360:   font-family: $mono;
                   7361:   white-space:pre;
1.921     bisitz   7362:   font-size: 120%;
1.778     bisitz   7363: }
                   7364: 
                   7365: .LC_fileicon {
                   7366:   border: none;
                   7367:   height: 1.3em;
                   7368:   vertical-align: text-bottom;
                   7369:   margin-right: 0.3em;
                   7370:   text-decoration:none;
                   7371: }
                   7372: 
1.1008    www      7373: .LC_setting {
                   7374:   text-decoration:underline;
                   7375: }
                   7376: 
1.350     albertel 7377: .LC_error {
                   7378:   color: red;
                   7379: }
1.795     www      7380: 
1.1097    bisitz   7381: .LC_warning {
                   7382:   color: darkorange;
                   7383: }
                   7384: 
1.457     albertel 7385: .LC_diff_removed {
1.733     bisitz   7386:   color: red;
1.394     albertel 7387: }
1.532     albertel 7388: 
                   7389: .LC_info,
1.457     albertel 7390: .LC_success,
                   7391: .LC_diff_added {
1.350     albertel 7392:   color: green;
                   7393: }
1.795     www      7394: 
1.802     bisitz   7395: div.LC_confirm_box {
                   7396:   background-color: #FAFAFA;
                   7397:   border: 1px solid $lg_border_color;
                   7398:   margin-right: 0;
                   7399:   padding: 5px;
                   7400: }
                   7401: 
                   7402: div.LC_confirm_box .LC_error img,
                   7403: div.LC_confirm_box .LC_success img {
                   7404:   vertical-align: middle;
                   7405: }
                   7406: 
1.1242    raeburn  7407: .LC_maxwidth {
                   7408:   max-width: 100%;
                   7409:   height: auto;
                   7410: }
                   7411: 
1.1243    raeburn  7412: .LC_textsize_mobile {
                   7413:   \@media only screen and (max-device-width: 480px) {
                   7414:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7415:   }
                   7416: }
                   7417: 
1.440     albertel 7418: .LC_icon {
1.771     droeschl 7419:   border: none;
1.790     droeschl 7420:   vertical-align: middle;
1.771     droeschl 7421: }
                   7422: 
1.543     albertel 7423: .LC_docs_spacer {
                   7424:   width: 25px;
                   7425:   height: 1px;
1.771     droeschl 7426:   border: none;
1.543     albertel 7427: }
1.346     albertel 7428: 
1.532     albertel 7429: .LC_internal_info {
1.735     bisitz   7430:   color: #999999;
1.532     albertel 7431: }
                   7432: 
1.794     www      7433: .LC_discussion {
1.1050    www      7434:   background: $data_table_dark;
1.911     bisitz   7435:   border: 1px solid black;
                   7436:   margin: 2px;
1.794     www      7437: }
                   7438: 
                   7439: .LC_disc_action_left {
1.1050    www      7440:   background: $sidebg;
1.911     bisitz   7441:   text-align: left;
1.1050    www      7442:   padding: 4px;
                   7443:   margin: 2px;
1.794     www      7444: }
                   7445: 
                   7446: .LC_disc_action_right {
1.1050    www      7447:   background: $sidebg;
1.911     bisitz   7448:   text-align: right;
1.1050    www      7449:   padding: 4px;
                   7450:   margin: 2px;
1.794     www      7451: }
                   7452: 
                   7453: .LC_disc_new_item {
1.911     bisitz   7454:   background: white;
                   7455:   border: 2px solid red;
1.1050    www      7456:   margin: 4px;
                   7457:   padding: 4px;
1.794     www      7458: }
                   7459: 
                   7460: .LC_disc_old_item {
1.911     bisitz   7461:   background: white;
1.1050    www      7462:   margin: 4px;
                   7463:   padding: 4px;
1.794     www      7464: }
                   7465: 
1.458     albertel 7466: table.LC_pastsubmission {
                   7467:   border: 1px solid black;
                   7468:   margin: 2px;
                   7469: }
                   7470: 
1.924     bisitz   7471: table#LC_menubuttons {
1.345     albertel 7472:   width: 100%;
                   7473:   background: $pgbg;
1.392     albertel 7474:   border: 2px;
1.402     albertel 7475:   border-collapse: separate;
1.803     bisitz   7476:   padding: 0;
1.345     albertel 7477: }
1.392     albertel 7478: 
1.801     tempelho 7479: table#LC_title_bar a {
                   7480:   color: $fontmenu;
                   7481: }
1.836     bisitz   7482: 
1.807     droeschl 7483: table#LC_title_bar {
1.819     tempelho 7484:   clear: both;
1.836     bisitz   7485:   display: none;
1.807     droeschl 7486: }
                   7487: 
1.795     www      7488: table#LC_title_bar,
1.933     droeschl 7489: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7490: table#LC_title_bar.LC_with_remote {
1.359     albertel 7491:   width: 100%;
1.392     albertel 7492:   border-color: $pgbg;
                   7493:   border-style: solid;
                   7494:   border-width: $border;
1.379     albertel 7495:   background: $pgbg;
1.801     tempelho 7496:   color: $fontmenu;
1.392     albertel 7497:   border-collapse: collapse;
1.803     bisitz   7498:   padding: 0;
1.819     tempelho 7499:   margin: 0;
1.359     albertel 7500: }
1.795     www      7501: 
1.933     droeschl 7502: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7503:     margin: 0;
                   7504:     padding: 0;
1.933     droeschl 7505:     position: relative;
                   7506:     list-style: none;
1.913     droeschl 7507: }
1.933     droeschl 7508: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7509:     display: inline;
                   7510: }
1.933     droeschl 7511: 
                   7512: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7513:     padding: 0;
1.933     droeschl 7514:     margin: 0;
                   7515:     float: left;
1.913     droeschl 7516: }
1.933     droeschl 7517: .LC_breadcrumb_tools_tools {
                   7518:     padding: 0;
                   7519:     margin: 0;
1.913     droeschl 7520:     float: right;
                   7521: }
                   7522: 
1.1240    raeburn  7523: .LC_placement_prog {
                   7524:     padding-right: 20px;
                   7525:     font-weight: bold;
                   7526:     font-size: 90%;
                   7527: }
                   7528: 
1.359     albertel 7529: table#LC_title_bar td {
                   7530:   background: $tabbg;
                   7531: }
1.795     www      7532: 
1.911     bisitz   7533: table#LC_menubuttons img {
1.803     bisitz   7534:   border: none;
1.346     albertel 7535: }
1.795     www      7536: 
1.842     droeschl 7537: .LC_breadcrumbs_component {
1.911     bisitz   7538:   float: right;
                   7539:   margin: 0 1em;
1.357     albertel 7540: }
1.842     droeschl 7541: .LC_breadcrumbs_component img {
1.911     bisitz   7542:   vertical-align: middle;
1.777     tempelho 7543: }
1.795     www      7544: 
1.1243    raeburn  7545: .LC_breadcrumbs_hoverable {
                   7546:   background: $sidebg;
                   7547: }
                   7548: 
1.383     albertel 7549: td.LC_table_cell_checkbox {
                   7550:   text-align: center;
                   7551: }
1.795     www      7552: 
                   7553: .LC_fontsize_small {
1.911     bisitz   7554:   font-size: 70%;
1.705     tempelho 7555: }
                   7556: 
1.844     bisitz   7557: #LC_breadcrumbs {
1.911     bisitz   7558:   clear:both;
                   7559:   background: $sidebg;
                   7560:   border-bottom: 1px solid $lg_border_color;
                   7561:   line-height: 2.5em;
1.933     droeschl 7562:   overflow: hidden;
1.911     bisitz   7563:   margin: 0;
                   7564:   padding: 0;
1.995     raeburn  7565:   text-align: left;
1.819     tempelho 7566: }
1.862     bisitz   7567: 
1.1098    bisitz   7568: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7569:   clear:both;
                   7570:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7571:   border: 1px solid $sidebg;
1.1098    bisitz   7572:   margin: 0 0 10px 0;
1.966     bisitz   7573:   padding: 3px;
1.995     raeburn  7574:   text-align: left;
1.822     bisitz   7575: }
                   7576: 
1.795     www      7577: .LC_fontsize_medium {
1.911     bisitz   7578:   font-size: 85%;
1.705     tempelho 7579: }
                   7580: 
1.795     www      7581: .LC_fontsize_large {
1.911     bisitz   7582:   font-size: 120%;
1.705     tempelho 7583: }
                   7584: 
1.346     albertel 7585: .LC_menubuttons_inline_text {
                   7586:   color: $font;
1.698     harmsja  7587:   font-size: 90%;
1.701     harmsja  7588:   padding-left:3px;
1.346     albertel 7589: }
                   7590: 
1.934     droeschl 7591: .LC_menubuttons_inline_text img{
                   7592:   vertical-align: middle;
                   7593: }
                   7594: 
1.1051    www      7595: li.LC_menubuttons_inline_text img {
1.951     onken    7596:   cursor:pointer;
1.1002    droeschl 7597:   text-decoration: none;
1.951     onken    7598: }
                   7599: 
1.526     www      7600: .LC_menubuttons_link {
                   7601:   text-decoration: none;
                   7602: }
1.795     www      7603: 
1.522     albertel 7604: .LC_menubuttons_category {
1.521     www      7605:   color: $font;
1.526     www      7606:   background: $pgbg;
1.521     www      7607:   font-size: larger;
                   7608:   font-weight: bold;
                   7609: }
                   7610: 
1.346     albertel 7611: td.LC_menubuttons_text {
1.911     bisitz   7612:   color: $font;
1.346     albertel 7613: }
1.706     harmsja  7614: 
1.346     albertel 7615: .LC_current_location {
                   7616:   background: $tabbg;
                   7617: }
1.795     www      7618: 
1.1286    raeburn  7619: td.LC_zero_height {
                   7620:   line-height: 0; 
                   7621:   cellpadding: 0;
                   7622: }
                   7623: 
1.938     bisitz   7624: table.LC_data_table {
1.347     albertel 7625:   border: 1px solid #000000;
1.402     albertel 7626:   border-collapse: separate;
1.426     albertel 7627:   border-spacing: 1px;
1.610     albertel 7628:   background: $pgbg;
1.347     albertel 7629: }
1.795     www      7630: 
1.422     albertel 7631: .LC_data_table_dense {
                   7632:   font-size: small;
                   7633: }
1.795     www      7634: 
1.507     raeburn  7635: table.LC_nested_outer {
                   7636:   border: 1px solid #000000;
1.589     raeburn  7637:   border-collapse: collapse;
1.803     bisitz   7638:   border-spacing: 0;
1.507     raeburn  7639:   width: 100%;
                   7640: }
1.795     www      7641: 
1.879     raeburn  7642: table.LC_innerpickbox,
1.507     raeburn  7643: table.LC_nested {
1.803     bisitz   7644:   border: none;
1.589     raeburn  7645:   border-collapse: collapse;
1.803     bisitz   7646:   border-spacing: 0;
1.507     raeburn  7647:   width: 100%;
                   7648: }
1.795     www      7649: 
1.911     bisitz   7650: table.LC_data_table tr th,
                   7651: table.LC_calendar tr th,
1.879     raeburn  7652: table.LC_prior_tries tr th,
                   7653: table.LC_innerpickbox tr th {
1.349     albertel 7654:   font-weight: bold;
                   7655:   background-color: $data_table_head;
1.801     tempelho 7656:   color:$fontmenu;
1.701     harmsja  7657:   font-size:90%;
1.347     albertel 7658: }
1.795     www      7659: 
1.879     raeburn  7660: table.LC_innerpickbox tr th,
                   7661: table.LC_innerpickbox tr td {
                   7662:   vertical-align: top;
                   7663: }
                   7664: 
1.711     raeburn  7665: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7666:   background-color: #CCCCCC;
1.711     raeburn  7667:   font-weight: bold;
                   7668:   text-align: left;
                   7669: }
1.795     www      7670: 
1.912     bisitz   7671: table.LC_data_table tr.LC_odd_row > td {
                   7672:   background-color: $data_table_light;
                   7673:   padding: 2px;
                   7674:   vertical-align: top;
                   7675: }
                   7676: 
1.809     bisitz   7677: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7678:   background-color: $data_table_light;
1.912     bisitz   7679:   vertical-align: top;
                   7680: }
                   7681: 
                   7682: table.LC_data_table tr.LC_even_row > td {
                   7683:   background-color: $data_table_dark;
1.425     albertel 7684:   padding: 2px;
1.900     bisitz   7685:   vertical-align: top;
1.347     albertel 7686: }
1.795     www      7687: 
1.809     bisitz   7688: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7689:   background-color: $data_table_dark;
1.900     bisitz   7690:   vertical-align: top;
1.347     albertel 7691: }
1.795     www      7692: 
1.425     albertel 7693: table.LC_data_table tr.LC_data_table_highlight td {
                   7694:   background-color: $data_table_darker;
                   7695: }
1.795     www      7696: 
1.639     raeburn  7697: table.LC_data_table tr td.LC_leftcol_header {
                   7698:   background-color: $data_table_head;
                   7699:   font-weight: bold;
                   7700: }
1.795     www      7701: 
1.451     albertel 7702: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7703: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7704:   font-weight: bold;
                   7705:   font-style: italic;
                   7706:   text-align: center;
                   7707:   padding: 8px;
1.347     albertel 7708: }
1.795     www      7709: 
1.1114    raeburn  7710: table.LC_data_table tr.LC_empty_row td,
                   7711: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7712:   background-color: $sidebg;
                   7713: }
                   7714: 
                   7715: table.LC_nested tr.LC_empty_row td {
                   7716:   background-color: #FFFFFF;
                   7717: }
                   7718: 
1.890     droeschl 7719: table.LC_caption {
                   7720: }
                   7721: 
1.507     raeburn  7722: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7723:   padding: 4ex
                   7724: }
1.795     www      7725: 
1.507     raeburn  7726: table.LC_nested_outer tr th {
                   7727:   font-weight: bold;
1.801     tempelho 7728:   color:$fontmenu;
1.507     raeburn  7729:   background-color: $data_table_head;
1.701     harmsja  7730:   font-size: small;
1.507     raeburn  7731:   border-bottom: 1px solid #000000;
                   7732: }
1.795     www      7733: 
1.507     raeburn  7734: table.LC_nested_outer tr td.LC_subheader {
                   7735:   background-color: $data_table_head;
                   7736:   font-weight: bold;
                   7737:   font-size: small;
                   7738:   border-bottom: 1px solid #000000;
                   7739:   text-align: right;
1.451     albertel 7740: }
1.795     www      7741: 
1.507     raeburn  7742: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7743:   background-color: #CCCCCC;
1.451     albertel 7744:   font-weight: bold;
                   7745:   font-size: small;
1.507     raeburn  7746:   text-align: center;
                   7747: }
1.795     www      7748: 
1.589     raeburn  7749: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7750: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7751:   text-align: left;
1.451     albertel 7752: }
1.795     www      7753: 
1.507     raeburn  7754: table.LC_nested td {
1.735     bisitz   7755:   background-color: #FFFFFF;
1.451     albertel 7756:   font-size: small;
1.507     raeburn  7757: }
1.795     www      7758: 
1.507     raeburn  7759: table.LC_nested_outer tr th.LC_right_item,
                   7760: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7761: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7762: table.LC_nested tr td.LC_right_item {
1.451     albertel 7763:   text-align: right;
                   7764: }
                   7765: 
1.507     raeburn  7766: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7767:   background-color: #EEEEEE;
1.451     albertel 7768: }
                   7769: 
1.473     raeburn  7770: table.LC_createuser {
                   7771: }
                   7772: 
                   7773: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7774:   font-size: small;
1.473     raeburn  7775: }
                   7776: 
                   7777: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7778:   background-color: #CCCCCC;
1.473     raeburn  7779:   font-weight: bold;
                   7780:   text-align: center;
                   7781: }
                   7782: 
1.349     albertel 7783: table.LC_calendar {
                   7784:   border: 1px solid #000000;
                   7785:   border-collapse: collapse;
1.917     raeburn  7786:   width: 98%;
1.349     albertel 7787: }
1.795     www      7788: 
1.349     albertel 7789: table.LC_calendar_pickdate {
                   7790:   font-size: xx-small;
                   7791: }
1.795     www      7792: 
1.349     albertel 7793: table.LC_calendar tr td {
                   7794:   border: 1px solid #000000;
                   7795:   vertical-align: top;
1.917     raeburn  7796:   width: 14%;
1.349     albertel 7797: }
1.795     www      7798: 
1.349     albertel 7799: table.LC_calendar tr td.LC_calendar_day_empty {
                   7800:   background-color: $data_table_dark;
                   7801: }
1.795     www      7802: 
1.779     bisitz   7803: table.LC_calendar tr td.LC_calendar_day_current {
                   7804:   background-color: $data_table_highlight;
1.777     tempelho 7805: }
1.795     www      7806: 
1.938     bisitz   7807: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7808:   background-color: $mail_new;
                   7809: }
1.795     www      7810: 
1.938     bisitz   7811: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7812:   background-color: $mail_new_hover;
                   7813: }
1.795     www      7814: 
1.938     bisitz   7815: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7816:   background-color: $mail_read;
                   7817: }
1.795     www      7818: 
1.938     bisitz   7819: /*
                   7820: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7821:   background-color: $mail_read_hover;
                   7822: }
1.938     bisitz   7823: */
1.795     www      7824: 
1.938     bisitz   7825: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7826:   background-color: $mail_replied;
                   7827: }
1.795     www      7828: 
1.938     bisitz   7829: /*
                   7830: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7831:   background-color: $mail_replied_hover;
                   7832: }
1.938     bisitz   7833: */
1.795     www      7834: 
1.938     bisitz   7835: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7836:   background-color: $mail_other;
                   7837: }
1.795     www      7838: 
1.938     bisitz   7839: /*
                   7840: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7841:   background-color: $mail_other_hover;
                   7842: }
1.938     bisitz   7843: */
1.494     raeburn  7844: 
1.777     tempelho 7845: table.LC_data_table tr > td.LC_browser_file,
                   7846: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7847:   background: #AAEE77;
1.389     albertel 7848: }
1.795     www      7849: 
1.777     tempelho 7850: table.LC_data_table tr > td.LC_browser_file_locked,
                   7851: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7852:   background: #FFAA99;
1.387     albertel 7853: }
1.795     www      7854: 
1.777     tempelho 7855: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7856:   background: #888888;
1.779     bisitz   7857: }
1.795     www      7858: 
1.777     tempelho 7859: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7860: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7861:   background: #F8F866;
1.777     tempelho 7862: }
1.795     www      7863: 
1.696     bisitz   7864: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7865:   background: #E0E8FF;
1.387     albertel 7866: }
1.696     bisitz   7867: 
1.707     bisitz   7868: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7869:   /* background: #77FF77; */
1.707     bisitz   7870: }
1.795     www      7871: 
1.707     bisitz   7872: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7873:   border-right: 8px solid #FFFF77;
1.707     bisitz   7874: }
1.795     www      7875: 
1.707     bisitz   7876: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7877:   border-right: 8px solid #FFAA77;
1.707     bisitz   7878: }
1.795     www      7879: 
1.707     bisitz   7880: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7881:   border-right: 8px solid #FF7777;
1.707     bisitz   7882: }
1.795     www      7883: 
1.707     bisitz   7884: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7885:   border-right: 8px solid #AAFF77;
1.707     bisitz   7886: }
1.795     www      7887: 
1.707     bisitz   7888: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7889:   border-right: 8px solid #11CC55;
1.707     bisitz   7890: }
                   7891: 
1.388     albertel 7892: span.LC_current_location {
1.701     harmsja  7893:   font-size:larger;
1.388     albertel 7894:   background: $pgbg;
                   7895: }
1.387     albertel 7896: 
1.1029    www      7897: span.LC_current_nav_location {
                   7898:   font-weight:bold;
                   7899:   background: $sidebg;
                   7900: }
                   7901: 
1.395     albertel 7902: span.LC_parm_menu_item {
                   7903:   font-size: larger;
                   7904: }
1.795     www      7905: 
1.395     albertel 7906: span.LC_parm_scope_all {
                   7907:   color: red;
                   7908: }
1.795     www      7909: 
1.395     albertel 7910: span.LC_parm_scope_folder {
                   7911:   color: green;
                   7912: }
1.795     www      7913: 
1.395     albertel 7914: span.LC_parm_scope_resource {
                   7915:   color: orange;
                   7916: }
1.795     www      7917: 
1.395     albertel 7918: span.LC_parm_part {
                   7919:   color: blue;
                   7920: }
1.795     www      7921: 
1.911     bisitz   7922: span.LC_parm_folder,
                   7923: span.LC_parm_symb {
1.395     albertel 7924:   font-size: x-small;
                   7925:   font-family: $mono;
                   7926:   color: #AAAAAA;
                   7927: }
                   7928: 
1.977     bisitz   7929: ul.LC_parm_parmlist li {
                   7930:   display: inline-block;
                   7931:   padding: 0.3em 0.8em;
                   7932:   vertical-align: top;
                   7933:   width: 150px;
                   7934:   border-top:1px solid $lg_border_color;
                   7935: }
                   7936: 
1.795     www      7937: td.LC_parm_overview_level_menu,
                   7938: td.LC_parm_overview_map_menu,
                   7939: td.LC_parm_overview_parm_selectors,
                   7940: td.LC_parm_overview_restrictions  {
1.396     albertel 7941:   border: 1px solid black;
                   7942:   border-collapse: collapse;
                   7943: }
1.795     www      7944: 
1.1285    raeburn  7945: span.LC_parm_recursive,
                   7946: td.LC_parm_recursive {
                   7947:   font-weight: bold;
                   7948:   font-size: smaller;
                   7949: }
                   7950: 
1.396     albertel 7951: table.LC_parm_overview_restrictions td {
                   7952:   border-width: 1px 4px 1px 4px;
                   7953:   border-style: solid;
                   7954:   border-color: $pgbg;
                   7955:   text-align: center;
                   7956: }
1.795     www      7957: 
1.396     albertel 7958: table.LC_parm_overview_restrictions th {
                   7959:   background: $tabbg;
                   7960:   border-width: 1px 4px 1px 4px;
                   7961:   border-style: solid;
                   7962:   border-color: $pgbg;
                   7963: }
1.795     www      7964: 
1.398     albertel 7965: table#LC_helpmenu {
1.803     bisitz   7966:   border: none;
1.398     albertel 7967:   height: 55px;
1.803     bisitz   7968:   border-spacing: 0;
1.398     albertel 7969: }
                   7970: 
                   7971: table#LC_helpmenu fieldset legend {
                   7972:   font-size: larger;
                   7973: }
1.795     www      7974: 
1.397     albertel 7975: table#LC_helpmenu_links {
                   7976:   width: 100%;
                   7977:   border: 1px solid black;
                   7978:   background: $pgbg;
1.803     bisitz   7979:   padding: 0;
1.397     albertel 7980:   border-spacing: 1px;
                   7981: }
1.795     www      7982: 
1.397     albertel 7983: table#LC_helpmenu_links tr td {
                   7984:   padding: 1px;
                   7985:   background: $tabbg;
1.399     albertel 7986:   text-align: center;
                   7987:   font-weight: bold;
1.397     albertel 7988: }
1.396     albertel 7989: 
1.795     www      7990: table#LC_helpmenu_links a:link,
                   7991: table#LC_helpmenu_links a:visited,
1.397     albertel 7992: table#LC_helpmenu_links a:active {
                   7993:   text-decoration: none;
                   7994:   color: $font;
                   7995: }
1.795     www      7996: 
1.397     albertel 7997: table#LC_helpmenu_links a:hover {
                   7998:   text-decoration: underline;
                   7999:   color: $vlink;
                   8000: }
1.396     albertel 8001: 
1.417     albertel 8002: .LC_chrt_popup_exists {
                   8003:   border: 1px solid #339933;
                   8004:   margin: -1px;
                   8005: }
1.795     www      8006: 
1.417     albertel 8007: .LC_chrt_popup_up {
                   8008:   border: 1px solid yellow;
                   8009:   margin: -1px;
                   8010: }
1.795     www      8011: 
1.417     albertel 8012: .LC_chrt_popup {
                   8013:   border: 1px solid #8888FF;
                   8014:   background: #CCCCFF;
                   8015: }
1.795     www      8016: 
1.421     albertel 8017: table.LC_pick_box {
                   8018:   border-collapse: separate;
                   8019:   background: white;
                   8020:   border: 1px solid black;
                   8021:   border-spacing: 1px;
                   8022: }
1.795     www      8023: 
1.421     albertel 8024: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   8025:   background: $sidebg;
1.421     albertel 8026:   font-weight: bold;
1.900     bisitz   8027:   text-align: left;
1.740     bisitz   8028:   vertical-align: top;
1.421     albertel 8029:   width: 184px;
                   8030:   padding: 8px;
                   8031: }
1.795     www      8032: 
1.579     raeburn  8033: table.LC_pick_box td.LC_pick_box_value {
                   8034:   text-align: left;
                   8035:   padding: 8px;
                   8036: }
1.795     www      8037: 
1.579     raeburn  8038: table.LC_pick_box td.LC_pick_box_select {
                   8039:   text-align: left;
                   8040:   padding: 8px;
                   8041: }
1.795     www      8042: 
1.424     albertel 8043: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   8044:   padding: 0;
1.421     albertel 8045:   height: 1px;
                   8046:   background: black;
                   8047: }
1.795     www      8048: 
1.421     albertel 8049: table.LC_pick_box td.LC_pick_box_submit {
                   8050:   text-align: right;
                   8051: }
1.795     www      8052: 
1.579     raeburn  8053: table.LC_pick_box td.LC_evenrow_value {
                   8054:   text-align: left;
                   8055:   padding: 8px;
                   8056:   background-color: $data_table_light;
                   8057: }
1.795     www      8058: 
1.579     raeburn  8059: table.LC_pick_box td.LC_oddrow_value {
                   8060:   text-align: left;
                   8061:   padding: 8px;
                   8062:   background-color: $data_table_light;
                   8063: }
1.795     www      8064: 
1.579     raeburn  8065: span.LC_helpform_receipt_cat {
                   8066:   font-weight: bold;
                   8067: }
1.795     www      8068: 
1.424     albertel 8069: table.LC_group_priv_box {
                   8070:   background: white;
                   8071:   border: 1px solid black;
                   8072:   border-spacing: 1px;
                   8073: }
1.795     www      8074: 
1.424     albertel 8075: table.LC_group_priv_box td.LC_pick_box_title {
                   8076:   background: $tabbg;
                   8077:   font-weight: bold;
                   8078:   text-align: right;
                   8079:   width: 184px;
                   8080: }
1.795     www      8081: 
1.424     albertel 8082: table.LC_group_priv_box td.LC_groups_fixed {
                   8083:   background: $data_table_light;
                   8084:   text-align: center;
                   8085: }
1.795     www      8086: 
1.424     albertel 8087: table.LC_group_priv_box td.LC_groups_optional {
                   8088:   background: $data_table_dark;
                   8089:   text-align: center;
                   8090: }
1.795     www      8091: 
1.424     albertel 8092: table.LC_group_priv_box td.LC_groups_functionality {
                   8093:   background: $data_table_darker;
                   8094:   text-align: center;
                   8095:   font-weight: bold;
                   8096: }
1.795     www      8097: 
1.424     albertel 8098: table.LC_group_priv td {
                   8099:   text-align: left;
1.803     bisitz   8100:   padding: 0;
1.424     albertel 8101: }
                   8102: 
                   8103: .LC_navbuttons {
                   8104:   margin: 2ex 0ex 2ex 0ex;
                   8105: }
1.795     www      8106: 
1.423     albertel 8107: .LC_topic_bar {
                   8108:   font-weight: bold;
                   8109:   background: $tabbg;
1.918     wenzelju 8110:   margin: 1em 0em 1em 2em;
1.805     bisitz   8111:   padding: 3px;
1.918     wenzelju 8112:   font-size: 1.2em;
1.423     albertel 8113: }
1.795     www      8114: 
1.423     albertel 8115: .LC_topic_bar span {
1.918     wenzelju 8116:   left: 0.5em;
                   8117:   position: absolute;
1.423     albertel 8118:   vertical-align: middle;
1.918     wenzelju 8119:   font-size: 1.2em;
1.423     albertel 8120: }
1.795     www      8121: 
1.423     albertel 8122: table.LC_course_group_status {
                   8123:   margin: 20px;
                   8124: }
1.795     www      8125: 
1.423     albertel 8126: table.LC_status_selector td {
                   8127:   vertical-align: top;
                   8128:   text-align: center;
1.424     albertel 8129:   padding: 4px;
                   8130: }
1.795     www      8131: 
1.599     albertel 8132: div.LC_feedback_link {
1.616     albertel 8133:   clear: both;
1.829     kalberla 8134:   background: $sidebg;
1.779     bisitz   8135:   width: 100%;
1.829     kalberla 8136:   padding-bottom: 10px;
                   8137:   border: 1px $tabbg solid;
1.833     kalberla 8138:   height: 22px;
                   8139:   line-height: 22px;
                   8140:   padding-top: 5px;
                   8141: }
                   8142: 
                   8143: div.LC_feedback_link img {
                   8144:   height: 22px;
1.867     kalberla 8145:   vertical-align:middle;
1.829     kalberla 8146: }
                   8147: 
1.911     bisitz   8148: div.LC_feedback_link a {
1.829     kalberla 8149:   text-decoration: none;
1.489     raeburn  8150: }
1.795     www      8151: 
1.867     kalberla 8152: div.LC_comblock {
1.911     bisitz   8153:   display:inline;
1.867     kalberla 8154:   color:$font;
                   8155:   font-size:90%;
                   8156: }
                   8157: 
                   8158: div.LC_feedback_link div.LC_comblock {
                   8159:   padding-left:5px;
                   8160: }
                   8161: 
                   8162: div.LC_feedback_link div.LC_comblock a {
                   8163:   color:$font;
                   8164: }
                   8165: 
1.489     raeburn  8166: span.LC_feedback_link {
1.858     bisitz   8167:   /* background: $feedback_link_bg; */
1.599     albertel 8168:   font-size: larger;
                   8169: }
1.795     www      8170: 
1.599     albertel 8171: span.LC_message_link {
1.858     bisitz   8172:   /* background: $feedback_link_bg; */
1.599     albertel 8173:   font-size: larger;
                   8174:   position: absolute;
                   8175:   right: 1em;
1.489     raeburn  8176: }
1.421     albertel 8177: 
1.515     albertel 8178: table.LC_prior_tries {
1.524     albertel 8179:   border: 1px solid #000000;
                   8180:   border-collapse: separate;
                   8181:   border-spacing: 1px;
1.515     albertel 8182: }
1.523     albertel 8183: 
1.515     albertel 8184: table.LC_prior_tries td {
1.524     albertel 8185:   padding: 2px;
1.515     albertel 8186: }
1.523     albertel 8187: 
                   8188: .LC_answer_correct {
1.795     www      8189:   background: lightgreen;
                   8190:   color: darkgreen;
                   8191:   padding: 6px;
1.523     albertel 8192: }
1.795     www      8193: 
1.523     albertel 8194: .LC_answer_charged_try {
1.797     www      8195:   background: #FFAAAA;
1.795     www      8196:   color: darkred;
                   8197:   padding: 6px;
1.523     albertel 8198: }
1.795     www      8199: 
1.779     bisitz   8200: .LC_answer_not_charged_try,
1.523     albertel 8201: .LC_answer_no_grade,
                   8202: .LC_answer_late {
1.795     www      8203:   background: lightyellow;
1.523     albertel 8204:   color: black;
1.795     www      8205:   padding: 6px;
1.523     albertel 8206: }
1.795     www      8207: 
1.523     albertel 8208: .LC_answer_previous {
1.795     www      8209:   background: lightblue;
                   8210:   color: darkblue;
                   8211:   padding: 6px;
1.523     albertel 8212: }
1.795     www      8213: 
1.779     bisitz   8214: .LC_answer_no_message {
1.777     tempelho 8215:   background: #FFFFFF;
                   8216:   color: black;
1.795     www      8217:   padding: 6px;
1.779     bisitz   8218: }
1.795     www      8219: 
1.1334    raeburn  8220: .LC_answer_unknown,
                   8221: .LC_answer_warning {
1.779     bisitz   8222:   background: orange;
                   8223:   color: black;
1.795     www      8224:   padding: 6px;
1.777     tempelho 8225: }
1.795     www      8226: 
1.529     albertel 8227: span.LC_prior_numerical,
                   8228: span.LC_prior_string,
                   8229: span.LC_prior_custom,
                   8230: span.LC_prior_reaction,
                   8231: span.LC_prior_math {
1.925     bisitz   8232:   font-family: $mono;
1.523     albertel 8233:   white-space: pre;
                   8234: }
                   8235: 
1.525     albertel 8236: span.LC_prior_string {
1.925     bisitz   8237:   font-family: $mono;
1.525     albertel 8238:   white-space: pre;
                   8239: }
                   8240: 
1.523     albertel 8241: table.LC_prior_option {
                   8242:   width: 100%;
                   8243:   border-collapse: collapse;
                   8244: }
1.795     www      8245: 
1.911     bisitz   8246: table.LC_prior_rank,
1.795     www      8247: table.LC_prior_match {
1.528     albertel 8248:   border-collapse: collapse;
                   8249: }
1.795     www      8250: 
1.528     albertel 8251: table.LC_prior_option tr td,
                   8252: table.LC_prior_rank tr td,
                   8253: table.LC_prior_match tr td {
1.524     albertel 8254:   border: 1px solid #000000;
1.515     albertel 8255: }
                   8256: 
1.855     bisitz   8257: .LC_nobreak {
1.544     albertel 8258:   white-space: nowrap;
1.519     raeburn  8259: }
                   8260: 
1.576     raeburn  8261: span.LC_cusr_emph {
                   8262:   font-style: italic;
                   8263: }
                   8264: 
1.633     raeburn  8265: span.LC_cusr_subheading {
                   8266:   font-weight: normal;
                   8267:   font-size: 85%;
                   8268: }
                   8269: 
1.861     bisitz   8270: div.LC_docs_entry_move {
1.859     bisitz   8271:   border: 1px solid #BBBBBB;
1.545     albertel 8272:   background: #DDDDDD;
1.861     bisitz   8273:   width: 22px;
1.859     bisitz   8274:   padding: 1px;
                   8275:   margin: 0;
1.545     albertel 8276: }
                   8277: 
1.861     bisitz   8278: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8279: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8280:   font-size: x-small;
                   8281: }
1.795     www      8282: 
1.861     bisitz   8283: .LC_docs_entry_parameter {
                   8284:   white-space: nowrap;
                   8285: }
                   8286: 
1.544     albertel 8287: .LC_docs_copy {
1.545     albertel 8288:   color: #000099;
1.544     albertel 8289: }
1.795     www      8290: 
1.544     albertel 8291: .LC_docs_cut {
1.545     albertel 8292:   color: #550044;
1.544     albertel 8293: }
1.795     www      8294: 
1.544     albertel 8295: .LC_docs_rename {
1.545     albertel 8296:   color: #009900;
1.544     albertel 8297: }
1.795     www      8298: 
1.544     albertel 8299: .LC_docs_remove {
1.545     albertel 8300:   color: #990000;
                   8301: }
                   8302: 
1.1284    raeburn  8303: .LC_docs_alias {
                   8304:   color: #440055;  
                   8305: }
                   8306: 
1.1286    raeburn  8307: .LC_domprefs_email,
1.1284    raeburn  8308: .LC_docs_alias_name,
1.547     albertel 8309: .LC_docs_reinit_warn,
                   8310: .LC_docs_ext_edit {
                   8311:   font-size: x-small;
                   8312: }
                   8313: 
1.545     albertel 8314: table.LC_docs_adddocs td,
                   8315: table.LC_docs_adddocs th {
                   8316:   border: 1px solid #BBBBBB;
                   8317:   padding: 4px;
                   8318:   background: #DDDDDD;
1.543     albertel 8319: }
                   8320: 
1.584     albertel 8321: table.LC_sty_begin {
                   8322:   background: #BBFFBB;
                   8323: }
1.795     www      8324: 
1.584     albertel 8325: table.LC_sty_end {
                   8326:   background: #FFBBBB;
                   8327: }
                   8328: 
1.589     raeburn  8329: table.LC_double_column {
1.803     bisitz   8330:   border-width: 0;
1.589     raeburn  8331:   border-collapse: collapse;
                   8332:   width: 100%;
                   8333:   padding: 2px;
                   8334: }
                   8335: 
                   8336: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8337:   top: 2px;
1.589     raeburn  8338:   left: 2px;
                   8339:   width: 47%;
                   8340:   vertical-align: top;
                   8341: }
                   8342: 
                   8343: table.LC_double_column tr td.LC_right_col {
                   8344:   top: 2px;
1.779     bisitz   8345:   right: 2px;
1.589     raeburn  8346:   width: 47%;
                   8347:   vertical-align: top;
                   8348: }
                   8349: 
1.591     raeburn  8350: div.LC_left_float {
                   8351:   float: left;
                   8352:   padding-right: 5%;
1.597     albertel 8353:   padding-bottom: 4px;
1.591     raeburn  8354: }
                   8355: 
                   8356: div.LC_clear_float_header {
1.597     albertel 8357:   padding-bottom: 2px;
1.591     raeburn  8358: }
                   8359: 
                   8360: div.LC_clear_float_footer {
1.597     albertel 8361:   padding-top: 10px;
1.591     raeburn  8362:   clear: both;
                   8363: }
                   8364: 
1.597     albertel 8365: div.LC_grade_show_user {
1.941     bisitz   8366: /*  border-left: 5px solid $sidebg; */
                   8367:   border-top: 5px solid #000000;
                   8368:   margin: 50px 0 0 0;
1.936     bisitz   8369:   padding: 15px 0 5px 10px;
1.597     albertel 8370: }
1.795     www      8371: 
1.936     bisitz   8372: div.LC_grade_show_user_odd_row {
1.941     bisitz   8373: /*  border-left: 5px solid #000000; */
                   8374: }
                   8375: 
                   8376: div.LC_grade_show_user div.LC_Box {
                   8377:   margin-right: 50px;
1.597     albertel 8378: }
                   8379: 
                   8380: div.LC_grade_submissions,
                   8381: div.LC_grade_message_center,
1.936     bisitz   8382: div.LC_grade_info_links {
1.597     albertel 8383:   margin: 5px;
                   8384:   width: 99%;
                   8385:   background: #FFFFFF;
                   8386: }
1.795     www      8387: 
1.597     albertel 8388: div.LC_grade_submissions_header,
1.936     bisitz   8389: div.LC_grade_message_center_header {
1.705     tempelho 8390:   font-weight: bold;
                   8391:   font-size: large;
1.597     albertel 8392: }
1.795     www      8393: 
1.597     albertel 8394: div.LC_grade_submissions_body,
1.936     bisitz   8395: div.LC_grade_message_center_body {
1.597     albertel 8396:   border: 1px solid black;
                   8397:   width: 99%;
                   8398:   background: #FFFFFF;
                   8399: }
1.795     www      8400: 
1.613     albertel 8401: table.LC_scantron_action {
                   8402:   width: 100%;
                   8403: }
1.795     www      8404: 
1.613     albertel 8405: table.LC_scantron_action tr th {
1.698     harmsja  8406:   font-weight:bold;
                   8407:   font-style:normal;
1.613     albertel 8408: }
1.795     www      8409: 
1.779     bisitz   8410: .LC_edit_problem_header,
1.614     albertel 8411: div.LC_edit_problem_footer {
1.705     tempelho 8412:   font-weight: normal;
                   8413:   font-size:  medium;
1.602     albertel 8414:   margin: 2px;
1.1060    bisitz   8415:   background-color: $sidebg;
1.600     albertel 8416: }
1.795     www      8417: 
1.600     albertel 8418: div.LC_edit_problem_header,
1.602     albertel 8419: div.LC_edit_problem_header div,
1.614     albertel 8420: div.LC_edit_problem_footer,
                   8421: div.LC_edit_problem_footer div,
1.602     albertel 8422: div.LC_edit_problem_editxml_header,
                   8423: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8424:   z-index: 100;
1.600     albertel 8425: }
1.795     www      8426: 
1.600     albertel 8427: div.LC_edit_problem_header_title {
1.705     tempelho 8428:   font-weight: bold;
                   8429:   font-size: larger;
1.602     albertel 8430:   background: $tabbg;
                   8431:   padding: 3px;
1.1060    bisitz   8432:   margin: 0 0 5px 0;
1.602     albertel 8433: }
1.795     www      8434: 
1.602     albertel 8435: table.LC_edit_problem_header_title {
                   8436:   width: 100%;
1.600     albertel 8437:   background: $tabbg;
1.602     albertel 8438: }
                   8439: 
1.1205    golterma 8440: div.LC_edit_actionbar {
                   8441:     background-color: $sidebg;
1.1218    droeschl 8442:     margin: 0;
                   8443:     padding: 0;
                   8444:     line-height: 200%;
1.602     albertel 8445: }
1.795     www      8446: 
1.1218    droeschl 8447: div.LC_edit_actionbar div{
                   8448:     padding: 0;
                   8449:     margin: 0;
                   8450:     display: inline-block;
1.600     albertel 8451: }
1.795     www      8452: 
1.1124    bisitz   8453: .LC_edit_opt {
                   8454:   padding-left: 1em;
                   8455:   white-space: nowrap;
                   8456: }
                   8457: 
1.1152    golterma 8458: .LC_edit_problem_latexhelper{
                   8459:     text-align: right;
                   8460: }
                   8461: 
                   8462: #LC_edit_problem_colorful div{
                   8463:     margin-left: 40px;
                   8464: }
                   8465: 
1.1205    golterma 8466: #LC_edit_problem_codemirror div{
                   8467:     margin-left: 0px;
                   8468: }
                   8469: 
1.911     bisitz   8470: img.stift {
1.803     bisitz   8471:   border-width: 0;
                   8472:   vertical-align: middle;
1.677     riegler  8473: }
1.680     riegler  8474: 
1.923     bisitz   8475: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8476:   vertical-align: top;
1.777     tempelho 8477: }
1.795     www      8478: 
1.716     raeburn  8479: div.LC_createcourse {
1.911     bisitz   8480:   margin: 10px 10px 10px 10px;
1.716     raeburn  8481: }
                   8482: 
1.917     raeburn  8483: .LC_dccid {
1.1130    raeburn  8484:   float: right;
1.917     raeburn  8485:   margin: 0.2em 0 0 0;
                   8486:   padding: 0;
                   8487:   font-size: 90%;
                   8488:   display:none;
                   8489: }
                   8490: 
1.897     wenzelju 8491: ol.LC_primary_menu a:hover,
1.721     harmsja  8492: ol#LC_MenuBreadcrumbs a:hover,
                   8493: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8494: ul#LC_secondary_menu a:hover,
1.721     harmsja  8495: .LC_FormSectionClearButton input:hover
1.795     www      8496: ul.LC_TabContent   li:hover a {
1.952     onken    8497:   color:$button_hover;
1.911     bisitz   8498:   text-decoration:none;
1.693     droeschl 8499: }
                   8500: 
1.779     bisitz   8501: h1 {
1.911     bisitz   8502:   padding: 0;
                   8503:   line-height:130%;
1.693     droeschl 8504: }
1.698     harmsja  8505: 
1.911     bisitz   8506: h2,
                   8507: h3,
                   8508: h4,
                   8509: h5,
                   8510: h6 {
                   8511:   margin: 5px 0 5px 0;
                   8512:   padding: 0;
                   8513:   line-height:130%;
1.693     droeschl 8514: }
1.795     www      8515: 
                   8516: .LC_hcell {
1.911     bisitz   8517:   padding:3px 15px 3px 15px;
                   8518:   margin: 0;
                   8519:   background-color:$tabbg;
                   8520:   color:$fontmenu;
                   8521:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8522: }
1.795     www      8523: 
1.840     bisitz   8524: .LC_Box > .LC_hcell {
1.911     bisitz   8525:   margin: 0 -10px 10px -10px;
1.835     bisitz   8526: }
                   8527: 
1.721     harmsja  8528: .LC_noBorder {
1.911     bisitz   8529:   border: 0;
1.698     harmsja  8530: }
1.693     droeschl 8531: 
1.721     harmsja  8532: .LC_FormSectionClearButton input {
1.911     bisitz   8533:   background-color:transparent;
                   8534:   border: none;
                   8535:   cursor:pointer;
                   8536:   text-decoration:underline;
1.693     droeschl 8537: }
1.763     bisitz   8538: 
                   8539: .LC_help_open_topic {
1.911     bisitz   8540:   color: #FFFFFF;
                   8541:   background-color: #EEEEFF;
                   8542:   margin: 1px;
                   8543:   padding: 4px;
                   8544:   border: 1px solid #000033;
                   8545:   white-space: nowrap;
                   8546:   /* vertical-align: middle; */
1.759     neumanie 8547: }
1.693     droeschl 8548: 
1.911     bisitz   8549: dl,
                   8550: ul,
                   8551: div,
                   8552: fieldset {
                   8553:   margin: 10px 10px 10px 0;
                   8554:   /* overflow: hidden; */
1.693     droeschl 8555: }
1.795     www      8556: 
1.1404    raeburn  8557: fieldset#LC_selectuser {
                   8558:     margin: 0;
                   8559:     padding: 0;
                   8560: }
                   8561: 
1.1211    raeburn  8562: article.geogebraweb div {
                   8563:     margin: 0;
                   8564: }
                   8565: 
1.838     bisitz   8566: fieldset > legend {
1.911     bisitz   8567:   font-weight: bold;
                   8568:   padding: 0 5px 0 5px;
1.838     bisitz   8569: }
                   8570: 
1.813     bisitz   8571: #LC_nav_bar {
1.911     bisitz   8572:   float: left;
1.995     raeburn  8573:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8574:   margin: 0 0 2px 0;
1.807     droeschl 8575: }
                   8576: 
1.916     droeschl 8577: #LC_realm {
                   8578:   margin: 0.2em 0 0 0;
                   8579:   padding: 0;
                   8580:   font-weight: bold;
                   8581:   text-align: center;
1.995     raeburn  8582:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8583: }
                   8584: 
1.911     bisitz   8585: #LC_nav_bar em {
                   8586:   font-weight: bold;
                   8587:   font-style: normal;
1.807     droeschl 8588: }
                   8589: 
1.897     wenzelju 8590: ol.LC_primary_menu {
1.934     droeschl 8591:   margin: 0;
1.1076    raeburn  8592:   padding: 0;
1.807     droeschl 8593: }
                   8594: 
1.852     droeschl 8595: ol#LC_PathBreadcrumbs {
1.911     bisitz   8596:   margin: 0;
1.693     droeschl 8597: }
                   8598: 
1.897     wenzelju 8599: ol.LC_primary_menu li {
1.1076    raeburn  8600:   color: RGB(80, 80, 80);
                   8601:   vertical-align: middle;
                   8602:   text-align: left;
                   8603:   list-style: none;
1.1205    golterma 8604:   position: relative;
1.1076    raeburn  8605:   float: left;
1.1205    golterma 8606:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8607:   line-height: 1.5em;
1.1076    raeburn  8608: }
                   8609: 
1.1205    golterma 8610: ol.LC_primary_menu li a,
                   8611: ol.LC_primary_menu li p {
1.1076    raeburn  8612:   display: block;
                   8613:   margin: 0;
                   8614:   padding: 0 5px 0 10px;
                   8615:   text-decoration: none;
                   8616: }
                   8617: 
1.1205    golterma 8618: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8619:   display: inline-block;
                   8620:   width: 95%;
                   8621:   text-align: left;
                   8622: }
                   8623: 
                   8624: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8625:   display: inline-block;	
                   8626:   width: 5%;
                   8627:   float: right;
                   8628:   text-align: right;
                   8629:   font-size: 70%;
                   8630: }
                   8631: 
                   8632: ol.LC_primary_menu ul {
1.1076    raeburn  8633:   display: none;
1.1205    golterma 8634:   width: 15em;
1.1076    raeburn  8635:   background-color: $data_table_light;
1.1205    golterma 8636:   position: absolute;
                   8637:   top: 100%;
1.1076    raeburn  8638: }
                   8639: 
1.1205    golterma 8640: ol.LC_primary_menu ul ul {
                   8641:   left: 100%;
                   8642:   top: 0;
                   8643: }
                   8644: 
                   8645: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8646:   display: block;
                   8647:   position: absolute;
                   8648:   margin: 0;
                   8649:   padding: 0;
1.1078    raeburn  8650:   z-index: 2;
1.1076    raeburn  8651: }
                   8652: 
                   8653: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8654: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8655:   font-size: 90%;
1.911     bisitz   8656:   vertical-align: top;
1.1076    raeburn  8657:   float: none;
1.1079    raeburn  8658:   border-left: 1px solid black;
                   8659:   border-right: 1px solid black;
1.1205    golterma 8660: /* A dark bottom border to visualize different menu options; 
                   8661: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8662:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8663: }
                   8664: 
1.1205    golterma 8665: ol.LC_primary_menu li li p:hover {
                   8666:   color:$button_hover;
                   8667:   text-decoration:none;
                   8668:   background-color:$data_table_dark;
1.1076    raeburn  8669: }
                   8670: 
                   8671: ol.LC_primary_menu li li a:hover {
                   8672:    color:$button_hover;
                   8673:    background-color:$data_table_dark;
1.693     droeschl 8674: }
                   8675: 
1.1205    golterma 8676: /* Font-size equal to the size of the predecessors*/
                   8677: ol.LC_primary_menu li:hover li li {
                   8678:   font-size: 100%;
                   8679: }
                   8680: 
1.897     wenzelju 8681: ol.LC_primary_menu li img {
1.911     bisitz   8682:   vertical-align: bottom;
1.934     droeschl 8683:   height: 1.1em;
1.1077    raeburn  8684:   margin: 0.2em 0 0 0;
1.693     droeschl 8685: }
                   8686: 
1.897     wenzelju 8687: ol.LC_primary_menu a {
1.911     bisitz   8688:   color: RGB(80, 80, 80);
                   8689:   text-decoration: none;
1.693     droeschl 8690: }
1.795     www      8691: 
1.949     droeschl 8692: ol.LC_primary_menu a.LC_new_message {
                   8693:   font-weight:bold;
                   8694:   color: darkred;
                   8695: }
                   8696: 
1.975     raeburn  8697: ol.LC_docs_parameters {
                   8698:   margin-left: 0;
                   8699:   padding: 0;
                   8700:   list-style: none;
                   8701: }
                   8702: 
                   8703: ol.LC_docs_parameters li {
                   8704:   margin: 0;
                   8705:   padding-right: 20px;
                   8706:   display: inline;
                   8707: }
                   8708: 
1.976     raeburn  8709: ol.LC_docs_parameters li:before {
                   8710:   content: "\\002022 \\0020";
                   8711: }
                   8712: 
                   8713: li.LC_docs_parameters_title {
                   8714:   font-weight: bold;
                   8715: }
                   8716: 
                   8717: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8718:   content: "";
                   8719: }
                   8720: 
1.897     wenzelju 8721: ul#LC_secondary_menu {
1.1107    raeburn  8722:   clear: right;
1.911     bisitz   8723:   color: $fontmenu;
                   8724:   background: $tabbg;
                   8725:   list-style: none;
                   8726:   padding: 0;
                   8727:   margin: 0;
                   8728:   width: 100%;
1.995     raeburn  8729:   text-align: left;
1.1107    raeburn  8730:   float: left;
1.808     droeschl 8731: }
                   8732: 
1.897     wenzelju 8733: ul#LC_secondary_menu li {
1.911     bisitz   8734:   font-weight: bold;
                   8735:   line-height: 1.8em;
1.1107    raeburn  8736:   border-right: 1px solid black;
                   8737:   float: left;
                   8738: }
                   8739: 
                   8740: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8741:   background-color: $data_table_light;
                   8742: }
                   8743: 
                   8744: ul#LC_secondary_menu li a {
1.911     bisitz   8745:   padding: 0 0.8em;
1.1107    raeburn  8746: }
                   8747: 
                   8748: ul#LC_secondary_menu li ul {
                   8749:   display: none;
                   8750: }
                   8751: 
                   8752: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8753:   display: block;
                   8754:   position: absolute;
                   8755:   margin: 0;
                   8756:   padding: 0;
                   8757:   list-style:none;
                   8758:   float: none;
                   8759:   background-color: $data_table_light;
                   8760:   z-index: 2;
                   8761:   margin-left: -1px;
                   8762: }
                   8763: 
                   8764: ul#LC_secondary_menu li ul li {
                   8765:   font-size: 90%;
                   8766:   vertical-align: top;
                   8767:   border-left: 1px solid black;
1.911     bisitz   8768:   border-right: 1px solid black;
1.1119    raeburn  8769:   background-color: $data_table_light;
1.1107    raeburn  8770:   list-style:none;
                   8771:   float: none;
                   8772: }
                   8773: 
                   8774: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8775:   background-color: $data_table_dark;
1.807     droeschl 8776: }
                   8777: 
1.847     tempelho 8778: ul.LC_TabContent {
1.911     bisitz   8779:   display:block;
                   8780:   background: $sidebg;
                   8781:   border-bottom: solid 1px $lg_border_color;
                   8782:   list-style:none;
1.1020    raeburn  8783:   margin: -1px -10px 0 -10px;
1.911     bisitz   8784:   padding: 0;
1.693     droeschl 8785: }
                   8786: 
1.795     www      8787: ul.LC_TabContent li,
                   8788: ul.LC_TabContentBigger li {
1.911     bisitz   8789:   float:left;
1.741     harmsja  8790: }
1.795     www      8791: 
1.897     wenzelju 8792: ul#LC_secondary_menu li a {
1.911     bisitz   8793:   color: $fontmenu;
                   8794:   text-decoration: none;
1.693     droeschl 8795: }
1.795     www      8796: 
1.721     harmsja  8797: ul.LC_TabContent {
1.952     onken    8798:   min-height:20px;
1.721     harmsja  8799: }
1.795     www      8800: 
                   8801: ul.LC_TabContent li {
1.911     bisitz   8802:   vertical-align:middle;
1.959     onken    8803:   padding: 0 16px 0 10px;
1.911     bisitz   8804:   background-color:$tabbg;
                   8805:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8806:   border-left: solid 1px $font;
1.721     harmsja  8807: }
1.795     www      8808: 
1.847     tempelho 8809: ul.LC_TabContent .right {
1.911     bisitz   8810:   float:right;
1.847     tempelho 8811: }
                   8812: 
1.911     bisitz   8813: ul.LC_TabContent li a,
                   8814: ul.LC_TabContent li {
                   8815:   color:rgb(47,47,47);
                   8816:   text-decoration:none;
                   8817:   font-size:95%;
                   8818:   font-weight:bold;
1.952     onken    8819:   min-height:20px;
                   8820: }
                   8821: 
1.959     onken    8822: ul.LC_TabContent li a:hover,
                   8823: ul.LC_TabContent li a:focus {
1.952     onken    8824:   color: $button_hover;
1.959     onken    8825:   background:none;
                   8826:   outline:none;
1.952     onken    8827: }
                   8828: 
                   8829: ul.LC_TabContent li:hover {
                   8830:   color: $button_hover;
                   8831:   cursor:pointer;
1.721     harmsja  8832: }
1.795     www      8833: 
1.911     bisitz   8834: ul.LC_TabContent li.active {
1.952     onken    8835:   color: $font;
1.911     bisitz   8836:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8837:   border-bottom:solid 1px #FFFFFF;
                   8838:   cursor: default;
1.744     ehlerst  8839: }
1.795     www      8840: 
1.959     onken    8841: ul.LC_TabContent li.active a {
                   8842:   color:$font;
                   8843:   background:#FFFFFF;
                   8844:   outline: none;
                   8845: }
1.1047    raeburn  8846: 
                   8847: ul.LC_TabContent li.goback {
                   8848:   float: left;
                   8849:   border-left: none;
                   8850: }
                   8851: 
1.870     tempelho 8852: #maincoursedoc {
1.911     bisitz   8853:   clear:both;
1.870     tempelho 8854: }
                   8855: 
                   8856: ul.LC_TabContentBigger {
1.911     bisitz   8857:   display:block;
                   8858:   list-style:none;
                   8859:   padding: 0;
1.870     tempelho 8860: }
                   8861: 
1.795     www      8862: ul.LC_TabContentBigger li {
1.911     bisitz   8863:   vertical-align:bottom;
                   8864:   height: 30px;
                   8865:   font-size:110%;
                   8866:   font-weight:bold;
                   8867:   color: #737373;
1.841     tempelho 8868: }
                   8869: 
1.957     onken    8870: ul.LC_TabContentBigger li.active {
                   8871:   position: relative;
                   8872:   top: 1px;
                   8873: }
                   8874: 
1.870     tempelho 8875: ul.LC_TabContentBigger li a {
1.911     bisitz   8876:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8877:   height: 30px;
                   8878:   line-height: 30px;
                   8879:   text-align: center;
                   8880:   display: block;
                   8881:   text-decoration: none;
1.958     onken    8882:   outline: none;  
1.741     harmsja  8883: }
1.795     www      8884: 
1.870     tempelho 8885: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8886:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8887:   color:$font;
1.744     ehlerst  8888: }
1.795     www      8889: 
1.870     tempelho 8890: ul.LC_TabContentBigger li b {
1.911     bisitz   8891:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8892:   display: block;
                   8893:   float: left;
                   8894:   padding: 0 30px;
1.957     onken    8895:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8896: }
                   8897: 
1.956     onken    8898: ul.LC_TabContentBigger li:hover b {
                   8899:   color:$button_hover;
                   8900: }
                   8901: 
1.870     tempelho 8902: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8903:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8904:   color:$font;
1.957     onken    8905:   border: 0;
1.741     harmsja  8906: }
1.693     droeschl 8907: 
1.870     tempelho 8908: 
1.862     bisitz   8909: ul.LC_CourseBreadcrumbs {
                   8910:   background: $sidebg;
1.1020    raeburn  8911:   height: 2em;
1.862     bisitz   8912:   padding-left: 10px;
1.1020    raeburn  8913:   margin: 0;
1.862     bisitz   8914:   list-style-position: inside;
                   8915: }
                   8916: 
1.911     bisitz   8917: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8918: ol#LC_PathBreadcrumbs {
1.911     bisitz   8919:   padding-left: 10px;
                   8920:   margin: 0;
1.933     droeschl 8921:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8922: }
                   8923: 
1.911     bisitz   8924: ol#LC_MenuBreadcrumbs li,
                   8925: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8926: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8927:   display: inline;
1.933     droeschl 8928:   white-space: normal;  
1.693     droeschl 8929: }
                   8930: 
1.823     bisitz   8931: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8932: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8933:   text-decoration: none;
                   8934:   font-size:90%;
1.693     droeschl 8935: }
1.795     www      8936: 
1.969     droeschl 8937: ol#LC_MenuBreadcrumbs h1 {
                   8938:   display: inline;
                   8939:   font-size: 90%;
                   8940:   line-height: 2.5em;
                   8941:   margin: 0;
                   8942:   padding: 0;
                   8943: }
                   8944: 
1.795     www      8945: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8946:   text-decoration:none;
                   8947:   font-size:100%;
                   8948:   font-weight:bold;
1.693     droeschl 8949: }
1.795     www      8950: 
1.840     bisitz   8951: .LC_Box {
1.911     bisitz   8952:   border: solid 1px $lg_border_color;
                   8953:   padding: 0 10px 10px 10px;
1.746     neumanie 8954: }
1.795     www      8955: 
1.1020    raeburn  8956: .LC_DocsBox {
                   8957:   border: solid 1px $lg_border_color;
                   8958:   padding: 0 0 10px 10px;
                   8959: }
                   8960: 
1.795     www      8961: .LC_AboutMe_Image {
1.911     bisitz   8962:   float:left;
                   8963:   margin-right:10px;
1.747     neumanie 8964: }
1.795     www      8965: 
                   8966: .LC_Clear_AboutMe_Image {
1.911     bisitz   8967:   clear:left;
1.747     neumanie 8968: }
1.795     www      8969: 
1.721     harmsja  8970: dl.LC_ListStyleClean dt {
1.911     bisitz   8971:   padding-right: 5px;
                   8972:   display: table-header-group;
1.693     droeschl 8973: }
                   8974: 
1.721     harmsja  8975: dl.LC_ListStyleClean dd {
1.911     bisitz   8976:   display: table-row;
1.693     droeschl 8977: }
                   8978: 
1.721     harmsja  8979: .LC_ListStyleClean,
                   8980: .LC_ListStyleSimple,
                   8981: .LC_ListStyleNormal,
1.795     www      8982: .LC_ListStyleSpecial {
1.911     bisitz   8983:   /* display:block; */
                   8984:   list-style-position: inside;
                   8985:   list-style-type: none;
                   8986:   overflow: hidden;
                   8987:   padding: 0;
1.693     droeschl 8988: }
                   8989: 
1.721     harmsja  8990: .LC_ListStyleSimple li,
                   8991: .LC_ListStyleSimple dd,
                   8992: .LC_ListStyleNormal li,
                   8993: .LC_ListStyleNormal dd,
                   8994: .LC_ListStyleSpecial li,
1.795     www      8995: .LC_ListStyleSpecial dd {
1.911     bisitz   8996:   margin: 0;
                   8997:   padding: 5px 5px 5px 10px;
                   8998:   clear: both;
1.693     droeschl 8999: }
                   9000: 
1.721     harmsja  9001: .LC_ListStyleClean li,
                   9002: .LC_ListStyleClean dd {
1.911     bisitz   9003:   padding-top: 0;
                   9004:   padding-bottom: 0;
1.693     droeschl 9005: }
                   9006: 
1.721     harmsja  9007: .LC_ListStyleSimple dd,
1.795     www      9008: .LC_ListStyleSimple li {
1.911     bisitz   9009:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 9010: }
                   9011: 
1.721     harmsja  9012: .LC_ListStyleSpecial li,
                   9013: .LC_ListStyleSpecial dd {
1.911     bisitz   9014:   list-style-type: none;
                   9015:   background-color: RGB(220, 220, 220);
                   9016:   margin-bottom: 4px;
1.693     droeschl 9017: }
                   9018: 
1.721     harmsja  9019: table.LC_SimpleTable {
1.911     bisitz   9020:   margin:5px;
                   9021:   border:solid 1px $lg_border_color;
1.795     www      9022: }
1.693     droeschl 9023: 
1.721     harmsja  9024: table.LC_SimpleTable tr {
1.911     bisitz   9025:   padding: 0;
                   9026:   border:solid 1px $lg_border_color;
1.693     droeschl 9027: }
1.795     www      9028: 
                   9029: table.LC_SimpleTable thead {
1.911     bisitz   9030:   background:rgb(220,220,220);
1.693     droeschl 9031: }
                   9032: 
1.721     harmsja  9033: div.LC_columnSection {
1.911     bisitz   9034:   display: block;
                   9035:   clear: both;
                   9036:   overflow: hidden;
                   9037:   margin: 0;
1.693     droeschl 9038: }
                   9039: 
1.721     harmsja  9040: div.LC_columnSection>* {
1.911     bisitz   9041:   float: left;
                   9042:   margin: 10px 20px 10px 0;
                   9043:   overflow:hidden;
1.693     droeschl 9044: }
1.721     harmsja  9045: 
1.795     www      9046: table em {
1.911     bisitz   9047:   font-weight: bold;
                   9048:   font-style: normal;
1.748     schulted 9049: }
1.795     www      9050: 
1.779     bisitz   9051: table.LC_tableBrowseRes,
1.795     www      9052: table.LC_tableOfContent {
1.911     bisitz   9053:   border:none;
                   9054:   border-spacing: 1px;
                   9055:   padding: 3px;
                   9056:   background-color: #FFFFFF;
                   9057:   font-size: 90%;
1.753     droeschl 9058: }
1.789     droeschl 9059: 
1.911     bisitz   9060: table.LC_tableOfContent {
                   9061:   border-collapse: collapse;
1.789     droeschl 9062: }
                   9063: 
1.771     droeschl 9064: table.LC_tableBrowseRes a,
1.768     schulted 9065: table.LC_tableOfContent a {
1.911     bisitz   9066:   background-color: transparent;
                   9067:   text-decoration: none;
1.753     droeschl 9068: }
                   9069: 
1.795     www      9070: table.LC_tableOfContent img {
1.911     bisitz   9071:   border: none;
                   9072:   height: 1.3em;
                   9073:   vertical-align: text-bottom;
                   9074:   margin-right: 0.3em;
1.753     droeschl 9075: }
1.757     schulted 9076: 
1.795     www      9077: a#LC_content_toolbar_firsthomework {
1.911     bisitz   9078:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  9079: }
                   9080: 
1.795     www      9081: a#LC_content_toolbar_everything {
1.911     bisitz   9082:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  9083: }
                   9084: 
1.795     www      9085: a#LC_content_toolbar_uncompleted {
1.911     bisitz   9086:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  9087: }
                   9088: 
1.795     www      9089: #LC_content_toolbar_clearbubbles {
1.911     bisitz   9090:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  9091: }
                   9092: 
1.795     www      9093: a#LC_content_toolbar_changefolder {
1.911     bisitz   9094:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 9095: }
                   9096: 
1.795     www      9097: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   9098:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 9099: }
                   9100: 
1.1043    raeburn  9101: a#LC_content_toolbar_edittoplevel {
                   9102:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   9103: }
                   9104: 
1.1384    raeburn  9105: a#LC_content_toolbar_printout {
                   9106:   background-image:url(/res/adm/pages/printout.gif);
                   9107: }
                   9108: 
1.795     www      9109: ul#LC_toolbar li a:hover {
1.911     bisitz   9110:   background-position: bottom center;
1.757     schulted 9111: }
                   9112: 
1.795     www      9113: ul#LC_toolbar {
1.911     bisitz   9114:   padding: 0;
                   9115:   margin: 2px;
                   9116:   list-style:none;
                   9117:   position:relative;
                   9118:   background-color:white;
1.1082    raeburn  9119:   overflow: auto;
1.757     schulted 9120: }
                   9121: 
1.795     www      9122: ul#LC_toolbar li {
1.911     bisitz   9123:   border:1px solid white;
                   9124:   padding: 0;
                   9125:   margin: 0;
                   9126:   float: left;
                   9127:   display:inline;
                   9128:   vertical-align:middle;
1.1082    raeburn  9129:   white-space: nowrap;
1.911     bisitz   9130: }
1.757     schulted 9131: 
1.783     amueller 9132: 
1.795     www      9133: a.LC_toolbarItem {
1.911     bisitz   9134:   display:block;
                   9135:   padding: 0;
                   9136:   margin: 0;
                   9137:   height: 32px;
                   9138:   width: 32px;
                   9139:   color:white;
                   9140:   border: none;
                   9141:   background-repeat:no-repeat;
                   9142:   background-color:transparent;
1.757     schulted 9143: }
                   9144: 
1.915     droeschl 9145: ul.LC_funclist {
                   9146:     margin: 0;
                   9147:     padding: 0.5em 1em 0.5em 0;
                   9148: }
                   9149: 
1.933     droeschl 9150: ul.LC_funclist > li:first-child {
                   9151:     font-weight:bold; 
                   9152:     margin-left:0.8em;
                   9153: }
                   9154: 
1.915     droeschl 9155: ul.LC_funclist + ul.LC_funclist {
                   9156:     /* 
                   9157:        left border as a seperator if we have more than
                   9158:        one list 
                   9159:     */
                   9160:     border-left: 1px solid $sidebg;
                   9161:     /* 
                   9162:        this hides the left border behind the border of the 
                   9163:        outer box if element is wrapped to the next 'line' 
                   9164:     */
                   9165:     margin-left: -1px;
                   9166: }
                   9167: 
1.843     bisitz   9168: ul.LC_funclist li {
1.915     droeschl 9169:   display: inline;
1.782     bisitz   9170:   white-space: nowrap;
1.915     droeschl 9171:   margin: 0 0 0 25px;
                   9172:   line-height: 150%;
1.782     bisitz   9173: }
                   9174: 
1.974     wenzelju 9175: .LC_hidden {
                   9176:   display: none;
                   9177: }
                   9178: 
1.1030    www      9179: .LCmodal-overlay {
                   9180: 		position:fixed;
                   9181: 		top:0;
                   9182: 		right:0;
                   9183: 		bottom:0;
                   9184: 		left:0;
                   9185: 		height:100%;
                   9186: 		width:100%;
                   9187: 		margin:0;
                   9188: 		padding:0;
                   9189: 		background:#999;
                   9190: 		opacity:.75;
                   9191: 		filter: alpha(opacity=75);
                   9192: 		-moz-opacity: 0.75;
                   9193: 		z-index:101;
                   9194: }
                   9195: 
                   9196: * html .LCmodal-overlay {   
                   9197: 		position: absolute;
                   9198: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9199: }
                   9200: 
                   9201: .LCmodal-window {
                   9202: 		position:fixed;
                   9203: 		top:50%;
                   9204: 		left:50%;
                   9205: 		margin:0;
                   9206: 		padding:0;
                   9207: 		z-index:102;
                   9208: 	}
                   9209: 
                   9210: * html .LCmodal-window {
                   9211: 		position:absolute;
                   9212: }
                   9213: 
                   9214: .LCclose-window {
                   9215: 		position:absolute;
                   9216: 		width:32px;
                   9217: 		height:32px;
                   9218: 		right:8px;
                   9219: 		top:8px;
                   9220: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9221: 		text-indent:-99999px;
                   9222: 		overflow:hidden;
                   9223: 		cursor:pointer;
                   9224: }
                   9225: 
1.1369    raeburn  9226: .LCisDisabled {
                   9227:   cursor: not-allowed;
                   9228:   opacity: 0.5;
                   9229: }
                   9230: 
                   9231: a[aria-disabled="true"] {
                   9232:   color: currentColor;
                   9233:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9234:   pointer-events: none;
                   9235:   text-decoration: none;
                   9236: }
                   9237: 
1.1335    raeburn  9238: pre.LC_wordwrap {
                   9239:   white-space: pre-wrap;
                   9240:   white-space: -moz-pre-wrap;
                   9241:   white-space: -pre-wrap;
                   9242:   white-space: -o-pre-wrap;
                   9243:   word-wrap: break-word;
                   9244: }
                   9245: 
1.1100    raeburn  9246: /*
1.1231    damieng  9247:   styles used for response display
                   9248: */
                   9249: div.LC_radiofoil, div.LC_rankfoil {
                   9250:   margin: .5em 0em .5em 0em;
                   9251: }
                   9252: table.LC_itemgroup {
                   9253:   margin-top: 1em;
                   9254: }
                   9255: 
                   9256: /*
1.1100    raeburn  9257:   styles used by TTH when "Default set of options to pass to tth/m
                   9258:   when converting TeX" in course settings has been set
                   9259: 
                   9260:   option passed: -t
                   9261: 
                   9262: */
                   9263: 
                   9264: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9265: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9266: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9267: td div.norm {line-height:normal;}
                   9268: 
                   9269: /*
                   9270:   option passed -y3
                   9271: */
                   9272: 
                   9273: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9274: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9275: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9276: 
1.1230    damieng  9277: /*
                   9278:   sections with roles, for content only
                   9279: */
                   9280: section[class^="role-"] {
                   9281:   padding-left: 10px;
                   9282:   padding-right: 5px;
                   9283:   margin-top: 8px;
                   9284:   margin-bottom: 8px;
                   9285:   border: 1px solid #2A4;
                   9286:   border-radius: 5px;
                   9287:   box-shadow: 0px 1px 1px #BBB;
                   9288: }
                   9289: section[class^="role-"]>h1 {
                   9290:   position: relative;
                   9291:   margin: 0px;
                   9292:   padding-top: 10px;
                   9293:   padding-left: 40px;
                   9294: }
                   9295: section[class^="role-"]>h1:before {
                   9296:   position: absolute;
                   9297:   left: -5px;
                   9298:   top: 5px;
                   9299: }
                   9300: section.role-activity>h1:before {
                   9301:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9302: }
                   9303: section.role-advice>h1:before {
                   9304:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9305: }
                   9306: section.role-bibliography>h1:before {
                   9307:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9308: }
                   9309: section.role-citation>h1:before {
                   9310:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9311: }
                   9312: section.role-conclusion>h1:before {
                   9313:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9314: }
                   9315: section.role-definition>h1:before {
                   9316:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9317: }
                   9318: section.role-demonstration>h1:before {
                   9319:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9320: }
                   9321: section.role-example>h1:before {
                   9322:   content:url('/adm/daxe/images/section_icons/example.png');
                   9323: }
                   9324: section.role-explanation>h1:before {
                   9325:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9326: }
                   9327: section.role-introduction>h1:before {
                   9328:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9329: }
                   9330: section.role-method>h1:before {
                   9331:   content:url('/adm/daxe/images/section_icons/method.png');
                   9332: }
                   9333: section.role-more_information>h1:before {
                   9334:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9335: }
                   9336: section.role-objectives>h1:before {
                   9337:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9338: }
                   9339: section.role-prerequisites>h1:before {
                   9340:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9341: }
                   9342: section.role-remark>h1:before {
                   9343:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9344: }
                   9345: section.role-reminder>h1:before {
                   9346:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9347: }
                   9348: section.role-summary>h1:before {
                   9349:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9350: }
                   9351: section.role-syntax>h1:before {
                   9352:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9353: }
                   9354: section.role-warning>h1:before {
                   9355:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9356: }
                   9357: 
1.1269    raeburn  9358: #LC_minitab_header {
                   9359:   float:left;
                   9360:   width:100%;
                   9361:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9362:   font-size:93%;
                   9363:   line-height:normal;
                   9364:   margin: 0.5em 0 0.5em 0;
                   9365: }
                   9366: #LC_minitab_header ul {
                   9367:   margin:0;
                   9368:   padding:10px 10px 0;
                   9369:   list-style:none;
                   9370: }
                   9371: #LC_minitab_header li {
                   9372:   float:left;
                   9373:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9374:   margin:0;
                   9375:   padding:0 0 0 9px;
                   9376: }
                   9377: #LC_minitab_header a {
                   9378:   display:block;
                   9379:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9380:   padding:5px 15px 4px 6px;
                   9381: }
                   9382: #LC_minitab_header #LC_current_minitab {
                   9383:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9384: }
                   9385: #LC_minitab_header #LC_current_minitab a {
                   9386:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9387:   padding-bottom:5px;
                   9388: }
                   9389: 
                   9390: 
1.343     albertel 9391: END
                   9392: }
                   9393: 
1.306     albertel 9394: =pod
                   9395: 
                   9396: =item * &headtag()
                   9397: 
                   9398: Returns a uniform footer for LON-CAPA web pages.
                   9399: 
1.307     albertel 9400: Inputs: $title - optional title for the head
                   9401:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9402:         $args - optional arguments
1.319     albertel 9403:             force_register - if is true call registerurl so the remote is 
                   9404:                              informed
1.415     albertel 9405:             redirect       -> array ref of
                   9406:                                    1- seconds before redirect occurs
                   9407:                                    2- url to redirect to
                   9408:                                    3- whether the side effect should occur
1.315     albertel 9409:                            (side effect of setting 
                   9410:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9411:                                redirected to)
                   9412:                                    4- whether the redirect target should be
                   9413:                                       the opener of the current (pop-up)
                   9414:                                       window (side effect of setting
                   9415:                                       $env{'internal.head.to_opener'} to
                   9416:                                       1, if true.
1.1388    raeburn  9417:                                    5- whether encrypt check should be skipped
1.352     albertel 9418:             domain         -> force to color decorate a page for a specific
                   9419:                                domain
                   9420:             function       -> force usage of a specific rolish color scheme
                   9421:             bgcolor        -> override the default page bgcolor
1.460     albertel 9422:             no_auto_mt_title
                   9423:                            -> prevent &mt()ing the title arg
1.464     albertel 9424: 
1.306     albertel 9425: =cut
                   9426: 
                   9427: sub headtag {
1.313     albertel 9428:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9429:     
1.363     albertel 9430:     my $function = $args->{'function'} || &get_users_function();
                   9431:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9432:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9433:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9434:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9435: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9436: 		   #time(),
1.418     albertel 9437: 		   $env{'environment.color.timestamp'},
1.363     albertel 9438: 		   $function,$domain,$bgcolor);
                   9439: 
1.369     www      9440:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9441: 
1.308     albertel 9442:     my $result =
                   9443: 	'<head>'.
1.1160    raeburn  9444: 	&font_settings($args);
1.319     albertel 9445: 
1.1188    raeburn  9446:     my $inhibitprint;
                   9447:     if ($args->{'print_suppress'}) {
                   9448:         $inhibitprint = &print_suppression();
                   9449:     }
1.1064    raeburn  9450: 
1.1439    raeburn  9451:     if (!$args->{'frameset'} && !$args->{'switchserver'}) {
1.461     albertel 9452: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9453:     }
1.962     droeschl 9454:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9455:         $result .= Apache::lonxml::display_title();
1.319     albertel 9456:     }
1.436     albertel 9457:     if (!$args->{'no_nav_bar'} 
                   9458: 	&& !$args->{'only_body'}
1.1438    raeburn  9459: 	&& !$args->{'frameset'}
                   9460: 	&& !$args->{'switchserver'}) {
1.1154    raeburn  9461: 	$result .= &help_menu_js($httphost);
1.1032    www      9462:         $result.=&modal_window();
1.1038    www      9463:         $result.=&togglebox_script();
1.1034    www      9464:         $result.=&wishlist_window();
1.1041    www      9465:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9466:     } else {
                   9467:         if ($args->{'add_modal'}) {
                   9468:            $result.=&modal_window();
                   9469:         }
                   9470:         if ($args->{'add_wishlist'}) {
                   9471:            $result.=&wishlist_window();
                   9472:         }
1.1038    www      9473:         if ($args->{'add_togglebox'}) {
                   9474:            $result.=&togglebox_script();
                   9475:         }
1.1041    www      9476:         if ($args->{'add_progressbar'}) {
                   9477:            $result.=&LCprogressbarUpdate_script();
                   9478:         }
1.436     albertel 9479:     }
1.314     albertel 9480:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9481: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9482:         if (!$skip_enc_check) {
                   9483:             $url = &Apache::lonenc::check_encrypt($url);
                   9484:         }
1.414     albertel 9485: 	if (!$inhibit_continue) {
                   9486: 	    $env{'internal.head.redirect'} = $url;
                   9487: 	}
1.1386    raeburn  9488: 	$result.=<<"ADDMETA";
1.313     albertel 9489: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9490: ADDMETA
                   9491:         if ($to_opener) {
                   9492:             $env{'internal.head.to_opener'} = 1;
                   9493:             my $dest = &js_escape($url);
                   9494:             my $timeout = int($time * 1000);
                   9495:             $result .=<<"ENDJS";
                   9496: <script type="text/javascript">
                   9497: // <![CDATA[
                   9498: function LC_To_Opener() {
                   9499:     var dest = '$dest';
                   9500:     if (dest != '') {
                   9501:         if (window.opener != null && !window.opener.closed) {
                   9502:             window.opener.location.href=dest;
                   9503:             window.close();
                   9504:         } else {
                   9505:             window.location.href=dest;
                   9506:         }
                   9507:     }
                   9508: }
                   9509: \$(document).ready(function () {
                   9510:     setTimeout('LC_To_Opener()',$timeout);
                   9511: });
                   9512: // ]]>
                   9513: </script>
                   9514: ENDJS
                   9515:         } else {
                   9516:             $result.=<<"ADDMETA";
1.344     albertel 9517: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9518: ADDMETA
1.1386    raeburn  9519:         }
1.1210    raeburn  9520:     } else {
                   9521:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9522:             my $requrl = $env{'request.uri'};
                   9523:             if ($requrl eq '') {
                   9524:                 $requrl = $ENV{'REQUEST_URI'};
                   9525:                 $requrl =~ s/\?.+$//;
                   9526:             }
                   9527:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9528:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9529:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9530:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9531:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9532:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9533:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9534:                     my ($offload,$offloadoth);
1.1210    raeburn  9535:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9536:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9537:                             $offload = 1;
1.1353    raeburn  9538:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9539:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9540:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9541:                                     $offloadoth = 1;
                   9542:                                     $dom_in_use = $env{'user.domain'};
                   9543:                                 }
                   9544:                             }
1.1340    raeburn  9545:                         }
                   9546:                     }
                   9547:                     unless ($offload) {
                   9548:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9549:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9550:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9551:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9552:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9553:                                         $offload = 1;
1.1352    raeburn  9554:                                         $offloadoth = 1;
1.1340    raeburn  9555:                                         $dom_in_use = $env{'user.domain'};
                   9556:                                     }
1.1210    raeburn  9557:                                 }
1.1340    raeburn  9558:                             }
                   9559:                         }
                   9560:                     }
                   9561:                     if ($offload) {
1.1358    raeburn  9562:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9563:                         if (($newserver eq '') && ($offloadoth)) {
                   9564:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9565:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9566:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9567:                             }
                   9568:                         }
1.1340    raeburn  9569:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9570:                             my $numsec = 5;
                   9571:                             my $timeout = $numsec * 1000;
                   9572:                             my ($newurl,$locknum,%locks,$msg);
                   9573:                             if ($env{'request.role.adv'}) {
                   9574:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9575:                             }
                   9576:                             my $disable_submit = 0;
                   9577:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9578:                                 $disable_submit = 1;
                   9579:                             }
                   9580:                             if ($locknum) {
                   9581:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9582:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9583:                                        join(", ",sort(values(%locks)))."\n";
                   9584:                                 if (&show_course()) {
                   9585:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9586:                                 } else {
                   9587:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9588:                                 }
1.1340    raeburn  9589:                             } else {
                   9590:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9591:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9592:                                 }
                   9593:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9594:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9595:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9596:                                     $newurl .= '&role='.$env{'request.role'};
                   9597:                                 }
                   9598:                                 if ($env{'request.symb'}) {
                   9599:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9600:                                     if ($shownsymb =~ m{^/enc/}) {
                   9601:                                         my $reqdmajor = 2;
                   9602:                                         my $reqdminor = 11;
                   9603:                                         my $reqdsubminor = 3;
                   9604:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9605:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9606:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9607:                                         if (($major eq '' && $minor eq '') ||
                   9608:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9609:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9610:                                              ($reqdsubminor > $subminor))))) {
                   9611:                                             undef($shownsymb);
                   9612:                                         }
1.1210    raeburn  9613:                                     }
1.1340    raeburn  9614:                                     if ($shownsymb) {
                   9615:                                         &js_escape(\$shownsymb);
                   9616:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9617:                                     }
1.1340    raeburn  9618:                                 } else {
                   9619:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9620:                                     &js_escape(\$shownurl);
                   9621:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9622:                                 }
1.1340    raeburn  9623:                             }
                   9624:                             &js_escape(\$msg);
                   9625:                             $result.=<<OFFLOAD
1.1210    raeburn  9626: <meta http-equiv="pragma" content="no-cache" />
                   9627: <script type="text/javascript">
1.1215    raeburn  9628: // <![CDATA[
1.1210    raeburn  9629: function LC_Offload_Now() {
                   9630:     var dest = "$newurl";
                   9631:     if (dest != '') {
                   9632:         window.location.href="$newurl";
                   9633:     }
                   9634: }
1.1214    raeburn  9635: \$(document).ready(function () {
                   9636:     window.alert('$msg');
                   9637:     if ($disable_submit) {
1.1210    raeburn  9638:         \$(".LC_hwk_submit").prop("disabled", true);
                   9639:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9640:     }
                   9641:     setTimeout('LC_Offload_Now()', $timeout);
                   9642: });
1.1215    raeburn  9643: // ]]>
1.1210    raeburn  9644: </script>
                   9645: OFFLOAD
                   9646:                         }
                   9647:                     }
                   9648:                 }
                   9649:             }
                   9650:         }
1.313     albertel 9651:     }
1.306     albertel 9652:     if (!defined($title)) {
                   9653: 	$title = 'The LearningOnline Network with CAPA';
                   9654:     }
1.460     albertel 9655:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1432    raeburn  9656:     if ($title =~ /^LON-CAPA\s+/) {
                   9657:         $result .= '<title> '.$title.'</title>';
                   9658:     } else {
                   9659:         $result .= '<title> LON-CAPA '.$title.'</title>';
                   9660:     }
                   9661:     $result .= "\n".'<link rel="stylesheet" type="text/css" href="'.$url.'"';
1.1168    raeburn  9662:     if (!$args->{'frameset'}) {
                   9663:         $result .= ' /';
                   9664:     }
                   9665:     $result .= '>' 
1.1064    raeburn  9666:         .$inhibitprint
1.414     albertel 9667: 	.$head_extra;
1.1242    raeburn  9668:     my $clientmobile;
                   9669:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9670:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9671:     } else {
                   9672:         $clientmobile = $env{'browser.mobile'};
                   9673:     }
                   9674:     if ($clientmobile) {
1.1137    raeburn  9675:         $result .= '
1.1435    raeburn  9676: <meta name="viewport" content="width=device-width, initial-scale=1.0">
1.1137    raeburn  9677: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9678:     }
1.1278    raeburn  9679:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9680:     return $result.'</head>';
1.306     albertel 9681: }
                   9682: 
                   9683: =pod
                   9684: 
1.340     albertel 9685: =item * &font_settings()
                   9686: 
                   9687: Returns neccessary <meta> to set the proper encoding
                   9688: 
1.1160    raeburn  9689: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9690: 
                   9691: =cut
                   9692: 
                   9693: sub font_settings {
1.1160    raeburn  9694:     my ($args) = @_;
1.340     albertel 9695:     my $headerstring='';
1.1160    raeburn  9696:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9697:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9698:         $headerstring.=
                   9699:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9700:         if (!$args->{'frameset'}) {
                   9701: 	    $headerstring.= ' /';
                   9702:         }
                   9703: 	$headerstring .= '>'."\n";
1.340     albertel 9704:     }
                   9705:     return $headerstring;
                   9706: }
                   9707: 
1.341     albertel 9708: =pod
                   9709: 
1.1064    raeburn  9710: =item * &print_suppression()
                   9711: 
                   9712: In course context returns css which causes the body to be blank when media="print",
                   9713: if printout generation is unavailable for the current resource.
                   9714: 
                   9715: This could be because:
                   9716: 
                   9717: (a) printstartdate is in the future
                   9718: 
                   9719: (b) printenddate is in the past
                   9720: 
                   9721: (c) there is an active exam block with "printout"
                   9722: functionality blocked
                   9723: 
                   9724: Users with pav, pfo or evb privileges are exempt.
                   9725: 
                   9726: Inputs: none
                   9727: 
                   9728: =cut
                   9729: 
                   9730: 
                   9731: sub print_suppression {
                   9732:     my $noprint;
                   9733:     if ($env{'request.course.id'}) {
                   9734:         my $scope = $env{'request.course.id'};
                   9735:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9736:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9737:             return;
                   9738:         }
                   9739:         if ($env{'request.course.sec'} ne '') {
                   9740:             $scope .= "/$env{'request.course.sec'}";
                   9741:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9742:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9743:                 return;
1.1064    raeburn  9744:             }
                   9745:         }
                   9746:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9747:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9748:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9749:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9750:         if ($blocked) {
                   9751:             my $checkrole = "cm./$cdom/$cnum";
                   9752:             if ($env{'request.course.sec'} ne '') {
                   9753:                 $checkrole .= "/$env{'request.course.sec'}";
                   9754:             }
                   9755:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9756:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9757:                 $noprint = 1;
                   9758:             }
                   9759:         }
                   9760:         unless ($noprint) {
                   9761:             my $symb = &Apache::lonnet::symbread();
                   9762:             if ($symb ne '') {
                   9763:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9764:                 if (ref($navmap)) {
                   9765:                     my $res = $navmap->getBySymb($symb);
                   9766:                     if (ref($res)) {
                   9767:                         if (!$res->resprintable()) {
                   9768:                             $noprint = 1;
                   9769:                         }
                   9770:                     }
                   9771:                 }
                   9772:             }
                   9773:         }
                   9774:         if ($noprint) {
                   9775:             return <<"ENDSTYLE";
                   9776: <style type="text/css" media="print">
                   9777:     body { display:none }
                   9778: </style>
                   9779: ENDSTYLE
                   9780:         }
                   9781:     }
                   9782:     return;
                   9783: }
                   9784: 
                   9785: =pod
                   9786: 
1.341     albertel 9787: =item * &xml_begin()
                   9788: 
                   9789: Returns the needed doctype and <html>
                   9790: 
                   9791: Inputs: none
                   9792: 
                   9793: =cut
                   9794: 
                   9795: sub xml_begin {
1.1168    raeburn  9796:     my ($is_frameset) = @_;
1.341     albertel 9797:     my $output='';
                   9798: 
                   9799:     if ($env{'browser.mathml'}) {
                   9800: 	$output='<?xml version="1.0"?>'
                   9801:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9802: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9803:             
                   9804: #	    .'<!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">] >'
                   9805: 	    .'<!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">'
                   9806:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9807: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9808:     } elsif ($is_frameset) {
                   9809:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9810:                 '<html>'."\n";
1.341     albertel 9811:     } else {
1.1168    raeburn  9812: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9813:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9814:     }
                   9815:     return $output;
                   9816: }
1.340     albertel 9817: 
                   9818: =pod
                   9819: 
1.306     albertel 9820: =item * &start_page()
                   9821: 
                   9822: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9823: 
1.648     raeburn  9824: Inputs:
                   9825: 
                   9826: =over 4
                   9827: 
                   9828: $title - optional title for the page
                   9829: 
                   9830: $head_extra - optional extra HTML to incude inside the <head>
                   9831: 
                   9832: $args - additional optional args supported are:
                   9833: 
                   9834: =over 8
                   9835: 
                   9836:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9837:                                     arg on
1.814     bisitz   9838:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9839:              add_entries    -> additional attributes to add to the  <body>
                   9840:              domain         -> force to color decorate a page for a 
1.317     albertel 9841:                                     specific domain
1.648     raeburn  9842:              function       -> force usage of a specific rolish color
1.317     albertel 9843:                                     scheme
1.648     raeburn  9844:              redirect       -> see &headtag()
                   9845:              bgcolor        -> override the default page bg color
                   9846:              js_ready       -> return a string ready for being used in 
1.317     albertel 9847:                                     a javascript writeln
1.648     raeburn  9848:              html_encode    -> return a string ready for being used in 
1.320     albertel 9849:                                     a html attribute
1.648     raeburn  9850:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9851:                                     $forcereg arg
1.648     raeburn  9852:              frameset       -> if true will start with a <frameset>
1.330     albertel 9853:                                     rather than <body>
1.648     raeburn  9854:              skip_phases    -> hash ref of 
1.338     albertel 9855:                                     head -> skip the <html><head> generation
                   9856:                                     body -> skip all <body> generation
1.648     raeburn  9857:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9858:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9859:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1437    raeburn  9860:              bread_crumbs_style -> breadcrumbs are contained within <div id="LC_breadcrumbs">,
                   9861:                                    and &standard_css() contains CSS for #LC_breadcrumbs, if you want
                   9862:                                    to override those values, or add to them, specify the value to
                   9863:                                    include in the style attribute to include in the div tag by using
                   9864:                                    bread_crumbs_style (e.g., overflow: visible)
1.1272    raeburn  9865:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9866:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9867:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9868:                                specific group
                   9869:              use_absolute   -> for request for external resource or syllabus, this
                   9870:                                will contain https://<hostname> if server uses
                   9871:                                https (as per hosts.tab), but request is for http
                   9872:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9873:              links_disabled -> Links in primary and secondary menus are disabled
                   9874:                                (Can enable them once page has loaded - see lonroles.pm
                   9875:                                for an example).
1.1380    raeburn  9876:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9877: 
1.648     raeburn  9878: =back
1.460     albertel 9879: 
1.648     raeburn  9880: =back
1.562     albertel 9881: 
1.306     albertel 9882: =cut
                   9883: 
                   9884: sub start_page {
1.309     albertel 9885:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9886:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9887: 
1.315     albertel 9888:     $env{'internal.start_page'}++;
1.1359    raeburn  9889:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9890: 
1.338     albertel 9891:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9892:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9893:     }
1.1316    raeburn  9894: 
                   9895:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9896:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9897:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9898:                 $args->{'no_primary_menu'} = 1;
                   9899:             }
                   9900:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9901:                 $args->{'no_inline_menu'} = 1;
                   9902:             }
                   9903:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9904:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9905:             }
                   9906:         } else {
                   9907:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9908:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9909:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9910:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9911:                     $args->{'no_primary_menu'} = 1;
                   9912:                 }
                   9913:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9914:                     $args->{'no_inline_menu'} = 1;
                   9915:                 }
                   9916:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9917:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9918:                 }
                   9919:             }
                   9920:         }
1.1316    raeburn  9921:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9922:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9923:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9924:     } elsif ($env{'request.course.id'}) {
                   9925:         my $expiretime=600;
                   9926:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9927:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9928:         }
                   9929:         my ($deeplinkmenu,$menuref);
                   9930:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9931:         if ($menucoll) {
                   9932:             if (ref($menuref) eq 'HASH') {
                   9933:                 %menu = %{$menuref};
                   9934:             }
                   9935:             if ($menu{'top'} eq 'n') {
                   9936:                 $args->{'no_primary_menu'} = 1;
                   9937:             }
                   9938:             if ($menu{'inline'} eq 'n') {
                   9939:                 unless (&Apache::lonnet::allowed('opa')) {
                   9940:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9941:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9942:                     my $crstype = &course_type();
                   9943:                     my $now = time;
                   9944:                     my $ccrole;
                   9945:                     if ($crstype eq 'Community') {
                   9946:                         $ccrole = 'co';
                   9947:                     } else {
                   9948:                         $ccrole = 'cc';
                   9949:                     }
                   9950:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9951:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9952:                         if ((($start) && ($start<0)) ||
                   9953:                             (($end) && ($end<$now))  ||
                   9954:                             (($start) && ($now<$start))) {
                   9955:                             $args->{'no_inline_menu'} = 1;
                   9956:                         }
                   9957:                     } else {
                   9958:                         $args->{'no_inline_menu'} = 1;
                   9959:                     }
                   9960:                 }
                   9961:             }
                   9962:         }
1.1316    raeburn  9963:     }
1.1359    raeburn  9964: 
1.1385    raeburn  9965:     my $showncrumbs;
1.338     albertel 9966:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9967: 	if ($args->{'frameset'}) {
                   9968: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9969: 						$args->{'add_entries'});
                   9970: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9971:         } else {
                   9972:             $result .=
                   9973:                 &bodytag($title, 
                   9974:                          $args->{'function'},       $args->{'add_entries'},
                   9975:                          $args->{'only_body'},      $args->{'domain'},
                   9976:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9977:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9978:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9979:                          \%menu,\$showncrumbs);
1.831     bisitz   9980:         }
1.330     albertel 9981:     }
1.338     albertel 9982: 
1.315     albertel 9983:     if ($args->{'js_ready'}) {
1.713     kaisler  9984: 		$result = &js_ready($result);
1.315     albertel 9985:     }
1.320     albertel 9986:     if ($args->{'html_encode'}) {
1.713     kaisler  9987: 		$result = &html_encode($result);
                   9988:     }
                   9989: 
1.813     bisitz   9990:     # Preparation for new and consistent functionlist at top of screen
                   9991:     # if ($args->{'functionlist'}) {
                   9992:     #            $result .= &build_functionlist();
                   9993:     #}
                   9994: 
1.964     droeschl 9995:     # Don't add anything more if only_body wanted or in const space
                   9996:     return $result if    $args->{'only_body'} 
                   9997:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9998: 
                   9999:     #Breadcrumbs
1.758     kaisler  10000:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  10001:         unless ($showncrumbs) {
1.758     kaisler  10002: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   10003: 		#if any br links exists, add them to the breadcrumbs
                   10004: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   10005: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   10006: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   10007: 			}
                   10008: 		}
1.1096    raeburn  10009:                 # if @advtools array contains items add then to the breadcrumbs
                   10010:                 if (@advtools > 0) {
                   10011:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   10012:                 }
1.1272    raeburn  10013:                 my $menulink;
                   10014:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   10015:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  10016:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  10017:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   10018:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   10019:                      (!$env{'request.role.adv'}))) {
                   10020:                     $menulink = 0;
                   10021:                 } else {
                   10022:                     undef($menulink);
                   10023:                 }
1.1385    raeburn  10024:                 my $linkprotout;
                   10025:                 if ($env{'request.deeplink.login'}) {
                   10026:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   10027:                     if ($linkprotout) {
                   10028:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   10029:                     }
                   10030:                 }
1.758     kaisler  10031: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   10032: 		if(exists($args->{'bread_crumbs_component'})){
1.1437    raeburn  10033: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},
                   10034:                                                                        '',$menulink,'',
                   10035:                                                                        $args->{'bread_crumbs_style'});
1.1237    raeburn  10036:                 } else {
1.1437    raeburn  10037: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink,'',
                   10038:                                                                        $args->{'bread_crumbs_style'});
1.758     kaisler  10039: 		}
1.1385    raeburn  10040:         }
1.320     albertel 10041:     }
1.315     albertel 10042:     return $result;
1.306     albertel 10043: }
                   10044: 
                   10045: sub end_page {
1.315     albertel 10046:     my ($args) = @_;
                   10047:     $env{'internal.end_page'}++;
1.330     albertel 10048:     my $result;
1.335     albertel 10049:     if ($args->{'discussion'}) {
                   10050: 	my ($target,$parser);
                   10051: 	if (ref($args->{'discussion'})) {
                   10052: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   10053: 				$args->{'discussion'}{'parser'});
                   10054: 	}
                   10055: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   10056:     }
1.330     albertel 10057:     if ($args->{'frameset'}) {
                   10058: 	$result .= '</frameset>';
                   10059:     } else {
1.635     raeburn  10060: 	$result .= &endbodytag($args);
1.330     albertel 10061:     }
1.1080    raeburn  10062:     unless ($args->{'notbody'}) {
                   10063:         $result .= "\n</html>";
                   10064:     }
1.330     albertel 10065: 
1.315     albertel 10066:     if ($args->{'js_ready'}) {
1.317     albertel 10067: 	$result = &js_ready($result);
1.315     albertel 10068:     }
1.335     albertel 10069: 
1.320     albertel 10070:     if ($args->{'html_encode'}) {
                   10071: 	$result = &html_encode($result);
                   10072:     }
1.335     albertel 10073: 
1.315     albertel 10074:     return $result;
                   10075: }
                   10076: 
1.1359    raeburn  10077: sub menucoll_in_effect {
                   10078:     my ($menucoll,$deeplinkmenu,%menu);
                   10079:     if ($env{'request.course.id'}) {
                   10080:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  10081:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  10082:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  10083:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10084:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10085:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   10086:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   10087:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10088:                     if (ref($navmap)) {
                   10089:                         $deeplink = $navmap->get_mapparam(undef,
                   10090:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   10091:                                                           '0.deeplink');
1.1370    raeburn  10092:                     } else {
                   10093:                         $check_login_symb = 1;
1.1362    raeburn  10094:                     }
                   10095:                 } else {
1.1370    raeburn  10096:                     my $symb = &Apache::lonnet::symbread();
                   10097:                     if ($symb) {
                   10098:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   10099:                     } else {
                   10100:                         $check_login_symb = 1;
                   10101:                     }
1.1362    raeburn  10102:                 }
                   10103:             } else {
1.1370    raeburn  10104:                 $check_login_symb = 1;
                   10105:             }
                   10106:             if ($check_login_symb) {
1.1362    raeburn  10107:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   10108:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   10109:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   10110:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10111:                     if (ref($navmap)) {
                   10112:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   10113:                     }
                   10114:                 } else {
                   10115:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   10116:                 }
                   10117:             }
1.1359    raeburn  10118:             if ($deeplink ne '') {
1.1378    raeburn  10119:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  10120:                 if ($display =~ /^\d+$/) {
                   10121:                     $deeplinkmenu = 1;
                   10122:                     $menucoll = $display;
                   10123:                 }
                   10124:             }
                   10125:         }
                   10126:         if ($menucoll) {
                   10127:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   10128:         }
                   10129:     }
                   10130:     return ($menucoll,$deeplinkmenu,\%menu);
                   10131: }
                   10132: 
1.1362    raeburn  10133: sub deeplink_login_symb {
                   10134:     my ($cnum,$cdom) = @_;
                   10135:     my $login_symb;
                   10136:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  10137:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   10138:     }
                   10139:     return $login_symb;
                   10140: }
                   10141: 
                   10142: sub symb_from_tinyurl {
                   10143:     my ($url,$cnum,$cdom) = @_;
                   10144:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   10145:         my $key = $1;
                   10146:         my ($tinyurl,$login);
                   10147:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   10148:         if (defined($cached)) {
                   10149:             $tinyurl = $result;
                   10150:         } else {
                   10151:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   10152:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   10153:             if ($currtiny{$key} ne '') {
                   10154:                 $tinyurl = $currtiny{$key};
                   10155:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  10156:             }
1.1364    raeburn  10157:         }
                   10158:         if ($tinyurl ne '') {
                   10159:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   10160:             if (wantarray) {
                   10161:                 return ($cnumreq,$symb);
                   10162:             } elsif ($cnumreq eq $cnum) {
                   10163:                 return $symb;
1.1362    raeburn  10164:             }
                   10165:         }
                   10166:     }
1.1364    raeburn  10167:     if (wantarray) {
                   10168:         return ();
                   10169:     } else {
                   10170:         return;
                   10171:     }
1.1362    raeburn  10172: }
                   10173: 
1.1405    raeburn  10174: sub usable_exttools {
                   10175:     my %tooltypes;
                   10176:     if ($env{'request.course.id'}) {
                   10177:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10178:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10179:                %tooltypes = (
                   10180:                              crs => 1,
                   10181:                              dom => 1,
                   10182:                             );
                   10183:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10184:                $tooltypes{'crs'} = 1;
                   10185:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10186:                $tooltypes{'dom'} = 1;
                   10187:            }
                   10188:         } else {
                   10189:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10190:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10191:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10192:             if ($crstype eq '') {
                   10193:                 $crstype = 'course';
                   10194:             }
                   10195:             if ($crstype eq 'course') {
                   10196:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10197:                     $crstype = 'official';
                   10198:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10199:                     $crstype = 'textbook';
                   10200:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10201:                     $crstype = 'lti';
                   10202:                 } else {
                   10203:                     $crstype = 'unofficial';
                   10204:                 }
                   10205:             }
                   10206:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10207:             if ($domdefaults{$crstype.'domexttool'}) {
                   10208:                 $tooltypes{'dom'} = 1;
                   10209:             }
                   10210:             if ($domdefaults{$crstype.'exttool'}) {
                   10211:                 $tooltypes{'crs'} = 1;
                   10212:             }
                   10213:         }
                   10214:     }
                   10215:     return %tooltypes;
                   10216: }
                   10217: 
1.1034    www      10218: sub wishlist_window {
                   10219:     return(<<'ENDWISHLIST');
1.1046    raeburn  10220: <script type="text/javascript">
1.1034    www      10221: // <![CDATA[
                   10222: // <!-- BEGIN LON-CAPA Internal
                   10223: function set_wishlistlink(title, path) {
                   10224:     if (!title) {
                   10225:         title = document.title;
                   10226:         title = title.replace(/^LON-CAPA /,'');
                   10227:     }
1.1175    raeburn  10228:     title = encodeURIComponent(title);
1.1203    raeburn  10229:     title = title.replace("'","\\\'");
1.1034    www      10230:     if (!path) {
                   10231:         path = location.pathname;
                   10232:     }
1.1175    raeburn  10233:     path = encodeURIComponent(path);
1.1203    raeburn  10234:     path = path.replace("'","\\\'");
1.1034    www      10235:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10236:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10237: }
                   10238: // END LON-CAPA Internal -->
                   10239: // ]]>
                   10240: </script>
                   10241: ENDWISHLIST
                   10242: }
                   10243: 
1.1030    www      10244: sub modal_window {
                   10245:     return(<<'ENDMODAL');
1.1046    raeburn  10246: <script type="text/javascript">
1.1030    www      10247: // <![CDATA[
                   10248: // <!-- BEGIN LON-CAPA Internal
                   10249: var modalWindow = {
                   10250: 	parent:"body",
                   10251: 	windowId:null,
                   10252: 	content:null,
                   10253: 	width:null,
                   10254: 	height:null,
                   10255: 	close:function()
                   10256: 	{
                   10257: 	        $(".LCmodal-window").remove();
                   10258: 	        $(".LCmodal-overlay").remove();
                   10259: 	},
                   10260: 	open:function()
                   10261: 	{
                   10262: 		var modal = "";
                   10263: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10264: 		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;\">";
                   10265: 		modal += this.content;
                   10266: 		modal += "</div>";	
                   10267: 
                   10268: 		$(this.parent).append(modal);
                   10269: 
                   10270: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10271: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10272: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10273: 	}
                   10274: };
1.1140    raeburn  10275: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10276: 	{
1.1266    raeburn  10277:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10278: 		modalWindow.windowId = "myModal";
                   10279: 		modalWindow.width = width;
                   10280: 		modalWindow.height = height;
1.1196    raeburn  10281: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10282: 		modalWindow.open();
1.1208    raeburn  10283: 	};
1.1030    www      10284: // END LON-CAPA Internal -->
                   10285: // ]]>
                   10286: </script>
                   10287: ENDMODAL
                   10288: }
                   10289: 
                   10290: sub modal_link {
1.1140    raeburn  10291:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10292:     unless ($width) { $width=480; }
                   10293:     unless ($height) { $height=400; }
1.1031    www      10294:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10295:     unless ($transparency) { $transparency='true'; }
                   10296: 
1.1074    raeburn  10297:     my $target_attr;
                   10298:     if (defined($target)) {
                   10299:         $target_attr = 'target="'.$target.'"';
                   10300:     }
                   10301:     return <<"ENDLINK";
1.1336    raeburn  10302: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10303: ENDLINK
1.1030    www      10304: }
                   10305: 
1.1032    www      10306: sub modal_adhoc_script {
1.1365    raeburn  10307:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10308:     my $mathjax;
                   10309:     if ($possmathjax) {
                   10310:         $mathjax = <<'ENDJAX';
                   10311:                if (typeof MathJax == 'object') {
                   10312:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10313:                }
                   10314: ENDJAX
                   10315:     }
1.1032    www      10316:     return (<<ENDADHOC);
1.1046    raeburn  10317: <script type="text/javascript">
1.1032    www      10318: // <![CDATA[
                   10319:         var $funcname = function()
                   10320:         {
                   10321:                 modalWindow.windowId = "myModal";
                   10322:                 modalWindow.width = $width;
                   10323:                 modalWindow.height = $height;
                   10324:                 modalWindow.content = '$content';
                   10325:                 modalWindow.open();
1.1365    raeburn  10326:                 $mathjax
1.1032    www      10327:         };  
                   10328: // ]]>
                   10329: </script>
                   10330: ENDADHOC
                   10331: }
                   10332: 
1.1041    www      10333: sub modal_adhoc_inner {
1.1365    raeburn  10334:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10335:     my $innerwidth=$width-20;
                   10336:     $content=&js_ready(
1.1140    raeburn  10337:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10338:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10339:                  $content.
1.1041    www      10340:                  &end_scrollbox().
1.1140    raeburn  10341:                  &end_page()
1.1041    www      10342:              );
1.1365    raeburn  10343:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10344: }
                   10345: 
                   10346: sub modal_adhoc_window {
1.1365    raeburn  10347:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10348:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10349:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10350: }
                   10351: 
                   10352: sub modal_adhoc_launch {
                   10353:     my ($funcname,$width,$height,$content)=@_;
                   10354:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10355: <script type="text/javascript">
                   10356: // <![CDATA[
                   10357: $funcname();
                   10358: // ]]>
                   10359: </script>
                   10360: ENDLAUNCH
                   10361: }
                   10362: 
                   10363: sub modal_adhoc_close {
                   10364:     return (<<ENDCLOSE);
                   10365: <script type="text/javascript">
                   10366: // <![CDATA[
                   10367: modalWindow.close();
                   10368: // ]]>
                   10369: </script>
                   10370: ENDCLOSE
                   10371: }
                   10372: 
1.1038    www      10373: sub togglebox_script {
                   10374:    return(<<ENDTOGGLE);
                   10375: <script type="text/javascript"> 
                   10376: // <![CDATA[
                   10377: function LCtoggleDisplay(id,hidetext,showtext) {
                   10378:    link = document.getElementById(id + "link").childNodes[0];
                   10379:    with (document.getElementById(id).style) {
                   10380:       if (display == "none" ) {
                   10381:           display = "inline";
                   10382:           link.nodeValue = hidetext;
                   10383:         } else {
                   10384:           display = "none";
                   10385:           link.nodeValue = showtext;
                   10386:        }
                   10387:    }
                   10388: }
                   10389: // ]]>
                   10390: </script>
                   10391: ENDTOGGLE
                   10392: }
                   10393: 
1.1039    www      10394: sub start_togglebox {
                   10395:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10396:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10397:     unless ($showtext) { $showtext=&mt('show'); }
                   10398:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10399:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10400:     return &start_data_table().
                   10401:            &start_data_table_header_row().
                   10402:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10403:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10404:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10405:            &end_data_table_header_row().
                   10406:            '<tr id="'.$id.'" style="display:none""><td>';
                   10407: }
                   10408: 
                   10409: sub end_togglebox {
                   10410:     return '</td></tr>'.&end_data_table();
                   10411: }
                   10412: 
1.1041    www      10413: sub LCprogressbar_script {
1.1302    raeburn  10414:    my ($id,$number_to_do)=@_;
                   10415:    if ($number_to_do) {
                   10416:        return(<<ENDPROGRESS);
1.1041    www      10417: <script type="text/javascript">
                   10418: // <![CDATA[
1.1045    www      10419: \$('#progressbar$id').progressbar({
1.1041    www      10420:   value: 0,
                   10421:   change: function(event, ui) {
                   10422:     var newVal = \$(this).progressbar('option', 'value');
                   10423:     \$('.pblabel', this).text(LCprogressTxt);
                   10424:   }
                   10425: });
                   10426: // ]]>
                   10427: </script>
                   10428: ENDPROGRESS
1.1302    raeburn  10429:    } else {
                   10430:        return(<<ENDPROGRESS);
                   10431: <script type="text/javascript">
                   10432: // <![CDATA[
                   10433: \$('#progressbar$id').progressbar({
                   10434:   value: false,
                   10435:   create: function(event, ui) {
                   10436:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10437:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10438:   }
                   10439: });
                   10440: // ]]>
                   10441: </script>
                   10442: ENDPROGRESS
                   10443:    }
1.1041    www      10444: }
                   10445: 
                   10446: sub LCprogressbarUpdate_script {
                   10447:    return(<<ENDPROGRESSUPDATE);
                   10448: <style type="text/css">
                   10449: .ui-progressbar { position:relative; }
1.1302    raeburn  10450: .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      10451: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10452: </style>
                   10453: <script type="text/javascript">
                   10454: // <![CDATA[
1.1045    www      10455: var LCprogressTxt='---';
                   10456: 
1.1302    raeburn  10457: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10458:    LCprogressTxt=progresstext;
1.1302    raeburn  10459:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10460:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10461:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10462:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10463:    } else {
                   10464:        \$('#progressbar'+id).progressbar('value',percent);
                   10465:    }
1.1041    www      10466: }
                   10467: // ]]>
                   10468: </script>
                   10469: ENDPROGRESSUPDATE
                   10470: }
                   10471: 
1.1042    www      10472: my $LClastpercent;
1.1045    www      10473: my $LCidcnt;
                   10474: my $LCcurrentid;
1.1042    www      10475: 
1.1041    www      10476: sub LCprogressbar {
1.1302    raeburn  10477:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10478:     $LClastpercent=0;
1.1045    www      10479:     $LCidcnt++;
                   10480:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10481:     my ($starting,$content);
                   10482:     if ($number_to_do) {
                   10483:         $starting=&mt('Starting');
                   10484:         $content=(<<ENDPROGBAR);
                   10485: $preamble
1.1045    www      10486:   <div id="progressbar$LCcurrentid">
1.1041    www      10487:     <span class="pblabel">$starting</span>
                   10488:   </div>
                   10489: ENDPROGBAR
1.1302    raeburn  10490:     } else {
                   10491:         $starting=&mt('Loading...');
                   10492:         $LClastpercent='false';
                   10493:         $content=(<<ENDPROGBAR);
                   10494: $preamble
                   10495:   <div id="progressbar$LCcurrentid">
                   10496:       <div class="progress-label">$starting</div>
                   10497:   </div>
                   10498: ENDPROGBAR
                   10499:     }
                   10500:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10501: }
                   10502: 
                   10503: sub LCprogressbarUpdate {
1.1302    raeburn  10504:     my ($r,$val,$text,$number_to_do)=@_;
                   10505:     if ($number_to_do) {
                   10506:         unless ($val) { 
                   10507:             if ($LClastpercent) {
                   10508:                 $val=$LClastpercent;
                   10509:             } else {
                   10510:                 $val=0;
                   10511:             }
                   10512:         }
                   10513:         if ($val<0) { $val=0; }
                   10514:         if ($val>100) { $val=0; }
                   10515:         $LClastpercent=$val;
                   10516:         unless ($text) { $text=$val.'%'; }
                   10517:     } else {
                   10518:         $val = 'false';
1.1042    www      10519:     }
1.1041    www      10520:     $text=&js_ready($text);
1.1044    www      10521:     &r_print($r,<<ENDUPDATE);
1.1041    www      10522: <script type="text/javascript">
                   10523: // <![CDATA[
1.1302    raeburn  10524: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10525: // ]]>
                   10526: </script>
                   10527: ENDUPDATE
1.1035    www      10528: }
                   10529: 
1.1042    www      10530: sub LCprogressbarClose {
                   10531:     my ($r)=@_;
                   10532:     $LClastpercent=0;
1.1044    www      10533:     &r_print($r,<<ENDCLOSE);
1.1042    www      10534: <script type="text/javascript">
                   10535: // <![CDATA[
1.1045    www      10536: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10537: // ]]>
                   10538: </script>
                   10539: ENDCLOSE
1.1044    www      10540: }
                   10541: 
                   10542: sub r_print {
                   10543:     my ($r,$to_print)=@_;
                   10544:     if ($r) {
                   10545:       $r->print($to_print);
                   10546:       $r->rflush();
                   10547:     } else {
                   10548:       print($to_print);
                   10549:     }
1.1042    www      10550: }
                   10551: 
1.320     albertel 10552: sub html_encode {
                   10553:     my ($result) = @_;
                   10554: 
1.322     albertel 10555:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10556:     
                   10557:     return $result;
                   10558: }
1.1044    www      10559: 
1.317     albertel 10560: sub js_ready {
                   10561:     my ($result) = @_;
                   10562: 
1.323     albertel 10563:     $result =~ s/[\n\r]/ /xmsg;
                   10564:     $result =~ s/\\/\\\\/xmsg;
                   10565:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10566:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10567:     
                   10568:     return $result;
                   10569: }
                   10570: 
1.315     albertel 10571: sub validate_page {
                   10572:     if (  exists($env{'internal.start_page'})
1.316     albertel 10573: 	  &&     $env{'internal.start_page'} > 1) {
                   10574: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10575: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10576: 				 $ENV{'request.filename'});
1.315     albertel 10577:     }
                   10578:     if (  exists($env{'internal.end_page'})
1.316     albertel 10579: 	  &&     $env{'internal.end_page'} > 1) {
                   10580: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10581: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10582: 				 $env{'request.filename'});
1.315     albertel 10583:     }
                   10584:     if (     exists($env{'internal.start_page'})
                   10585: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10586: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10587: 				 $env{'request.filename'});
1.315     albertel 10588:     }
                   10589:     if (   ! exists($env{'internal.start_page'})
                   10590: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10591: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10592: 				 $env{'request.filename'});
1.315     albertel 10593:     }
1.306     albertel 10594: }
1.315     albertel 10595: 
1.996     www      10596: 
                   10597: sub start_scrollbox {
1.1140    raeburn  10598:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10599:     unless ($outerwidth) { $outerwidth='520px'; }
                   10600:     unless ($width) { $width='500px'; }
                   10601:     unless ($height) { $height='200px'; }
1.1075    raeburn  10602:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10603:     if ($id ne '') {
1.1140    raeburn  10604:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10605:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10606:     }
1.1075    raeburn  10607:     if ($bgcolor ne '') {
                   10608:         $tdcol = "background-color: $bgcolor;";
                   10609:     }
1.1137    raeburn  10610:     my $nicescroll_js;
                   10611:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10612:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10613:     }
                   10614:     return <<"END";
                   10615: $nicescroll_js
                   10616: 
                   10617: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10618: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10619: END
                   10620: }
                   10621: 
                   10622: sub end_scrollbox {
                   10623:     return '</div></td></tr></table>';
                   10624: }
                   10625: 
                   10626: sub nicescroll_javascript {
                   10627:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10628:     my %options;
                   10629:     if (ref($cursor) eq 'HASH') {
                   10630:         %options = %{$cursor};
                   10631:     }
                   10632:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10633:         $options{'railalign'} = 'left';
                   10634:     }
                   10635:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10636:         my $function  = &get_users_function();
                   10637:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10638:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10639:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10640:         }
1.1140    raeburn  10641:     }
                   10642:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10643:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10644:             $options{'cursoropacity'}='1.0';
                   10645:         }
1.1140    raeburn  10646:     } else {
                   10647:         $options{'cursoropacity'}='1.0';
                   10648:     }
                   10649:     if ($options{'cursorfixedheight'} eq 'none') {
                   10650:         delete($options{'cursorfixedheight'});
                   10651:     } else {
                   10652:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10653:     }
                   10654:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10655:         delete($options{'railoffset'});
                   10656:     }
                   10657:     my @niceoptions;
                   10658:     while (my($key,$value) = each(%options)) {
                   10659:         if ($value =~ /^\{.+\}$/) {
                   10660:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10661:         } else {
1.1140    raeburn  10662:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10663:         }
1.1140    raeburn  10664:     }
                   10665:     my $nicescroll_js = '
1.1137    raeburn  10666: $(document).ready(
1.1140    raeburn  10667:       function() {
                   10668:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10669:       }
1.1137    raeburn  10670: );
                   10671: ';
1.1140    raeburn  10672:     if ($framecheck) {
                   10673:         $nicescroll_js .= '
                   10674: function expand_div(caller) {
                   10675:     if (top === self) {
                   10676:         document.getElementById("'.$id.'").style.width = "auto";
                   10677:         document.getElementById("'.$id.'").style.height = "auto";
                   10678:     } else {
                   10679:         try {
                   10680:             if (parent.frames) {
                   10681:                 if (parent.frames.length > 1) {
                   10682:                     var framesrc = parent.frames[1].location.href;
                   10683:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10684:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10685:                         document.getElementById("'.$id.'").style.width = "auto";
                   10686:                         document.getElementById("'.$id.'").style.height = "auto";
                   10687:                     }
                   10688:                 }
                   10689:             }
                   10690:         } catch (e) {
                   10691:             return;
                   10692:         }
1.1137    raeburn  10693:     }
1.1140    raeburn  10694:     return;
1.996     www      10695: }
1.1140    raeburn  10696: ';
                   10697:     }
                   10698:     if ($needjsready) {
                   10699:         $nicescroll_js = '
                   10700: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10701:     } else {
                   10702:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10703:     }
                   10704:     return $nicescroll_js;
1.996     www      10705: }
                   10706: 
1.318     albertel 10707: sub simple_error_page {
1.1150    bisitz   10708:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10709:     my %displayargs;
1.1151    raeburn  10710:     if (ref($args) eq 'HASH') {
                   10711:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10712:         if ($args->{'only_body'}) {
                   10713:             $displayargs{'only_body'} = 1;
                   10714:         }
                   10715:         if ($args->{'no_nav_bar'}) {
                   10716:             $displayargs{'no_nav_bar'} = 1;
                   10717:         }
1.1151    raeburn  10718:     } else {
                   10719:         $msg = &mt($msg);
                   10720:     }
1.1150    bisitz   10721: 
1.318     albertel 10722:     my $page =
1.1304    raeburn  10723: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10724: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10725: 	&Apache::loncommon::end_page();
                   10726:     if (ref($r)) {
                   10727: 	$r->print($page);
1.327     albertel 10728: 	return;
1.318     albertel 10729:     }
                   10730:     return $page;
                   10731: }
1.347     albertel 10732: 
                   10733: {
1.610     albertel 10734:     my @row_count;
1.961     onken    10735: 
                   10736:     sub start_data_table_count {
                   10737:         unshift(@row_count, 0);
                   10738:         return;
                   10739:     }
                   10740: 
                   10741:     sub end_data_table_count {
                   10742:         shift(@row_count);
                   10743:         return;
                   10744:     }
                   10745: 
1.347     albertel 10746:     sub start_data_table {
1.1018    raeburn  10747: 	my ($add_class,$id) = @_;
1.422     albertel 10748: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10749:         my $table_id;
                   10750:         if (defined($id)) {
                   10751:             $table_id = ' id="'.$id.'"';
                   10752:         }
1.961     onken    10753: 	&start_data_table_count();
1.1018    raeburn  10754: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10755:     }
                   10756: 
                   10757:     sub end_data_table {
1.961     onken    10758: 	&end_data_table_count();
1.389     albertel 10759: 	return '</table>'."\n";;
1.347     albertel 10760:     }
                   10761: 
                   10762:     sub start_data_table_row {
1.974     wenzelju 10763: 	my ($add_class, $id) = @_;
1.610     albertel 10764: 	$row_count[0]++;
                   10765: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10766: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10767:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10768:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10769:     }
1.471     banghart 10770:     
                   10771:     sub continue_data_table_row {
1.974     wenzelju 10772: 	my ($add_class, $id) = @_;
1.610     albertel 10773: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10774: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10775:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10776:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10777:     }
1.347     albertel 10778: 
                   10779:     sub end_data_table_row {
1.389     albertel 10780: 	return '</tr>'."\n";;
1.347     albertel 10781:     }
1.367     www      10782: 
1.421     albertel 10783:     sub start_data_table_empty_row {
1.707     bisitz   10784: #	$row_count[0]++;
1.421     albertel 10785: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10786:     }
                   10787: 
                   10788:     sub end_data_table_empty_row {
                   10789: 	return '</tr>'."\n";;
                   10790:     }
                   10791: 
1.367     www      10792:     sub start_data_table_header_row {
1.389     albertel 10793: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10794:     }
                   10795: 
                   10796:     sub end_data_table_header_row {
1.389     albertel 10797: 	return '</tr>'."\n";;
1.367     www      10798:     }
1.890     droeschl 10799: 
                   10800:     sub data_table_caption {
                   10801:         my $caption = shift;
                   10802:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10803:     }
1.347     albertel 10804: }
                   10805: 
1.548     albertel 10806: =pod
                   10807: 
                   10808: =item * &inhibit_menu_check($arg)
                   10809: 
                   10810: Checks for a inhibitmenu state and generates output to preserve it
                   10811: 
                   10812: Inputs:         $arg - can be any of
                   10813:                      - undef - in which case the return value is a string 
                   10814:                                to add  into arguments list of a uri
                   10815:                      - 'input' - in which case the return value is a HTML
                   10816:                                  <form> <input> field of type hidden to
                   10817:                                  preserve the value
                   10818:                      - a url - in which case the return value is the url with
                   10819:                                the neccesary cgi args added to preserve the
                   10820:                                inhibitmenu state
                   10821:                      - a ref to a url - no return value, but the string is
                   10822:                                         updated to include the neccessary cgi
                   10823:                                         args to preserve the inhibitmenu state
                   10824: 
                   10825: =cut
                   10826: 
                   10827: sub inhibit_menu_check {
                   10828:     my ($arg) = @_;
                   10829:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10830:     if ($arg eq 'input') {
                   10831: 	if ($env{'form.inhibitmenu'}) {
                   10832: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10833: 	} else {
                   10834: 	    return
                   10835: 	}
                   10836:     }
                   10837:     if ($env{'form.inhibitmenu'}) {
                   10838: 	if (ref($arg)) {
                   10839: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10840: 	} elsif ($arg eq '') {
                   10841: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10842: 	} else {
                   10843: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10844: 	}
                   10845:     }
                   10846:     if (!ref($arg)) {
                   10847: 	return $arg;
                   10848:     }
                   10849: }
                   10850: 
1.251     albertel 10851: ###############################################
1.182     matthew  10852: 
                   10853: =pod
                   10854: 
1.549     albertel 10855: =back
                   10856: 
                   10857: =head1 User Information Routines
                   10858: 
                   10859: =over 4
                   10860: 
1.405     albertel 10861: =item * &get_users_function()
1.182     matthew  10862: 
                   10863: Used by &bodytag to determine the current users primary role.
                   10864: Returns either 'student','coordinator','admin', or 'author'.
                   10865: 
                   10866: =cut
                   10867: 
                   10868: ###############################################
                   10869: sub get_users_function {
1.815     tempelho 10870:     my $function = 'norole';
1.818     tempelho 10871:     if ($env{'request.role'}=~/^(st)/) {
                   10872:         $function='student';
                   10873:     }
1.907     raeburn  10874:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10875:         $function='coordinator';
                   10876:     }
1.258     albertel 10877:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10878:         $function='admin';
                   10879:     }
1.826     bisitz   10880:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10881:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10882:         $function='author';
                   10883:     }
                   10884:     return $function;
1.54      www      10885: }
1.99      www      10886: 
                   10887: ###############################################
                   10888: 
1.233     raeburn  10889: =pod
                   10890: 
1.821     raeburn  10891: =item * &show_course()
                   10892: 
                   10893: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10894: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10895: 
                   10896: Inputs:
                   10897: None
                   10898: 
                   10899: Outputs:
                   10900: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10901: 
                   10902: =cut
                   10903: 
                   10904: ###############################################
                   10905: sub show_course {
1.1408    raeburn  10906:     my ($udom,$uname) = @_;
                   10907:     if (($udom ne '') && ($uname ne '')) {
                   10908:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10909:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10910:                 return 0;
                   10911:             } else {
                   10912:                 return 1;
                   10913:             }
                   10914:         }
                   10915:     }
1.821     raeburn  10916:     my $course = !$env{'user.adv'};
                   10917:     if (!$env{'user.adv'}) {
                   10918:         foreach my $env (keys(%env)) {
                   10919:             next if ($env !~ m/^user\.priv\./);
                   10920:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10921:                 $course = 0;
                   10922:                 last;
                   10923:             }
                   10924:         }
                   10925:     }
                   10926:     return $course;
                   10927: }
                   10928: 
                   10929: ###############################################
                   10930: 
                   10931: =pod
                   10932: 
1.542     raeburn  10933: =item * &check_user_status()
1.274     raeburn  10934: 
                   10935: Determines current status of supplied role for a
                   10936: specific user. Roles can be active, previous or future.
                   10937: 
                   10938: Inputs: 
                   10939: user's domain, user's username, course's domain,
1.375     raeburn  10940: course's number, optional section ID.
1.274     raeburn  10941: 
                   10942: Outputs:
                   10943: role status: active, previous or future. 
                   10944: 
                   10945: =cut
                   10946: 
                   10947: sub check_user_status {
1.412     raeburn  10948:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10949:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10950:     my @uroles = keys(%userinfo);
1.274     raeburn  10951:     my $srchstr;
                   10952:     my $active_chk = 'none';
1.412     raeburn  10953:     my $now = time;
1.274     raeburn  10954:     if (@uroles > 0) {
1.908     raeburn  10955:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10956:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10957:         } else {
1.412     raeburn  10958:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10959:         }
                   10960:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10961:             my $role_end = 0;
                   10962:             my $role_start = 0;
                   10963:             $active_chk = 'active';
1.412     raeburn  10964:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10965:                 $role_end = $1;
                   10966:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10967:                     $role_start = $1;
1.274     raeburn  10968:                 }
                   10969:             }
                   10970:             if ($role_start > 0) {
1.412     raeburn  10971:                 if ($now < $role_start) {
1.274     raeburn  10972:                     $active_chk = 'future';
                   10973:                 }
                   10974:             }
                   10975:             if ($role_end > 0) {
1.412     raeburn  10976:                 if ($now > $role_end) {
1.274     raeburn  10977:                     $active_chk = 'previous';
                   10978:                 }
                   10979:             }
                   10980:         }
                   10981:     }
                   10982:     return $active_chk;
                   10983: }
                   10984: 
                   10985: ###############################################
                   10986: 
                   10987: =pod
                   10988: 
1.405     albertel 10989: =item * &get_sections()
1.233     raeburn  10990: 
                   10991: Determines all the sections for a course including
                   10992: sections with students and sections containing other roles.
1.419     raeburn  10993: Incoming parameters: 
                   10994: 
                   10995: 1. domain
                   10996: 2. course number 
                   10997: 3. reference to array containing roles for which sections should 
                   10998: be gathered (optional).
                   10999: 4. reference to array containing status types for which sections 
                   11000: should be gathered (optional).
                   11001: 
                   11002: If the third argument is undefined, sections are gathered for any role. 
                   11003: If the fourth argument is undefined, sections are gathered for any status.
                   11004: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  11005:  
1.374     raeburn  11006: Returns section hash (keys are section IDs, values are
                   11007: number of users in each section), subject to the
1.419     raeburn  11008: optional roles filter, optional status filter 
1.233     raeburn  11009: 
                   11010: =cut
                   11011: 
                   11012: ###############################################
                   11013: sub get_sections {
1.419     raeburn  11014:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 11015:     if (!defined($cdom) || !defined($cnum)) {
                   11016:         my $cid =  $env{'request.course.id'};
                   11017: 
                   11018: 	return if (!defined($cid));
                   11019: 
                   11020:         $cdom = $env{'course.'.$cid.'.domain'};
                   11021:         $cnum = $env{'course.'.$cid.'.num'};
                   11022:     }
                   11023: 
                   11024:     my %sectioncount;
1.419     raeburn  11025:     my $now = time;
1.240     albertel 11026: 
1.1118    raeburn  11027:     my $check_students = 1;
                   11028:     my $only_students = 0;
                   11029:     if (ref($possible_roles) eq 'ARRAY') {
                   11030:         if (grep(/^st$/,@{$possible_roles})) {
                   11031:             if (@{$possible_roles} == 1) {
                   11032:                 $only_students = 1;
                   11033:             }
                   11034:         } else {
                   11035:             $check_students = 0;
                   11036:         }
                   11037:     }
                   11038: 
                   11039:     if ($check_students) { 
1.276     albertel 11040: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 11041: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   11042: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  11043:         my $start_index = &Apache::loncoursedata::CL_START();
                   11044:         my $end_index = &Apache::loncoursedata::CL_END();
                   11045:         my $status;
1.366     albertel 11046: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  11047: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   11048: 				                     $data->[$status_index],
                   11049:                                                      $data->[$start_index],
                   11050:                                                      $data->[$end_index]);
                   11051:             if ($stu_status eq 'Active') {
                   11052:                 $status = 'active';
                   11053:             } elsif ($end < $now) {
                   11054:                 $status = 'previous';
                   11055:             } elsif ($start > $now) {
                   11056:                 $status = 'future';
                   11057:             } 
                   11058: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   11059:                 if ((!defined($possible_status)) || (($status ne '') && 
                   11060:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   11061: 		    $sectioncount{$section}++;
                   11062:                 }
1.240     albertel 11063: 	    }
                   11064: 	}
                   11065:     }
1.1118    raeburn  11066:     if ($only_students) {
                   11067:         return %sectioncount;
                   11068:     }
1.240     albertel 11069:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11070:     foreach my $user (sort(keys(%courseroles))) {
                   11071: 	if ($user !~ /^(\w{2})/) { next; }
                   11072: 	my ($role) = ($user =~ /^(\w{2})/);
                   11073: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  11074: 	my ($section,$status);
1.240     albertel 11075: 	if ($role eq 'cr' &&
                   11076: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   11077: 	    $section=$1;
                   11078: 	}
                   11079: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   11080: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  11081:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   11082:         if ($end == -1 && $start == -1) {
                   11083:             next; #deleted role
                   11084:         }
                   11085:         if (!defined($possible_status)) { 
                   11086:             $sectioncount{$section}++;
                   11087:         } else {
                   11088:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   11089:                 $status = 'active';
                   11090:             } elsif ($end < $now) {
                   11091:                 $status = 'future';
                   11092:             } elsif ($start > $now) {
                   11093:                 $status = 'previous';
                   11094:             }
                   11095:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   11096:                 $sectioncount{$section}++;
                   11097:             }
                   11098:         }
1.233     raeburn  11099:     }
1.366     albertel 11100:     return %sectioncount;
1.233     raeburn  11101: }
                   11102: 
1.274     raeburn  11103: ###############################################
1.294     raeburn  11104: 
                   11105: =pod
1.405     albertel 11106: 
                   11107: =item * &get_course_users()
                   11108: 
1.275     raeburn  11109: Retrieves usernames:domains for users in the specified course
                   11110: with specific role(s), and access status. 
                   11111: 
                   11112: Incoming parameters:
1.277     albertel 11113: 1. course domain
                   11114: 2. course number
                   11115: 3. access status: users must have - either active, 
1.275     raeburn  11116: previous, future, or all.
1.277     albertel 11117: 4. reference to array of permissible roles
1.288     raeburn  11118: 5. reference to array of section restrictions (optional)
                   11119: 6. reference to results object (hash of hashes).
                   11120: 7. reference to optional userdata hash
1.609     raeburn  11121: 8. reference to optional statushash
1.630     raeburn  11122: 9. flag if privileged users (except those set to unhide in
                   11123:    course settings) should be excluded    
1.609     raeburn  11124: Keys of top level results hash are roles.
1.275     raeburn  11125: Keys of inner hashes are username:domain, with 
                   11126: values set to access type.
1.288     raeburn  11127: Optional userdata hash returns an array with arguments in the 
                   11128: same order as loncoursedata::get_classlist() for student data.
                   11129: 
1.609     raeburn  11130: Optional statushash returns
                   11131: 
1.288     raeburn  11132: Entries for end, start, section and status are blank because
                   11133: of the possibility of multiple values for non-student roles.
                   11134: 
1.275     raeburn  11135: =cut
1.405     albertel 11136: 
1.275     raeburn  11137: ###############################################
1.405     albertel 11138: 
1.275     raeburn  11139: sub get_course_users {
1.630     raeburn  11140:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  11141:     my %idx = ();
1.419     raeburn  11142:     my %seclists;
1.288     raeburn  11143: 
                   11144:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   11145:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   11146:     $idx{end} = &Apache::loncoursedata::CL_END();
                   11147:     $idx{start} = &Apache::loncoursedata::CL_START();
                   11148:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   11149:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   11150:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   11151:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   11152: 
1.290     albertel 11153:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 11154:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  11155:         my $now = time;
1.277     albertel 11156:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  11157:             my $match = 0;
1.412     raeburn  11158:             my $secmatch = 0;
1.419     raeburn  11159:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  11160:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  11161:             if ($section eq '') {
                   11162:                 $section = 'none';
                   11163:             }
1.291     albertel 11164:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11165:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11166:                     $secmatch = 1;
                   11167:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11168:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11169:                         $secmatch = 1;
                   11170:                     }
                   11171:                 } else {  
1.419     raeburn  11172: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11173: 		        $secmatch = 1;
                   11174:                     }
1.290     albertel 11175: 		}
1.412     raeburn  11176:                 if (!$secmatch) {
                   11177:                     next;
                   11178:                 }
1.419     raeburn  11179:             }
1.275     raeburn  11180:             if (defined($$types{'active'})) {
1.288     raeburn  11181:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11182:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11183:                     $match = 1;
1.275     raeburn  11184:                 }
                   11185:             }
                   11186:             if (defined($$types{'previous'})) {
1.609     raeburn  11187:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11188:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11189:                     $match = 1;
1.275     raeburn  11190:                 }
                   11191:             }
                   11192:             if (defined($$types{'future'})) {
1.609     raeburn  11193:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11194:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11195:                     $match = 1;
1.275     raeburn  11196:                 }
                   11197:             }
1.609     raeburn  11198:             if ($match) {
                   11199:                 push(@{$seclists{$student}},$section);
                   11200:                 if (ref($userdata) eq 'HASH') {
                   11201:                     $$userdata{$student} = $$classlist{$student};
                   11202:                 }
                   11203:                 if (ref($statushash) eq 'HASH') {
                   11204:                     $statushash->{$student}{'st'}{$section} = $status;
                   11205:                 }
1.288     raeburn  11206:             }
1.275     raeburn  11207:         }
                   11208:     }
1.412     raeburn  11209:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11210:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11211:         my $now = time;
1.609     raeburn  11212:         my %displaystatus = ( previous => 'Expired',
                   11213:                               active   => 'Active',
                   11214:                               future   => 'Future',
                   11215:                             );
1.1121    raeburn  11216:         my (%nothide,@possdoms);
1.630     raeburn  11217:         if ($hidepriv) {
                   11218:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11219:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11220:                 if ($user !~ /:/) {
                   11221:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11222:                 } else {
                   11223:                     $nothide{$user} = 1;
                   11224:                 }
                   11225:             }
1.1121    raeburn  11226:             my @possdoms = ($cdom);
                   11227:             if ($coursehash{'checkforpriv'}) {
                   11228:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11229:             }
1.630     raeburn  11230:         }
1.439     raeburn  11231:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11232:             my $match = 0;
1.412     raeburn  11233:             my $secmatch = 0;
1.439     raeburn  11234:             my $status;
1.412     raeburn  11235:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11236:             $user =~ s/:$//;
1.439     raeburn  11237:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11238:             if ($end == -1 || $start == -1) {
                   11239:                 next;
                   11240:             }
                   11241:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11242:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11243:                 my ($uname,$udom) = split(/:/,$user);
                   11244:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11245:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11246:                         $secmatch = 1;
                   11247:                     } elsif ($usec eq '') {
1.420     albertel 11248:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11249:                             $secmatch = 1;
                   11250:                         }
                   11251:                     } else {
                   11252:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11253:                             $secmatch = 1;
                   11254:                         }
                   11255:                     }
                   11256:                     if (!$secmatch) {
                   11257:                         next;
                   11258:                     }
1.288     raeburn  11259:                 }
1.419     raeburn  11260:                 if ($usec eq '') {
                   11261:                     $usec = 'none';
                   11262:                 }
1.275     raeburn  11263:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11264:                     if ($hidepriv) {
1.1121    raeburn  11265:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11266:                             (!$nothide{$uname.':'.$udom})) {
                   11267:                             next;
                   11268:                         }
                   11269:                     }
1.503     raeburn  11270:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11271:                         $status = 'previous';
                   11272:                     } elsif ($start > $now) {
                   11273:                         $status = 'future';
                   11274:                     } else {
                   11275:                         $status = 'active';
                   11276:                     }
1.277     albertel 11277:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11278:                         if ($status eq $type) {
1.420     albertel 11279:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11280:                                 push(@{$$users{$role}{$user}},$type);
                   11281:                             }
1.288     raeburn  11282:                             $match = 1;
                   11283:                         }
                   11284:                     }
1.419     raeburn  11285:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11286:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11287: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11288:                         }
1.420     albertel 11289:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11290:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11291:                         }
1.609     raeburn  11292:                         if (ref($statushash) eq 'HASH') {
                   11293:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11294:                         }
1.275     raeburn  11295:                     }
                   11296:                 }
                   11297:             }
                   11298:         }
1.290     albertel 11299:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11300:             if ((defined($cdom)) && (defined($cnum))) {
                   11301:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11302:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11303:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11304:                     next if ($owner eq '');
                   11305:                     my ($ownername,$ownerdom);
                   11306:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11307:                         $ownername = $1;
                   11308:                         $ownerdom = $2;
                   11309:                     } else {
                   11310:                         $ownername = $owner;
                   11311:                         $ownerdom = $cdom;
                   11312:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11313:                     }
                   11314:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11315:                     if (defined($userdata) && 
1.609     raeburn  11316: 			!exists($$userdata{$owner})) {
                   11317: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11318:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11319:                             push(@{$seclists{$owner}},'none');
                   11320:                         }
                   11321:                         if (ref($statushash) eq 'HASH') {
                   11322:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11323:                         }
1.290     albertel 11324: 		    }
1.279     raeburn  11325:                 }
                   11326:             }
                   11327:         }
1.419     raeburn  11328:         foreach my $user (keys(%seclists)) {
                   11329:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11330:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11331:         }
1.275     raeburn  11332:     }
                   11333:     return;
                   11334: }
                   11335: 
1.288     raeburn  11336: sub get_user_info {
                   11337:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11338:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11339: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11340:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11341:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11342:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11343:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11344:     return;
                   11345: }
1.275     raeburn  11346: 
1.472     raeburn  11347: ###############################################
                   11348: 
                   11349: =pod
                   11350: 
                   11351: =item * &get_user_quota()
                   11352: 
1.1134    raeburn  11353: Retrieves quota assigned for storage of user files.
                   11354: Default is to report quota for portfolio files.
1.472     raeburn  11355: 
                   11356: Incoming parameters:
                   11357: 1. user's username
                   11358: 2. user's domain
1.1134    raeburn  11359: 3. quota name - portfolio, author, or course
1.1136    raeburn  11360:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11361: 4. crstype - official, unofficial, textbook, placement or community, 
                   11362:    if quota name is course
1.472     raeburn  11363: 
                   11364: Returns:
1.1163    raeburn  11365: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11366: 2. (Optional) Type of setting: custom or default
                   11367:    (individually assigned or default for user's 
                   11368:    institutional status).
                   11369: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11370:    or student - types as defined in localenroll::inst_usertypes 
                   11371:    for user's domain, which determines default quota for user.
                   11372: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11373: 
                   11374: If a value has been stored in the user's environment, 
1.536     raeburn  11375: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11376: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11377: 
                   11378: =cut
                   11379: 
                   11380: ###############################################
                   11381: 
                   11382: 
                   11383: sub get_user_quota {
1.1136    raeburn  11384:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11385:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11386:     if (!defined($udom)) {
                   11387:         $udom = $env{'user.domain'};
                   11388:     }
                   11389:     if (!defined($uname)) {
                   11390:         $uname = $env{'user.name'};
                   11391:     }
                   11392:     if (($udom eq '' || $uname eq '') ||
                   11393:         ($udom eq 'public') && ($uname eq 'public')) {
                   11394:         $quota = 0;
1.536     raeburn  11395:         $quotatype = 'default';
                   11396:         $defquota = 0; 
1.472     raeburn  11397:     } else {
1.536     raeburn  11398:         my $inststatus;
1.1134    raeburn  11399:         if ($quotaname eq 'course') {
                   11400:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11401:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11402:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11403:             } else {
                   11404:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11405:                 $quota = $cenv{'internal.uploadquota'};
                   11406:             }
1.536     raeburn  11407:         } else {
1.1134    raeburn  11408:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11409:                 if ($quotaname eq 'author') {
                   11410:                     $quota = $env{'environment.authorquota'};
                   11411:                 } else {
                   11412:                     $quota = $env{'environment.portfolioquota'};
                   11413:                 }
                   11414:                 $inststatus = $env{'environment.inststatus'};
                   11415:             } else {
                   11416:                 my %userenv = 
                   11417:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11418:                                          'authorquota','inststatus'],$udom,$uname);
                   11419:                 my ($tmp) = keys(%userenv);
                   11420:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11421:                     if ($quotaname eq 'author') {
                   11422:                         $quota = $userenv{'authorquota'};
                   11423:                     } else {
                   11424:                         $quota = $userenv{'portfolioquota'};
                   11425:                     }
                   11426:                     $inststatus = $userenv{'inststatus'};
                   11427:                 } else {
                   11428:                     undef(%userenv);
                   11429:                 }
                   11430:             }
                   11431:         }
                   11432:         if ($quota eq '' || wantarray) {
                   11433:             if ($quotaname eq 'course') {
                   11434:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11435:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11436:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11437:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11438:                     $defquota = $domdefs{$crstype.'quota'};
                   11439:                 }
                   11440:                 if ($defquota eq '') {
                   11441:                     $defquota = 500;
                   11442:                 }
1.1134    raeburn  11443:             } else {
                   11444:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11445:             }
                   11446:             if ($quota eq '') {
                   11447:                 $quota = $defquota;
                   11448:                 $quotatype = 'default';
                   11449:             } else {
                   11450:                 $quotatype = 'custom';
                   11451:             }
1.472     raeburn  11452:         }
                   11453:     }
1.536     raeburn  11454:     if (wantarray) {
                   11455:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11456:     } else {
                   11457:         return $quota;
                   11458:     }
1.472     raeburn  11459: }
                   11460: 
                   11461: ###############################################
                   11462: 
                   11463: =pod
                   11464: 
                   11465: =item * &default_quota()
                   11466: 
1.536     raeburn  11467: Retrieves default quota assigned for storage of user portfolio files,
                   11468: given an (optional) user's institutional status.
1.472     raeburn  11469: 
                   11470: Incoming parameters:
1.1142    raeburn  11471: 
1.472     raeburn  11472: 1. domain
1.536     raeburn  11473: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11474:    status types (e.g., faculty, staff, student etc.)
                   11475:    which apply to the user for whom the default is being retrieved.
                   11476:    If the institutional status string in undefined, the domain
1.1134    raeburn  11477:    default quota will be returned.
                   11478: 3.  quota name - portfolio, author, or course
                   11479:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11480: 
                   11481: Returns:
1.1142    raeburn  11482: 
1.1163    raeburn  11483: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11484: 2. (Optional) institutional type which determined the value of the
                   11485:    default quota.
1.472     raeburn  11486: 
                   11487: If a value has been stored in the domain's configuration db,
                   11488: it will return that, otherwise it returns 20 (for backwards 
                   11489: compatibility with domains which have not set up a configuration
1.1163    raeburn  11490: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11491: 
1.536     raeburn  11492: If the user's status includes multiple types (e.g., staff and student),
                   11493: the largest default quota which applies to the user determines the
                   11494: default quota returned.
                   11495: 
1.472     raeburn  11496: =cut
                   11497: 
                   11498: ###############################################
                   11499: 
                   11500: 
                   11501: sub default_quota {
1.1134    raeburn  11502:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11503:     my ($defquota,$settingstatus);
                   11504:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11505:                                             ['quotas'],$udom);
1.1134    raeburn  11506:     my $key = 'defaultquota';
                   11507:     if ($quotaname eq 'author') {
                   11508:         $key = 'authorquota';
                   11509:     }
1.622     raeburn  11510:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11511:         if ($inststatus ne '') {
1.765     raeburn  11512:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11513:             foreach my $item (@statuses) {
1.1134    raeburn  11514:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11515:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11516:                         if ($defquota eq '') {
1.1134    raeburn  11517:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11518:                             $settingstatus = $item;
1.1134    raeburn  11519:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11520:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11521:                             $settingstatus = $item;
                   11522:                         }
                   11523:                     }
1.1134    raeburn  11524:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11525:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11526:                         if ($defquota eq '') {
                   11527:                             $defquota = $quotahash{'quotas'}{$item};
                   11528:                             $settingstatus = $item;
                   11529:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11530:                             $defquota = $quotahash{'quotas'}{$item};
                   11531:                             $settingstatus = $item;
                   11532:                         }
1.536     raeburn  11533:                     }
                   11534:                 }
                   11535:             }
                   11536:         }
                   11537:         if ($defquota eq '') {
1.1134    raeburn  11538:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11539:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11540:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11541:                 $defquota = $quotahash{'quotas'}{'default'};
                   11542:             }
1.536     raeburn  11543:             $settingstatus = 'default';
1.1139    raeburn  11544:             if ($defquota eq '') {
                   11545:                 if ($quotaname eq 'author') {
                   11546:                     $defquota = 500;
                   11547:                 }
                   11548:             }
1.536     raeburn  11549:         }
                   11550:     } else {
                   11551:         $settingstatus = 'default';
1.1134    raeburn  11552:         if ($quotaname eq 'author') {
                   11553:             $defquota = 500;
                   11554:         } else {
                   11555:             $defquota = 20;
                   11556:         }
1.536     raeburn  11557:     }
                   11558:     if (wantarray) {
                   11559:         return ($defquota,$settingstatus);
1.472     raeburn  11560:     } else {
1.536     raeburn  11561:         return $defquota;
1.472     raeburn  11562:     }
                   11563: }
                   11564: 
1.1135    raeburn  11565: ###############################################
                   11566: 
                   11567: =pod
                   11568: 
1.1136    raeburn  11569: =item * &excess_filesize_warning()
1.1135    raeburn  11570: 
                   11571: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11572: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11573: space to be exceeded.
1.1136    raeburn  11574: 
                   11575: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11576: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11577: 
1.1165    raeburn  11578: Inputs: 7 
1.1136    raeburn  11579: 1. username or coursenum
1.1135    raeburn  11580: 2. domain
1.1136    raeburn  11581: 3. context ('author' or 'course')
1.1135    raeburn  11582: 4. filename of file for which action is being requested
                   11583: 5. filesize (kB) of file
                   11584: 6. action being taken: copy or upload.
1.1237    raeburn  11585: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11586: 
                   11587: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11588:          otherwise return null.
                   11589: 
                   11590: =back
1.1135    raeburn  11591: 
                   11592: =cut
                   11593: 
1.1136    raeburn  11594: sub excess_filesize_warning {
1.1165    raeburn  11595:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11596:     my $current_disk_usage = 0;
1.1165    raeburn  11597:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11598:     if ($context eq 'author') {
                   11599:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11600:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11601:     } else {
                   11602:         foreach my $subdir ('docs','supplemental') {
                   11603:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11604:         }
                   11605:     }
1.1135    raeburn  11606:     $disk_quota = int($disk_quota * 1000);
                   11607:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11608:         return '<p class="LC_warning">'.
1.1135    raeburn  11609:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11610:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11611:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11612:                             $disk_quota,$current_disk_usage).
                   11613:                '</p>';
                   11614:     }
                   11615:     return;
                   11616: }
                   11617: 
                   11618: ###############################################
                   11619: 
                   11620: 
1.1136    raeburn  11621: 
                   11622: 
1.384     raeburn  11623: sub get_secgrprole_info {
                   11624:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11625:     my %sections_count = &get_sections($cdom,$cnum);
                   11626:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11627:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11628:     my @groups = sort(keys(%curr_groups));
                   11629:     my $allroles = [];
                   11630:     my $rolehash;
                   11631:     my $accesshash = {
                   11632:                      active => 'Currently has access',
                   11633:                      future => 'Will have future access',
                   11634:                      previous => 'Previously had access',
                   11635:                   };
                   11636:     if ($needroles) {
                   11637:         $rolehash = {'all' => 'all'};
1.385     albertel 11638:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11639: 	if (&Apache::lonnet::error(%user_roles)) {
                   11640: 	    undef(%user_roles);
                   11641: 	}
                   11642:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11643:             my ($role)=split(/\:/,$item,2);
                   11644:             if ($role eq 'cr') { next; }
                   11645:             if ($role =~ /^cr/) {
                   11646:                 $$rolehash{$role} = (split('/',$role))[3];
                   11647:             } else {
                   11648:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11649:             }
                   11650:         }
                   11651:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11652:             push(@{$allroles},$key);
                   11653:         }
                   11654:         push (@{$allroles},'st');
                   11655:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11656:     }
                   11657:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11658: }
                   11659: 
1.555     raeburn  11660: sub user_picker {
1.1279    raeburn  11661:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11662:     my $currdom = $dom;
1.1253    raeburn  11663:     my @alldoms = &Apache::lonnet::all_domains();
                   11664:     if (@alldoms == 1) {
                   11665:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11666:                                                ['directorysrch'],$alldoms[0]);
                   11667:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11668:         my $showdom = $domdesc;
                   11669:         if ($showdom eq '') {
                   11670:             $showdom = $dom;
                   11671:         }
                   11672:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11673:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11674:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11675:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11676:             }
                   11677:         }
                   11678:     }
1.555     raeburn  11679:     my %curr_selected = (
                   11680:                         srchin => 'dom',
1.580     raeburn  11681:                         srchby => 'lastname',
1.555     raeburn  11682:                       );
                   11683:     my $srchterm;
1.625     raeburn  11684:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11685:         if ($srch->{'srchby'} ne '') {
                   11686:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11687:         }
                   11688:         if ($srch->{'srchin'} ne '') {
                   11689:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11690:         }
                   11691:         if ($srch->{'srchtype'} ne '') {
                   11692:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11693:         }
                   11694:         if ($srch->{'srchdomain'} ne '') {
                   11695:             $currdom = $srch->{'srchdomain'};
                   11696:         }
                   11697:         $srchterm = $srch->{'srchterm'};
                   11698:     }
1.1222    damieng  11699:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11700:                     'usr'       => 'Search criteria',
1.563     raeburn  11701:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11702:                     'uname'     => 'username',
                   11703:                     'lastname'  => 'last name',
1.555     raeburn  11704:                     'lastfirst' => 'last name, first name',
1.558     albertel 11705:                     'crs'       => 'in this course',
1.576     raeburn  11706:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11707:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11708:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11709:                     'exact'     => 'is',
                   11710:                     'contains'  => 'contains',
1.569     raeburn  11711:                     'begins'    => 'begins with',
1.1222    damieng  11712:                                        );
                   11713:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11714:                     'youm'      => "You must include some text to search for.",
                   11715:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11716:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11717:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11718:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11719:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11720:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11721:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11722:                                        );
1.1222    damieng  11723:     &html_escape(\%html_lt);
                   11724:     &js_escape(\%js_lt);
1.1255    raeburn  11725:     my $domform;
1.1277    raeburn  11726:     my $allow_blank = 1;
1.1255    raeburn  11727:     if ($fixeddom) {
1.1277    raeburn  11728:         $allow_blank = 0;
                   11729:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11730:     } else {
1.1287    raeburn  11731:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11732:         my ($trusted,$untrusted);
1.1287    raeburn  11733:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11734:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11735:         } elsif ($context eq 'author') {
1.1288    raeburn  11736:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11737:         } elsif ($context eq 'domain') {
1.1288    raeburn  11738:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11739:         }
1.1288    raeburn  11740:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11741:     }
1.563     raeburn  11742:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11743: 
                   11744:     my @srchins = ('crs','dom','alc','instd');
                   11745: 
                   11746:     foreach my $option (@srchins) {
                   11747:         # FIXME 'alc' option unavailable until 
                   11748:         #       loncreateuser::print_user_query_page()
                   11749:         #       has been completed.
                   11750:         next if ($option eq 'alc');
1.880     raeburn  11751:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11752:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11753:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11754:         if ($curr_selected{'srchin'} eq $option) {
                   11755:             $srchinsel .= ' 
1.1222    damieng  11756:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11757:         } else {
                   11758:             $srchinsel .= '
1.1222    damieng  11759:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11760:         }
1.555     raeburn  11761:     }
1.563     raeburn  11762:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11763: 
                   11764:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11765:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11766:         if ($curr_selected{'srchby'} eq $option) {
                   11767:             $srchbysel .= '
1.1222    damieng  11768:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11769:         } else {
                   11770:             $srchbysel .= '
1.1222    damieng  11771:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11772:          }
                   11773:     }
                   11774:     $srchbysel .= "\n  </select>\n";
                   11775: 
                   11776:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11777:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11778:         if ($curr_selected{'srchtype'} eq $option) {
                   11779:             $srchtypesel .= '
1.1222    damieng  11780:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11781:         } else {
                   11782:             $srchtypesel .= '
1.1222    damieng  11783:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11784:         }
                   11785:     }
                   11786:     $srchtypesel .= "\n  </select>\n";
                   11787: 
1.558     albertel 11788:     my ($newuserscript,$new_user_create);
1.994     raeburn  11789:     my $context_dom = $env{'request.role.domain'};
                   11790:     if ($context eq 'requestcrs') {
                   11791:         if ($env{'form.coursedom'} ne '') { 
                   11792:             $context_dom = $env{'form.coursedom'};
                   11793:         }
                   11794:     }
1.556     raeburn  11795:     if ($forcenewuser) {
1.576     raeburn  11796:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11797:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11798:                 if ($cancreate) {
                   11799:                     $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>';
                   11800:                 } else {
1.799     bisitz   11801:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11802:                     my %usertypetext = (
                   11803:                         official   => 'institutional',
                   11804:                         unofficial => 'non-institutional',
                   11805:                     );
1.799     bisitz   11806:                     $new_user_create = '<p class="LC_warning">'
                   11807:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11808:                                       .' '
                   11809:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11810:                                           ,'<a href="'.$helplink.'">','</a>')
                   11811:                                       .'</p><br />';
1.627     raeburn  11812:                 }
1.576     raeburn  11813:             }
                   11814:         }
                   11815: 
1.556     raeburn  11816:         $newuserscript = <<"ENDSCRIPT";
                   11817: 
1.570     raeburn  11818: function setSearch(createnew,callingForm) {
1.556     raeburn  11819:     if (createnew == 1) {
1.570     raeburn  11820:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11821:             if (callingForm.srchby.options[i].value == 'uname') {
                   11822:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11823:             }
                   11824:         }
1.570     raeburn  11825:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11826:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11827: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11828:             }
                   11829:         }
1.570     raeburn  11830:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11831:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11832:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11833:             }
                   11834:         }
1.570     raeburn  11835:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11836:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11837:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11838:             }
                   11839:         }
                   11840:     }
                   11841: }
                   11842: ENDSCRIPT
1.558     albertel 11843: 
1.556     raeburn  11844:     }
                   11845: 
1.555     raeburn  11846:     my $output = <<"END_BLOCK";
1.556     raeburn  11847: <script type="text/javascript">
1.824     bisitz   11848: // <![CDATA[
1.570     raeburn  11849: function validateEntry(callingForm) {
1.558     albertel 11850: 
1.556     raeburn  11851:     var checkok = 1;
1.558     albertel 11852:     var srchin;
1.570     raeburn  11853:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11854: 	if ( callingForm.srchin[i].checked ) {
                   11855: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11856: 	}
                   11857:     }
                   11858: 
1.570     raeburn  11859:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11860:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11861:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11862:     var srchterm =  callingForm.srchterm.value;
                   11863:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11864:     var msg = "";
                   11865: 
                   11866:     if (srchterm == "") {
                   11867:         checkok = 0;
1.1222    damieng  11868:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11869:     }
                   11870: 
1.569     raeburn  11871:     if (srchtype== 'begins') {
                   11872:         if (srchterm.length < 2) {
                   11873:             checkok = 0;
1.1222    damieng  11874:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11875:         }
                   11876:     }
                   11877: 
1.556     raeburn  11878:     if (srchtype== 'contains') {
                   11879:         if (srchterm.length < 3) {
                   11880:             checkok = 0;
1.1222    damieng  11881:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11882:         }
                   11883:     }
                   11884:     if (srchin == 'instd') {
                   11885:         if (srchdomain == '') {
                   11886:             checkok = 0;
1.1222    damieng  11887:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11888:         }
                   11889:     }
                   11890:     if (srchin == 'dom') {
                   11891:         if (srchdomain == '') {
                   11892:             checkok = 0;
1.1222    damieng  11893:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11894:         }
                   11895:     }
                   11896:     if (srchby == 'lastfirst') {
                   11897:         if (srchterm.indexOf(",") == -1) {
                   11898:             checkok = 0;
1.1222    damieng  11899:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11900:         }
                   11901:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11902:             checkok = 0;
1.1222    damieng  11903:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11904:         }
                   11905:     }
                   11906:     if (checkok == 0) {
1.1222    damieng  11907:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11908:         return;
                   11909:     }
                   11910:     if (checkok == 1) {
1.570     raeburn  11911:         callingForm.submit();
1.556     raeburn  11912:     }
                   11913: }
                   11914: 
                   11915: $newuserscript
                   11916: 
1.824     bisitz   11917: // ]]>
1.556     raeburn  11918: </script>
1.558     albertel 11919: 
                   11920: $new_user_create
                   11921: 
1.555     raeburn  11922: END_BLOCK
1.558     albertel 11923: 
1.876     raeburn  11924:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11925:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11926:                $domform.
                   11927:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11928:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11929:                $srchbysel.
                   11930:                $srchtypesel. 
                   11931:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11932:                $srchinsel.
                   11933:                &Apache::lonhtmlcommon::row_closure(1). 
                   11934:                &Apache::lonhtmlcommon::end_pick_box().
                   11935:                '<br />';
1.1253    raeburn  11936:     return ($output,1);
1.555     raeburn  11937: }
                   11938: 
1.612     raeburn  11939: sub user_rule_check {
1.615     raeburn  11940:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11941:     my ($response,%inst_response);
1.612     raeburn  11942:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11943:         if (keys(%{$usershash}) > 1) {
                   11944:             my (%by_username,%by_id,%userdoms);
                   11945:             my $checkid; 
                   11946:             if (ref($checks) eq 'HASH') {
                   11947:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11948:                     $checkid = 1;
                   11949:                 }
                   11950:             }
                   11951:             foreach my $user (keys(%{$usershash})) {
                   11952:                 my ($uname,$udom) = split(/:/,$user);
                   11953:                 if ($checkid) {
                   11954:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11955:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11956:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11957:                             $userdoms{$udom} = 1;
1.1227    raeburn  11958:                             if (ref($inst_results) eq 'HASH') {
                   11959:                                 $inst_results->{$uname.':'.$udom} = {};
                   11960:                             }
1.1226    raeburn  11961:                         }
                   11962:                     }
                   11963:                 } else {
                   11964:                     $by_username{$udom}{$uname} = 1;
                   11965:                     $userdoms{$udom} = 1;
1.1227    raeburn  11966:                     if (ref($inst_results) eq 'HASH') {
                   11967:                         $inst_results->{$uname.':'.$udom} = {};
                   11968:                     }
1.1226    raeburn  11969:                 }
                   11970:             }
                   11971:             foreach my $udom (keys(%userdoms)) {
                   11972:                 if (!$got_rules->{$udom}) {
                   11973:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11974:                                                              ['usercreation'],$udom);
                   11975:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11976:                         foreach my $item ('username','id') {
                   11977:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11978:                                 $$curr_rules{$udom}{$item} =
                   11979:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11980:                             }
                   11981:                         }
                   11982:                     }
                   11983:                     $got_rules->{$udom} = 1;
                   11984:                 }
1.612     raeburn  11985:             }
1.1226    raeburn  11986:             if ($checkid) {
                   11987:                 foreach my $udom (keys(%by_id)) {
                   11988:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11989:                     if ($outcome eq 'ok') {
1.1227    raeburn  11990:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11991:                             my $uname = $by_id{$udom}{$id};
                   11992:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11993:                         }
1.1226    raeburn  11994:                         if (ref($results) eq 'HASH') {
                   11995:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11996:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11997:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11998:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11999:                                 }
1.1226    raeburn  12000:                             }
                   12001:                         }
                   12002:                     }
1.612     raeburn  12003:                 }
1.615     raeburn  12004:             } else {
1.1226    raeburn  12005:                 foreach my $udom (keys(%by_username)) {
                   12006:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   12007:                     if ($outcome eq 'ok') {
1.1227    raeburn  12008:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   12009:                             $inst_response{$uname.':'.$udom} = $outcome;
                   12010:                         }
1.1226    raeburn  12011:                         if (ref($results) eq 'HASH') {
                   12012:                             foreach my $uname (keys(%{$results})) {
                   12013:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   12014:                             }
                   12015:                         }
                   12016:                     }
                   12017:                 }
1.612     raeburn  12018:             }
1.1226    raeburn  12019:         } elsif (keys(%{$usershash}) == 1) {
                   12020:             my $user = (keys(%{$usershash}))[0];
                   12021:             my ($uname,$udom) = split(/:/,$user);
                   12022:             if (($udom ne '') && ($uname ne '')) {
                   12023:                 if (ref($usershash->{$user}) eq 'HASH') {
                   12024:                     if (ref($checks) eq 'HASH') {
                   12025:                         if (defined($checks->{'username'})) {
                   12026:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   12027:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   12028:                         } elsif (defined($checks->{'id'})) {
                   12029:                             if ($usershash->{$user}->{'id'} ne '') {
                   12030:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12031:                                     &Apache::lonnet::get_instuser($udom,undef,
                   12032:                                                                   $usershash->{$user}->{'id'});
                   12033:                             } else {
                   12034:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   12035:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   12036:                             }
1.585     raeburn  12037:                         }
1.1226    raeburn  12038:                     } else {
                   12039:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   12040:                             &Apache::lonnet::get_instuser($udom,$uname);
                   12041:                        return;
                   12042:                     }
                   12043:                     if (!$got_rules->{$udom}) {
                   12044:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   12045:                                                                  ['usercreation'],$udom);
                   12046:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   12047:                             foreach my $item ('username','id') {
                   12048:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   12049:                                    $$curr_rules{$udom}{$item} = 
                   12050:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   12051:                                 }
                   12052:                             }
                   12053:                         }
                   12054:                         $got_rules->{$udom} = 1;
1.585     raeburn  12055:                     }
                   12056:                 }
1.1226    raeburn  12057:             } else {
                   12058:                 return;
                   12059:             }
                   12060:         } else {
                   12061:             return;
                   12062:         }
                   12063:         foreach my $user (keys(%{$usershash})) {
                   12064:             my ($uname,$udom) = split(/:/,$user);
                   12065:             next if (($udom eq '') || ($uname eq ''));
                   12066:             my $id;
1.1227    raeburn  12067:             if (ref($inst_results) eq 'HASH') {
                   12068:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   12069:                     $id = $inst_results->{$user}->{'id'};
                   12070:                 }
                   12071:             }
                   12072:             if ($id eq '') { 
                   12073:                 if (ref($usershash->{$user})) {
                   12074:                     $id = $usershash->{$user}->{'id'};
                   12075:                 }
1.585     raeburn  12076:             }
1.612     raeburn  12077:             foreach my $item (keys(%{$checks})) {
                   12078:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   12079:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   12080:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  12081:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   12082:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  12083:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   12084:                                 if ($rule_check{$rule}) {
                   12085:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  12086:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  12087:                                         if (ref($inst_results) eq 'HASH') {
                   12088:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   12089:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   12090:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  12091:                                                 } elsif ($item eq 'id') {
                   12092:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   12093:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   12094:                                                     }
1.615     raeburn  12095:                                                 }
1.612     raeburn  12096:                                             }
                   12097:                                         }
1.615     raeburn  12098:                                     }
                   12099:                                     last;
1.585     raeburn  12100:                                 }
                   12101:                             }
                   12102:                         }
                   12103:                     }
                   12104:                 }
                   12105:             }
                   12106:         }
                   12107:     }
1.612     raeburn  12108:     return;
                   12109: }
                   12110: 
                   12111: sub user_rule_formats {
                   12112:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   12113:     my %text = ( 
                   12114:                  'username' => 'Usernames',
                   12115:                  'id'       => 'IDs',
                   12116:                );
                   12117:     my $output;
                   12118:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   12119:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   12120:         if (@{$ruleorder} > 0) {
1.1102    raeburn  12121:             $output = '<br />'.
                   12122:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   12123:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   12124:                       ' <ul>';
1.612     raeburn  12125:             foreach my $rule (@{$ruleorder}) {
                   12126:                 if (ref($curr_rules) eq 'ARRAY') {
                   12127:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   12128:                         if (ref($rules->{$rule}) eq 'HASH') {
                   12129:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   12130:                                         $rules->{$rule}{'desc'}.'</li>';
                   12131:                         }
                   12132:                     }
                   12133:                 }
                   12134:             }
                   12135:             $output .= '</ul>';
                   12136:         }
                   12137:     }
                   12138:     return $output;
                   12139: }
                   12140: 
                   12141: sub instrule_disallow_msg {
1.615     raeburn  12142:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  12143:     my $response;
                   12144:     my %text = (
                   12145:                   item   => 'username',
                   12146:                   items  => 'usernames',
                   12147:                   match  => 'matches',
                   12148:                   do     => 'does',
                   12149:                   action => 'a username',
                   12150:                   one    => 'one',
                   12151:                );
                   12152:     if ($count > 1) {
                   12153:         $text{'item'} = 'usernames';
                   12154:         $text{'match'} ='match';
                   12155:         $text{'do'} = 'do';
                   12156:         $text{'action'} = 'usernames',
                   12157:         $text{'one'} = 'ones';
                   12158:     }
                   12159:     if ($checkitem eq 'id') {
                   12160:         $text{'items'} = 'IDs';
                   12161:         $text{'item'} = 'ID';
                   12162:         $text{'action'} = 'an ID';
1.615     raeburn  12163:         if ($count > 1) {
                   12164:             $text{'item'} = 'IDs';
                   12165:             $text{'action'} = 'IDs';
                   12166:         }
1.612     raeburn  12167:     }
1.674     bisitz   12168:     $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  12169:     if ($mode eq 'upload') {
                   12170:         if ($checkitem eq 'username') {
                   12171:             $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'}.");
                   12172:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12173:             $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  12174:         }
1.669     raeburn  12175:     } elsif ($mode eq 'selfcreate') {
                   12176:         if ($checkitem eq 'id') {
                   12177:             $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.");
                   12178:         }
1.615     raeburn  12179:     } else {
                   12180:         if ($checkitem eq 'username') {
                   12181:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12182:         } elsif ($checkitem eq 'id') {
                   12183:             $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.");
                   12184:         }
1.612     raeburn  12185:     }
                   12186:     return $response;
1.585     raeburn  12187: }
                   12188: 
1.624     raeburn  12189: sub personal_data_fieldtitles {
                   12190:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12191:                         id => 'Student/Employee ID',
                   12192:                         permanentemail => 'E-mail address',
                   12193:                         lastname => 'Last Name',
                   12194:                         firstname => 'First Name',
                   12195:                         middlename => 'Middle Name',
                   12196:                         generation => 'Generation',
                   12197:                         gen => 'Generation',
1.765     raeburn  12198:                         inststatus => 'Affiliation',
1.624     raeburn  12199:                    );
                   12200:     return %fieldtitles;
                   12201: }
                   12202: 
1.642     raeburn  12203: sub sorted_inst_types {
                   12204:     my ($dom) = @_;
1.1185    raeburn  12205:     my ($usertypes,$order);
                   12206:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12207:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12208:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12209:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12210:     } else {
                   12211:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12212:     }
1.642     raeburn  12213:     my $othertitle = &mt('All users');
                   12214:     if ($env{'request.course.id'}) {
1.668     raeburn  12215:         $othertitle  = &mt('Any users');
1.642     raeburn  12216:     }
                   12217:     my @types;
                   12218:     if (ref($order) eq 'ARRAY') {
                   12219:         @types = @{$order};
                   12220:     }
                   12221:     if (@types == 0) {
                   12222:         if (ref($usertypes) eq 'HASH') {
                   12223:             @types = sort(keys(%{$usertypes}));
                   12224:         }
                   12225:     }
                   12226:     if (keys(%{$usertypes}) > 0) {
                   12227:         $othertitle = &mt('Other users');
                   12228:     }
                   12229:     return ($othertitle,$usertypes,\@types);
                   12230: }
                   12231: 
1.645     raeburn  12232: sub get_institutional_codes {
1.1361    raeburn  12233:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12234: # Get complete list of course sections to update
                   12235:     my @currsections = ();
                   12236:     my @currxlists = ();
1.1361    raeburn  12237:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12238:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12239:     my $crskey = $crs.':'.$coursecode;
                   12240:     @{$unclutteredsec{$crskey}} = ();
                   12241:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12242: 
                   12243:     if ($$settings{'internal.sectionnums'} ne '') {
                   12244:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12245:     }
                   12246: 
                   12247:     if ($$settings{'internal.crosslistings'} ne '') {
                   12248:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12249:     }
                   12250: 
                   12251:     if (@currxlists > 0) {
1.1361    raeburn  12252:         foreach my $xl (@currxlists) {
                   12253:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12254:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12255:                     push(@{$allcourses},$1);
1.645     raeburn  12256:                     $$LC_code{$1} = $2;
                   12257:                 }
                   12258:             }
                   12259:         }
                   12260:     }
1.1361    raeburn  12261: 
1.645     raeburn  12262:     if (@currsections > 0) {
1.1361    raeburn  12263:         foreach my $sec (@currsections) {
                   12264:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12265:                 my $instsec = $1;
1.645     raeburn  12266:                 my $lc_sec = $2;
1.1361    raeburn  12267:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12268:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12269:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12270:                 }
                   12271:             }
                   12272:         }
                   12273:     }
                   12274: 
                   12275:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12276:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12277:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12278:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12279:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12280:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12281:                     push(@{$allcourses},$sec);
1.1361    raeburn  12282:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12283:                 }
                   12284:             }
                   12285:         }
                   12286:     }
                   12287:     return;
                   12288: }
                   12289: 
1.971     raeburn  12290: sub get_standard_codeitems {
                   12291:     return ('Year','Semester','Department','Number','Section');
                   12292: }
                   12293: 
1.112     bowersj2 12294: =pod
                   12295: 
1.780     raeburn  12296: =head1 Slot Helpers
                   12297: 
                   12298: =over 4
                   12299: 
                   12300: =item * sorted_slots()
                   12301: 
1.1040    raeburn  12302: Sorts an array of slot names in order of an optional sort key,
                   12303: default sort is by slot start time (earliest first). 
1.780     raeburn  12304: 
                   12305: Inputs:
                   12306: 
                   12307: =over 4
                   12308: 
                   12309: slotsarr  - Reference to array of unsorted slot names.
                   12310: 
                   12311: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12312: 
1.1040    raeburn  12313: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12314: 
1.549     albertel 12315: =back
                   12316: 
1.780     raeburn  12317: Returns:
                   12318: 
                   12319: =over 4
                   12320: 
1.1040    raeburn  12321: sorted   - An array of slot names sorted by a specified sort key 
                   12322:            (default sort key is start time of the slot).
1.780     raeburn  12323: 
                   12324: =back
                   12325: 
                   12326: =cut
                   12327: 
                   12328: 
                   12329: sub sorted_slots {
1.1040    raeburn  12330:     my ($slotsarr,$slots,$sortkey) = @_;
                   12331:     if ($sortkey eq '') {
                   12332:         $sortkey = 'starttime';
                   12333:     }
1.780     raeburn  12334:     my @sorted;
                   12335:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12336:         @sorted =
                   12337:             sort {
                   12338:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12339:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12340:                      }
                   12341:                      if (ref($slots->{$a})) { return -1;}
                   12342:                      if (ref($slots->{$b})) { return 1;}
                   12343:                      return 0;
                   12344:                  } @{$slotsarr};
                   12345:     }
                   12346:     return @sorted;
                   12347: }
                   12348: 
1.1040    raeburn  12349: =pod
                   12350: 
                   12351: =item * get_future_slots()
                   12352: 
                   12353: Inputs:
                   12354: 
                   12355: =over 4
                   12356: 
                   12357: cnum - course number
                   12358: 
                   12359: cdom - course domain
                   12360: 
                   12361: now - current UNIX time
                   12362: 
                   12363: symb - optional symb
                   12364: 
                   12365: =back
                   12366: 
                   12367: Returns:
                   12368: 
                   12369: =over 4
                   12370: 
                   12371: sorted_reservable - ref to array of student_schedulable slots currently 
                   12372:                     reservable, ordered by end date of reservation period.
                   12373: 
                   12374: reservable_now - ref to hash of student_schedulable slots currently
                   12375:                  reservable.
                   12376: 
                   12377:     Keys in inner hash are:
                   12378:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12379:     (b) endreserve: end date of reservation period.
                   12380:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12381:         selected.
1.1040    raeburn  12382: 
                   12383: sorted_future - ref to array of student_schedulable slots reservable in
                   12384:                 the future, ordered by start date of reservation period.
                   12385: 
                   12386: future_reservable - ref to hash of student_schedulable slots reservable
                   12387:                     in the future.
                   12388: 
                   12389:     Keys in inner hash are:
                   12390:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12391:     (b) startreserve: start date of reservation period.
                   12392:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12393:         selected.
1.1040    raeburn  12394: 
                   12395: =back
                   12396: 
                   12397: =cut
                   12398: 
                   12399: sub get_future_slots {
                   12400:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12401:     my $map;
                   12402:     if ($symb) {
                   12403:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12404:     }
1.1040    raeburn  12405:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12406:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12407:     foreach my $slot (keys(%slots)) {
                   12408:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12409:         if ($symb) {
1.1229    raeburn  12410:             if ($slots{$slot}->{'symb'} ne '') {
                   12411:                 my $canuse;
                   12412:                 my %oksymbs;
                   12413:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12414:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12415:                 if ($oksymbs{$symb}) {
                   12416:                     $canuse = 1;
                   12417:                 } else {
                   12418:                     foreach my $item (@slotsymbs) {
                   12419:                         if ($item =~ /\.(page|sequence)$/) {
                   12420:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12421:                             if (($map ne '') && ($map eq $sloturl)) {
                   12422:                                 $canuse = 1;
                   12423:                                 last;
                   12424:                             }
                   12425:                         }
                   12426:                     }
                   12427:                 }
                   12428:                 next unless ($canuse);
                   12429:             }
1.1040    raeburn  12430:         }
                   12431:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12432:             ($slots{$slot}->{'endtime'} > $now)) {
                   12433:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12434:                 my $userallowed = 0;
                   12435:                 if ($slots{$slot}->{'allowedsections'}) {
                   12436:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12437:                     if (!defined($env{'request.role.sec'})
                   12438:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12439:                         $userallowed=1;
                   12440:                     } else {
                   12441:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12442:                             $userallowed=1;
                   12443:                         }
                   12444:                     }
                   12445:                     unless ($userallowed) {
                   12446:                         if (defined($env{'request.course.groups'})) {
                   12447:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12448:                             foreach my $group (@groups) {
                   12449:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12450:                                     $userallowed=1;
                   12451:                                     last;
                   12452:                                 }
                   12453:                             }
                   12454:                         }
                   12455:                     }
                   12456:                 }
                   12457:                 if ($slots{$slot}->{'allowedusers'}) {
                   12458:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12459:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12460:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12461:                         $userallowed = 1;
                   12462:                     }
                   12463:                 }
                   12464:                 next unless($userallowed);
                   12465:             }
                   12466:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12467:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12468:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12469:             my $uniqueperiod;
                   12470:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12471:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12472:             }
1.1040    raeburn  12473:             if (($startreserve < $now) &&
                   12474:                 (!$endreserve || $endreserve > $now)) {
                   12475:                 my $lastres = $endreserve;
                   12476:                 if (!$lastres) {
                   12477:                     $lastres = $slots{$slot}->{'starttime'};
                   12478:                 }
                   12479:                 $reservable_now{$slot} = {
                   12480:                                            symb       => $symb,
1.1250    raeburn  12481:                                            endreserve => $lastres,
                   12482:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12483:                                          };
                   12484:             } elsif (($startreserve > $now) &&
                   12485:                      (!$endreserve || $endreserve > $startreserve)) {
                   12486:                 $future_reservable{$slot} = {
                   12487:                                               symb         => $symb,
1.1250    raeburn  12488:                                               startreserve => $startreserve,
                   12489:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12490:                                             };
                   12491:             }
                   12492:         }
                   12493:     }
                   12494:     my @unsorted_reservable = keys(%reservable_now);
                   12495:     if (@unsorted_reservable > 0) {
                   12496:         @sorted_reservable = 
                   12497:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12498:     }
                   12499:     my @unsorted_future = keys(%future_reservable);
                   12500:     if (@unsorted_future > 0) {
                   12501:         @sorted_future =
                   12502:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12503:     }
                   12504:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12505: }
1.780     raeburn  12506: 
                   12507: =pod
                   12508: 
1.1057    foxr     12509: =back
                   12510: 
1.549     albertel 12511: =head1 HTTP Helpers
                   12512: 
                   12513: =over 4
                   12514: 
1.648     raeburn  12515: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12516: 
1.258     albertel 12517: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12518: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12519: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12520: 
                   12521: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12522: $possible_names is an ref to an array of form element names.  As an example:
                   12523: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12524: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12525: 
                   12526: =cut
1.1       albertel 12527: 
1.6       albertel 12528: sub get_unprocessed_cgi {
1.25      albertel 12529:   my ($query,$possible_names)= @_;
1.26      matthew  12530:   # $Apache::lonxml::debug=1;
1.356     albertel 12531:   foreach my $pair (split(/&/,$query)) {
                   12532:     my ($name, $value) = split(/=/,$pair);
1.369     www      12533:     $name = &unescape($name);
1.25      albertel 12534:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12535:       $value =~ tr/+/ /;
                   12536:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12537:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12538:     }
1.16      harris41 12539:   }
1.6       albertel 12540: }
                   12541: 
1.112     bowersj2 12542: =pod
                   12543: 
1.648     raeburn  12544: =item * &cacheheader() 
1.112     bowersj2 12545: 
                   12546: returns cache-controlling header code
                   12547: 
                   12548: =cut
                   12549: 
1.7       albertel 12550: sub cacheheader {
1.258     albertel 12551:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12552:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12553:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12554:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12555:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12556:     return $output;
1.7       albertel 12557: }
                   12558: 
1.112     bowersj2 12559: =pod
                   12560: 
1.648     raeburn  12561: =item * &no_cache($r) 
1.112     bowersj2 12562: 
                   12563: specifies header code to not have cache
                   12564: 
                   12565: =cut
                   12566: 
1.9       albertel 12567: sub no_cache {
1.216     albertel 12568:     my ($r) = @_;
                   12569:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12570: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12571:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12572:     $r->no_cache(1);
                   12573:     $r->header_out("Expires" => $date);
                   12574:     $r->header_out("Pragma" => "no-cache");
1.123     www      12575: }
                   12576: 
                   12577: sub content_type {
1.181     albertel 12578:     my ($r,$type,$charset) = @_;
1.299     foxr     12579:     if ($r) {
                   12580: 	#  Note that printout.pl calls this with undef for $r.
                   12581: 	&no_cache($r);
                   12582:     }
1.258     albertel 12583:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12584:     unless ($charset) {
                   12585: 	$charset=&Apache::lonlocal::current_encoding;
                   12586:     }
                   12587:     if ($charset) { $type.='; charset='.$charset; }
                   12588:     if ($r) {
                   12589: 	$r->content_type($type);
                   12590:     } else {
                   12591: 	print("Content-type: $type\n\n");
                   12592:     }
1.9       albertel 12593: }
1.25      albertel 12594: 
1.112     bowersj2 12595: =pod
                   12596: 
1.648     raeburn  12597: =item * &add_to_env($name,$value) 
1.112     bowersj2 12598: 
1.258     albertel 12599: adds $name to the %env hash with value
1.112     bowersj2 12600: $value, if $name already exists, the entry is converted to an array
                   12601: reference and $value is added to the array.
                   12602: 
                   12603: =cut
                   12604: 
1.25      albertel 12605: sub add_to_env {
                   12606:   my ($name,$value)=@_;
1.258     albertel 12607:   if (defined($env{$name})) {
                   12608:     if (ref($env{$name})) {
1.25      albertel 12609:       #already have multiple values
1.258     albertel 12610:       push(@{ $env{$name} },$value);
1.25      albertel 12611:     } else {
                   12612:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12613:       my $first=$env{$name};
                   12614:       undef($env{$name});
                   12615:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12616:     }
                   12617:   } else {
1.258     albertel 12618:     $env{$name}=$value;
1.25      albertel 12619:   }
1.31      albertel 12620: }
1.149     albertel 12621: 
                   12622: =pod
                   12623: 
1.648     raeburn  12624: =item * &get_env_multiple($name) 
1.149     albertel 12625: 
1.258     albertel 12626: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12627: values may be defined and end up as an array ref.
                   12628: 
                   12629: returns an array of values
                   12630: 
                   12631: =cut
                   12632: 
                   12633: sub get_env_multiple {
                   12634:     my ($name) = @_;
                   12635:     my @values;
1.258     albertel 12636:     if (defined($env{$name})) {
1.149     albertel 12637:         # exists is it an array
1.258     albertel 12638:         if (ref($env{$name})) {
                   12639:             @values=@{ $env{$name} };
1.149     albertel 12640:         } else {
1.258     albertel 12641:             $values[0]=$env{$name};
1.149     albertel 12642:         }
                   12643:     }
                   12644:     return(@values);
                   12645: }
                   12646: 
1.1249    damieng  12647: # Looks at given dependencies, and returns something depending on the context.
                   12648: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12649: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12650: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12651: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12652: # $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.
                   12653: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12654: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12655: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12656: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12657: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12658: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12659: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12660: # @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)
                   12661: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12662: sub ask_for_embedded_content {
1.1249    damieng  12663:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12664:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12665:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12666:         %currsubfile,%unused,$rem);
1.1071    raeburn  12667:     my $counter = 0;
                   12668:     my $numnew = 0;
1.987     raeburn  12669:     my $numremref = 0;
                   12670:     my $numinvalid = 0;
                   12671:     my $numpathchg = 0;
                   12672:     my $numexisting = 0;
1.1071    raeburn  12673:     my $numunused = 0;
                   12674:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12675:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12676:     my $heading = &mt('Upload embedded files');
                   12677:     my $buttontext = &mt('Upload');
                   12678: 
1.1249    damieng  12679:     # fills these variables based on the context:
                   12680:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12681:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12682:     if ($env{'request.course.id'}) {
1.1123    raeburn  12683:         if ($actionurl eq '/adm/dependencies') {
                   12684:             $navmap = Apache::lonnavmaps::navmap->new();
                   12685:         }
                   12686:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12687:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12688:     }
1.1123    raeburn  12689:     if (($actionurl eq '/adm/portfolio') || 
                   12690:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12691:         my $current_path='/';
                   12692:         if ($env{'form.currentpath'}) {
                   12693:             $current_path = $env{'form.currentpath'};
                   12694:         }
                   12695:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12696:             $udom = $cdom;
                   12697:             $uname = $cnum;
1.984     raeburn  12698:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12699:         } else {
                   12700:             $udom = $env{'user.domain'};
                   12701:             $uname = $env{'user.name'};
                   12702:             $url = '/userfiles/portfolio';
                   12703:         }
1.987     raeburn  12704:         $toplevel = $url.'/';
1.984     raeburn  12705:         $url .= $current_path;
                   12706:         $getpropath = 1;
1.987     raeburn  12707:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12708:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12709:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12710:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12711:         $toplevel = $url;
1.984     raeburn  12712:         if ($rest ne '') {
1.987     raeburn  12713:             $url .= $rest;
                   12714:         }
                   12715:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12716:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12717:             $url = $args->{'docs_url'};
                   12718:             $toplevel = $url;
1.1084    raeburn  12719:             if ($args->{'context'} eq 'paste') {
                   12720:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12721:                 ($path) = 
                   12722:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12723:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12724:                 $fileloc =~ s{^/}{};
                   12725:             }
1.1071    raeburn  12726:         }
1.1084    raeburn  12727:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12728:         if ($env{'request.course.id'} ne '') {
                   12729:             if (ref($args) eq 'HASH') {
                   12730:                 $url = $args->{'docs_url'};
                   12731:                 $title = $args->{'docs_title'};
1.1126    raeburn  12732:                 $toplevel = $url; 
                   12733:                 unless ($toplevel =~ m{^/}) {
                   12734:                     $toplevel = "/$url";
                   12735:                 }
1.1085    raeburn  12736:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12737:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12738:                     $path = $1;
                   12739:                 } else {
                   12740:                     ($path) =
                   12741:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12742:                 }
1.1195    raeburn  12743:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12744:                     $fileloc = $toplevel;
                   12745:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12746:                     my ($udom,$uname,$fname) =
                   12747:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12748:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12749:                 } else {
                   12750:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12751:                 }
1.1071    raeburn  12752:                 $fileloc =~ s{^/}{};
                   12753:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12754:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12755:             }
1.987     raeburn  12756:         }
1.1123    raeburn  12757:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12758:         $udom = $cdom;
                   12759:         $uname = $cnum;
                   12760:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12761:         $toplevel = $url;
                   12762:         $path = $url;
                   12763:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12764:         $fileloc =~ s{^/}{};
1.987     raeburn  12765:     }
1.1249    damieng  12766:     
                   12767:     # parses the dependency paths to get some info
                   12768:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12769:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12770:     # (will be completed later)
                   12771:     # $mapping:
                   12772:     #   for external URLs: external URL -> external URL
                   12773:     #   for relative paths: clean path -> original path
                   12774:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12775:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12776:     foreach my $file (keys(%{$allfiles})) {
                   12777:         my $embed_file;
                   12778:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12779:             $embed_file = $1;
                   12780:         } else {
                   12781:             $embed_file = $file;
                   12782:         }
1.1158    raeburn  12783:         my ($absolutepath,$cleaned_file);
                   12784:         if ($embed_file =~ m{^\w+://}) {
                   12785:             $cleaned_file = $embed_file;
1.1147    raeburn  12786:             $newfiles{$cleaned_file} = 1;
                   12787:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12788:         } else {
1.1158    raeburn  12789:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12790:             if ($embed_file =~ m{^/}) {
                   12791:                 $absolutepath = $embed_file;
                   12792:             }
1.1147    raeburn  12793:             if ($cleaned_file =~ m{/}) {
                   12794:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12795:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12796:                 my $item = $fname;
                   12797:                 if ($path ne '') {
                   12798:                     $item = $path.'/'.$fname;
                   12799:                     $subdependencies{$path}{$fname} = 1;
                   12800:                 } else {
                   12801:                     $dependencies{$item} = 1;
                   12802:                 }
                   12803:                 if ($absolutepath) {
                   12804:                     $mapping{$item} = $absolutepath;
                   12805:                 } else {
                   12806:                     $mapping{$item} = $embed_file;
                   12807:                 }
                   12808:             } else {
                   12809:                 $dependencies{$embed_file} = 1;
                   12810:                 if ($absolutepath) {
1.1147    raeburn  12811:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12812:                 } else {
1.1147    raeburn  12813:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12814:                 }
                   12815:             }
1.984     raeburn  12816:         }
                   12817:     }
1.1249    damieng  12818:     
                   12819:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12820:     # and lists
                   12821:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12822:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12823:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12824:     #                                    the path had to be cleaned up
                   12825:     # $existing: hash clean path -> 1 if the file exists
                   12826:     # $numexisting: number of keys in $existing
                   12827:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12828:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12829:     #                                      dependency subdirectories that are
                   12830:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12831:     my $dirptr = 16384;
1.984     raeburn  12832:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12833:         $currsubfile{$path} = {};
1.1123    raeburn  12834:         if (($actionurl eq '/adm/portfolio') || 
                   12835:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12836:             my ($sublistref,$listerror) =
                   12837:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12838:             if (ref($sublistref) eq 'ARRAY') {
                   12839:                 foreach my $line (@{$sublistref}) {
                   12840:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12841:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12842:                 }
1.984     raeburn  12843:             }
1.987     raeburn  12844:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12845:             if (opendir(my $dir,$url.'/'.$path)) {
                   12846:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12847:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12848:             }
1.1084    raeburn  12849:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12850:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12851:                   ($args->{'context'} eq 'paste')) ||
                   12852:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12853:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12854:                 my $dir;
                   12855:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12856:                     $dir = $fileloc;
                   12857:                 } else {
                   12858:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12859:                 }
1.1071    raeburn  12860:                 if ($dir ne '') {
                   12861:                     my ($sublistref,$listerror) =
                   12862:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12863:                     if (ref($sublistref) eq 'ARRAY') {
                   12864:                         foreach my $line (@{$sublistref}) {
                   12865:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12866:                                 undef,$mtime)=split(/\&/,$line,12);
                   12867:                             unless (($testdir&$dirptr) ||
                   12868:                                     ($file_name =~ /^\.\.?$/)) {
                   12869:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12870:                             }
                   12871:                         }
                   12872:                     }
                   12873:                 }
1.984     raeburn  12874:             }
                   12875:         }
                   12876:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12877:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12878:                 my $item = $path.'/'.$file;
                   12879:                 unless ($mapping{$item} eq $item) {
                   12880:                     $pathchanges{$item} = 1;
                   12881:                 }
                   12882:                 $existing{$item} = 1;
                   12883:                 $numexisting ++;
                   12884:             } else {
                   12885:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12886:             }
                   12887:         }
1.1071    raeburn  12888:         if ($actionurl eq '/adm/dependencies') {
                   12889:             foreach my $path (keys(%currsubfile)) {
                   12890:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12891:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12892:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12893:                              next if (($rem ne '') &&
                   12894:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12895:                                        (ref($navmap) &&
                   12896:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12897:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12898:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12899:                              $unused{$path.'/'.$file} = 1; 
                   12900:                          }
                   12901:                     }
                   12902:                 }
                   12903:             }
                   12904:         }
1.984     raeburn  12905:     }
1.1249    damieng  12906:     
                   12907:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12908:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12909:     my %currfile;
1.1123    raeburn  12910:     if (($actionurl eq '/adm/portfolio') ||
                   12911:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12912:         my ($dirlistref,$listerror) =
                   12913:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12914:         if (ref($dirlistref) eq 'ARRAY') {
                   12915:             foreach my $line (@{$dirlistref}) {
                   12916:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12917:                 $currfile{$file_name} = 1;
                   12918:             }
1.984     raeburn  12919:         }
1.987     raeburn  12920:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12921:         if (opendir(my $dir,$url)) {
1.987     raeburn  12922:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12923:             map {$currfile{$_} = 1;} @dir_list;
                   12924:         }
1.1084    raeburn  12925:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12926:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12927:               ($args->{'context'} eq 'paste')) ||
                   12928:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12929:         if ($env{'request.course.id'} ne '') {
                   12930:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12931:             if ($dir ne '') {
                   12932:                 my ($dirlistref,$listerror) =
                   12933:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12934:                 if (ref($dirlistref) eq 'ARRAY') {
                   12935:                     foreach my $line (@{$dirlistref}) {
                   12936:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12937:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12938:                         unless (($testdir&$dirptr) ||
                   12939:                                 ($file_name =~ /^\.\.?$/)) {
                   12940:                             $currfile{$file_name} = [$size,$mtime];
                   12941:                         }
                   12942:                     }
                   12943:                 }
                   12944:             }
                   12945:         }
1.984     raeburn  12946:     }
1.1249    damieng  12947:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12948:     # are not in subdirectories, using $currfile
1.984     raeburn  12949:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12950:         if (exists($currfile{$file})) {
1.987     raeburn  12951:             unless ($mapping{$file} eq $file) {
                   12952:                 $pathchanges{$file} = 1;
                   12953:             }
                   12954:             $existing{$file} = 1;
                   12955:             $numexisting ++;
                   12956:         } else {
1.984     raeburn  12957:             $newfiles{$file} = 1;
                   12958:         }
                   12959:     }
1.1071    raeburn  12960:     foreach my $file (keys(%currfile)) {
                   12961:         unless (($file eq $filename) ||
                   12962:                 ($file eq $filename.'.bak') ||
                   12963:                 ($dependencies{$file})) {
1.1085    raeburn  12964:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12965:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12966:                     next if (($rem ne '') &&
                   12967:                              (($env{"httpref.$rem".$file} ne '') ||
                   12968:                               (ref($navmap) &&
                   12969:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12970:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12971:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12972:                 }
1.1085    raeburn  12973:             }
1.1071    raeburn  12974:             $unused{$file} = 1;
                   12975:         }
                   12976:     }
1.1249    damieng  12977:     
                   12978:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12979:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12980:         ($args->{'context'} eq 'paste')) {
                   12981:         $counter = scalar(keys(%existing));
                   12982:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12983:         return ($output,$counter,$numpathchg,\%existing);
                   12984:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12985:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12986:         $counter = scalar(keys(%existing));
                   12987:         $numpathchg = scalar(keys(%pathchanges));
                   12988:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12989:     }
1.1249    damieng  12990:     
                   12991:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12992:     
                   12993:     # $upload_output: missing dependencies (with upload form)
                   12994:     # $modify_output: uploaded dependencies (in use)
                   12995:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12996:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12997:         if ($actionurl eq '/adm/dependencies') {
                   12998:             next if ($embed_file =~ m{^\w+://});
                   12999:         }
1.660     raeburn  13000:         $upload_output .= &start_data_table_row().
1.1123    raeburn  13001:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  13002:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  13003:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  13004:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   13005:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  13006:         }
1.1123    raeburn  13007:         $upload_output .= '</td>';
1.1071    raeburn  13008:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  13009:             $upload_output.='<td align="right">'.
                   13010:                             '<span class="LC_info LC_fontsize_medium">'.
                   13011:                             &mt("URL points to web address").'</span>';
1.987     raeburn  13012:             $numremref++;
1.660     raeburn  13013:         } elsif ($args->{'error_on_invalid_names'}
                   13014:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  13015:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   13016:                             &mt('Invalid characters').'</span>';
1.987     raeburn  13017:             $numinvalid++;
1.660     raeburn  13018:         } else {
1.1123    raeburn  13019:             $upload_output .= '<td>'.
                   13020:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  13021:                                                      $embed_file,\%mapping,
1.1071    raeburn  13022:                                                      $allfiles,$codebase,'upload');
                   13023:             $counter ++;
                   13024:             $numnew ++;
1.987     raeburn  13025:         }
                   13026:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   13027:     }
                   13028:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  13029:         if ($actionurl eq '/adm/dependencies') {
                   13030:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   13031:             $modify_output .= &start_data_table_row().
                   13032:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   13033:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   13034:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   13035:                               '<td>'.$size.'</td>'.
                   13036:                               '<td>'.$mtime.'</td>'.
                   13037:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   13038:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   13039:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   13040:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   13041:                               &embedded_file_element('upload_embedded',$counter,
                   13042:                                                      $embed_file,\%mapping,
                   13043:                                                      $allfiles,$codebase,'modify').
                   13044:                               '</div></td>'.
                   13045:                               &end_data_table_row()."\n";
                   13046:             $counter ++;
                   13047:         } else {
                   13048:             $upload_output .= &start_data_table_row().
1.1123    raeburn  13049:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   13050:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   13051:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  13052:                               &Apache::loncommon::end_data_table_row()."\n";
                   13053:         }
                   13054:     }
                   13055:     my $delidx = $counter;
                   13056:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   13057:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   13058:         $delete_output .= &start_data_table_row().
                   13059:                           '<td><img src="'.&icon($oldfile).'" />'.
                   13060:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   13061:                           '<td>'.$size.'</td>'.
                   13062:                           '<td>'.$mtime.'</td>'.
                   13063:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   13064:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   13065:                           &embedded_file_element('upload_embedded',$delidx,
                   13066:                                                  $oldfile,\%mapping,$allfiles,
                   13067:                                                  $codebase,'delete').'</td>'.
                   13068:                           &end_data_table_row()."\n"; 
                   13069:         $numunused ++;
                   13070:         $delidx ++;
1.987     raeburn  13071:     }
                   13072:     if ($upload_output) {
                   13073:         $upload_output = &start_data_table().
                   13074:                          $upload_output.
                   13075:                          &end_data_table()."\n";
                   13076:     }
1.1071    raeburn  13077:     if ($modify_output) {
                   13078:         $modify_output = &start_data_table().
                   13079:                          &start_data_table_header_row().
                   13080:                          '<th>'.&mt('File').'</th>'.
                   13081:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13082:                          '<th>'.&mt('Modified').'</th>'.
                   13083:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   13084:                          &end_data_table_header_row().
                   13085:                          $modify_output.
                   13086:                          &end_data_table()."\n";
                   13087:     }
                   13088:     if ($delete_output) {
                   13089:         $delete_output = &start_data_table().
                   13090:                          &start_data_table_header_row().
                   13091:                          '<th>'.&mt('File').'</th>'.
                   13092:                          '<th>'.&mt('Size (KB)').'</th>'.
                   13093:                          '<th>'.&mt('Modified').'</th>'.
                   13094:                          '<th>'.&mt('Delete?').'</th>'.
                   13095:                          &end_data_table_header_row().
                   13096:                          $delete_output.
                   13097:                          &end_data_table()."\n";
                   13098:     }
1.987     raeburn  13099:     my $applies = 0;
                   13100:     if ($numremref) {
                   13101:         $applies ++;
                   13102:     }
                   13103:     if ($numinvalid) {
                   13104:         $applies ++;
                   13105:     }
                   13106:     if ($numexisting) {
                   13107:         $applies ++;
                   13108:     }
1.1071    raeburn  13109:     if ($counter || $numunused) {
1.987     raeburn  13110:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   13111:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  13112:                   $state.'<h3>'.$heading.'</h3>'; 
                   13113:         if ($actionurl eq '/adm/dependencies') {
                   13114:             if ($numnew) {
                   13115:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   13116:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   13117:                            $upload_output.'<br />'."\n";
                   13118:             }
                   13119:             if ($numexisting) {
                   13120:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   13121:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   13122:                            $modify_output.'<br />'."\n";
                   13123:                            $buttontext = &mt('Save changes');
                   13124:             }
                   13125:             if ($numunused) {
                   13126:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   13127:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   13128:                            $delete_output.'<br />'."\n";
                   13129:                            $buttontext = &mt('Save changes');
                   13130:             }
                   13131:         } else {
                   13132:             $output .= $upload_output.'<br />'."\n";
                   13133:         }
                   13134:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   13135:                    $counter.'" />'."\n";
                   13136:         if ($actionurl eq '/adm/dependencies') { 
                   13137:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   13138:                        $numnew.'" />'."\n";
                   13139:         } elsif ($actionurl eq '') {
1.987     raeburn  13140:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   13141:         }
                   13142:     } elsif ($applies) {
                   13143:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   13144:         if ($applies > 1) {
                   13145:             $output .=  
1.1123    raeburn  13146:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  13147:             if ($numremref) {
                   13148:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   13149:             }
                   13150:             if ($numinvalid) {
                   13151:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   13152:             }
                   13153:             if ($numexisting) {
                   13154:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   13155:             }
                   13156:             $output .= '</ul><br />';
                   13157:         } elsif ($numremref) {
                   13158:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   13159:         } elsif ($numinvalid) {
                   13160:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   13161:         } elsif ($numexisting) {
                   13162:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   13163:         }
                   13164:         $output .= $upload_output.'<br />';
                   13165:     }
                   13166:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13167:     $chgcount = $counter;
1.987     raeburn  13168:     if (keys(%pathchanges) > 0) {
                   13169:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13170:             if ($counter) {
1.987     raeburn  13171:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13172:                                                   $embed_file,\%mapping,
1.1071    raeburn  13173:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13174:             } else {
                   13175:                 $pathchange_output .= 
                   13176:                     &start_data_table_row().
                   13177:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13178:                     $chgcount.'" checked="checked" /></td>'.
                   13179:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13180:                     '<td>'.$embed_file.
                   13181:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13182:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13183:                     '</td>'.&end_data_table_row();
1.660     raeburn  13184:             }
1.987     raeburn  13185:             $numpathchg ++;
                   13186:             $chgcount ++;
1.660     raeburn  13187:         }
                   13188:     }
1.1127    raeburn  13189:     if (($counter) || ($numunused)) {
1.987     raeburn  13190:         if ($numpathchg) {
                   13191:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13192:                        $numpathchg.'" />'."\n";
                   13193:         }
                   13194:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13195:             ($actionurl eq '/adm/imsimport')) {
                   13196:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13197:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13198:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13199:         } elsif ($actionurl eq '/adm/dependencies') {
                   13200:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13201:         }
1.1123    raeburn  13202:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13203:     } elsif ($numpathchg) {
                   13204:         my %pathchange = ();
                   13205:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13206:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13207:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13208:         }
1.987     raeburn  13209:     }
1.1071    raeburn  13210:     return ($output,$counter,$numpathchg);
1.987     raeburn  13211: }
                   13212: 
1.1147    raeburn  13213: =pod
                   13214: 
                   13215: =item * clean_path($name)
                   13216: 
                   13217: Performs clean-up of directories, subdirectories and filename in an
                   13218: embedded object, referenced in an HTML file which is being uploaded
                   13219: to a course or portfolio, where 
                   13220: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13221: checked.
                   13222: 
                   13223: Clean-up is similar to replacements in lonnet::clean_filename()
                   13224: except each / between sub-directory and next level is preserved.
                   13225: 
                   13226: =cut
                   13227: 
                   13228: sub clean_path {
                   13229:     my ($embed_file) = @_;
                   13230:     $embed_file =~s{^/+}{};
                   13231:     my @contents;
                   13232:     if ($embed_file =~ m{/}) {
                   13233:         @contents = split(/\//,$embed_file);
                   13234:     } else {
                   13235:         @contents = ($embed_file);
                   13236:     }
                   13237:     my $lastidx = scalar(@contents)-1;
                   13238:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13239:         $contents[$i]=~s{\\}{/}g;
                   13240:         $contents[$i]=~s/\s+/\_/g;
                   13241:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13242:         if ($i == $lastidx) {
                   13243:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13244:         }
                   13245:     }
                   13246:     if ($lastidx > 0) {
                   13247:         return join('/',@contents);
                   13248:     } else {
                   13249:         return $contents[0];
                   13250:     }
                   13251: }
                   13252: 
1.987     raeburn  13253: sub embedded_file_element {
1.1071    raeburn  13254:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13255:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13256:                    (ref($codebase) eq 'HASH'));
                   13257:     my $output;
1.1071    raeburn  13258:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13259:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13260:     }
                   13261:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13262:                &escape($embed_file).'" />';
                   13263:     unless (($context eq 'upload_embedded') && 
                   13264:             ($mapping->{$embed_file} eq $embed_file)) {
                   13265:         $output .='
                   13266:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13267:     }
                   13268:     my $attrib;
                   13269:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13270:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13271:     }
                   13272:     $output .=
                   13273:         "\n\t\t".
                   13274:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13275:         $attrib.'" />';
                   13276:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13277:         $output .=
                   13278:             "\n\t\t".
                   13279:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13280:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13281:     }
1.987     raeburn  13282:     return $output;
1.660     raeburn  13283: }
                   13284: 
1.1071    raeburn  13285: sub get_dependency_details {
                   13286:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13287:     my ($size,$mtime,$showsize,$showmtime);
                   13288:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13289:         if ($embed_file =~ m{/}) {
                   13290:             my ($path,$fname) = split(/\//,$embed_file);
                   13291:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13292:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13293:             }
                   13294:         } else {
                   13295:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13296:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13297:             }
                   13298:         }
                   13299:         $showsize = $size/1024.0;
                   13300:         $showsize = sprintf("%.1f",$showsize);
                   13301:         if ($mtime > 0) {
                   13302:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13303:         }
                   13304:     }
                   13305:     return ($showsize,$showmtime);
                   13306: }
                   13307: 
                   13308: sub ask_embedded_js {
                   13309:     return <<"END";
                   13310: <script type="text/javascript"">
                   13311: // <![CDATA[
                   13312: function toggleBrowse(counter) {
                   13313:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13314:     var fileid = document.getElementById('embedded_item_'+counter);
                   13315:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13316:     if (chkboxid.checked == true) {
                   13317:         uploaddivid.style.display='block';
                   13318:     } else {
                   13319:         uploaddivid.style.display='none';
                   13320:         fileid.value = '';
                   13321:     }
                   13322: }
                   13323: // ]]>
                   13324: </script>
                   13325: 
                   13326: END
                   13327: }
                   13328: 
1.661     raeburn  13329: sub upload_embedded {
                   13330:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13331:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13332:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13333:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13334:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13335:         my $orig_uploaded_filename =
                   13336:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13337:         foreach my $type ('orig','ref','attrib','codebase') {
                   13338:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13339:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13340:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13341:             }
                   13342:         }
1.661     raeburn  13343:         my ($path,$fname) =
                   13344:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13345:         # no path, whole string is fname
                   13346:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13347:         $fname = &Apache::lonnet::clean_filename($fname);
                   13348:         # See if there is anything left
                   13349:         next if ($fname eq '');
                   13350: 
                   13351:         # Check if file already exists as a file or directory.
                   13352:         my ($state,$msg);
                   13353:         if ($context eq 'portfolio') {
                   13354:             my $port_path = $dirpath;
                   13355:             if ($group ne '') {
                   13356:                 $port_path = "groups/$group/$port_path";
                   13357:             }
1.987     raeburn  13358:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13359:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13360:                                               $dir_root,$port_path,$disk_quota,
                   13361:                                               $current_disk_usage,$uname,$udom);
                   13362:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13363:                 || $state eq 'file_locked') {
1.661     raeburn  13364:                 $output .= $msg;
                   13365:                 next;
                   13366:             }
                   13367:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13368:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13369:             if ($state eq 'exists') {
                   13370:                 $output .= $msg;
                   13371:                 next;
                   13372:             }
                   13373:         }
                   13374:         # Check if extension is valid
                   13375:         if (($fname =~ /\.(\w+)$/) &&
                   13376:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13377:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13378:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13379:             next;
                   13380:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13381:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13382:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13383:             next;
                   13384:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13385:             $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  13386:             next;
                   13387:         }
                   13388:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13389:         my $subdir = $path;
                   13390:         $subdir =~ s{/+$}{};
1.661     raeburn  13391:         if ($context eq 'portfolio') {
1.984     raeburn  13392:             my $result;
                   13393:             if ($state eq 'existingfile') {
                   13394:                 $result=
                   13395:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13396:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13397:             } else {
1.984     raeburn  13398:                 $result=
                   13399:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13400:                                                     $dirpath.
1.1123    raeburn  13401:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13402:                 if ($result !~ m|^/uploaded/|) {
                   13403:                     $output .= '<span class="LC_error">'
                   13404:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13405:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13406:                                .'</span><br />';
                   13407:                     next;
                   13408:                 } else {
1.987     raeburn  13409:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13410:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13411:                 }
1.661     raeburn  13412:             }
1.1123    raeburn  13413:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13414:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13415:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13416:             my $result =
1.1126    raeburn  13417:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13418:             if ($result !~ m|^/uploaded/|) {
                   13419:                 $output .= '<span class="LC_error">'
                   13420:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13421:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13422:                            .'</span><br />';
                   13423:                     next;
                   13424:             } else {
                   13425:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13426:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13427:                 if ($context eq 'syllabus') {
                   13428:                     &Apache::lonnet::make_public_indefinitely($result);
                   13429:                 }
1.987     raeburn  13430:             }
1.661     raeburn  13431:         } else {
                   13432: # Save the file
                   13433:             my $target = $env{'form.embedded_item_'.$i};
                   13434:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13435:             my $dest = $fullpath.$fname;
                   13436:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13437:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13438:             my $count;
                   13439:             my $filepath = $dir_root;
1.1027    raeburn  13440:             foreach my $subdir (@parts) {
                   13441:                 $filepath .= "/$subdir";
                   13442:                 if (!-e $filepath) {
1.661     raeburn  13443:                     mkdir($filepath,0770);
                   13444:                 }
                   13445:             }
                   13446:             my $fh;
                   13447:             if (!open($fh,'>'.$dest)) {
                   13448:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13449:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13450:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13451:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13452:                            '</span><br />';
                   13453:             } else {
                   13454:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13455:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13456:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13457:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13458:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13459:                               '</span><br />';
                   13460:                 } else {
1.987     raeburn  13461:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13462:                                $url.'</span>').'<br />';
                   13463:                     unless ($context eq 'testbank') {
                   13464:                         $footer .= &mt('View embedded file: [_1]',
                   13465:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13466:                     }
                   13467:                 }
                   13468:                 close($fh);
                   13469:             }
                   13470:         }
                   13471:         if ($env{'form.embedded_ref_'.$i}) {
                   13472:             $pathchange{$i} = 1;
                   13473:         }
                   13474:     }
                   13475:     if ($output) {
                   13476:         $output = '<p>'.$output.'</p>';
                   13477:     }
                   13478:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13479:     $returnflag = 'ok';
1.1071    raeburn  13480:     my $numpathchgs = scalar(keys(%pathchange));
                   13481:     if ($numpathchgs > 0) {
1.987     raeburn  13482:         if ($context eq 'portfolio') {
                   13483:             $output .= '<p>'.&mt('or').'</p>';
                   13484:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13485:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13486:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13487:             $returnflag = 'modify_orightml';
                   13488:         }
                   13489:     }
1.1071    raeburn  13490:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13491: }
                   13492: 
                   13493: sub modify_html_form {
                   13494:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13495:     my $end = 0;
                   13496:     my $modifyform;
                   13497:     if ($context eq 'upload_embedded') {
                   13498:         return unless (ref($pathchange) eq 'HASH');
                   13499:         if ($env{'form.number_embedded_items'}) {
                   13500:             $end += $env{'form.number_embedded_items'};
                   13501:         }
                   13502:         if ($env{'form.number_pathchange_items'}) {
                   13503:             $end += $env{'form.number_pathchange_items'};
                   13504:         }
                   13505:         if ($end) {
                   13506:             for (my $i=0; $i<$end; $i++) {
                   13507:                 if ($i < $env{'form.number_embedded_items'}) {
                   13508:                     next unless($pathchange->{$i});
                   13509:                 }
                   13510:                 $modifyform .=
                   13511:                     &start_data_table_row().
                   13512:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13513:                     'checked="checked" /></td>'.
                   13514:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13515:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13516:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13517:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13518:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13519:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13520:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13521:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13522:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13523:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13524:                     &end_data_table_row();
1.1071    raeburn  13525:             }
1.987     raeburn  13526:         }
                   13527:     } else {
                   13528:         $modifyform = $pathchgtable;
                   13529:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13530:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13531:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13532:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13533:         }
                   13534:     }
                   13535:     if ($modifyform) {
1.1071    raeburn  13536:         if ($actionurl eq '/adm/dependencies') {
                   13537:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13538:         }
1.987     raeburn  13539:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13540:                '<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".
                   13541:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13542:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13543:                '</ol></p>'."\n".'<p>'.
                   13544:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13545:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13546:                &start_data_table()."\n".
                   13547:                &start_data_table_header_row().
                   13548:                '<th>'.&mt('Change?').'</th>'.
                   13549:                '<th>'.&mt('Current reference').'</th>'.
                   13550:                '<th>'.&mt('Required reference').'</th>'.
                   13551:                &end_data_table_header_row()."\n".
                   13552:                $modifyform.
                   13553:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13554:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13555:                '</form>'."\n";
                   13556:     }
                   13557:     return;
                   13558: }
                   13559: 
                   13560: sub modify_html_refs {
1.1123    raeburn  13561:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13562:     my $container;
                   13563:     if ($context eq 'portfolio') {
                   13564:         $container = $env{'form.container'};
                   13565:     } elsif ($context eq 'coursedoc') {
                   13566:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13567:     } elsif ($context eq 'manage_dependencies') {
                   13568:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13569:         $container = "/$container";
1.1123    raeburn  13570:     } elsif ($context eq 'syllabus') {
                   13571:         $container = $url;
1.987     raeburn  13572:     } else {
1.1027    raeburn  13573:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13574:     }
                   13575:     my (%allfiles,%codebase,$output,$content);
                   13576:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13577:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13578:         if (wantarray) {
                   13579:             return ('',0,0); 
                   13580:         } else {
                   13581:             return;
                   13582:         }
                   13583:     }
                   13584:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13585:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13586:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13587:             if (wantarray) {
                   13588:                 return ('',0,0);
                   13589:             } else {
                   13590:                 return;
                   13591:             }
                   13592:         } 
1.987     raeburn  13593:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13594:         if ($content eq '-1') {
                   13595:             if (wantarray) {
                   13596:                 return ('',0,0);
                   13597:             } else {
                   13598:                 return;
                   13599:             }
                   13600:         }
1.987     raeburn  13601:     } else {
1.1071    raeburn  13602:         unless ($container =~ /^\Q$dir_root\E/) {
                   13603:             if (wantarray) {
                   13604:                 return ('',0,0);
                   13605:             } else {
                   13606:                 return;
                   13607:             }
                   13608:         } 
1.1317    raeburn  13609:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13610:             $content = join('', <$fh>);
                   13611:             close($fh);
                   13612:         } else {
1.1071    raeburn  13613:             if (wantarray) {
                   13614:                 return ('',0,0);
                   13615:             } else {
                   13616:                 return;
                   13617:             }
1.987     raeburn  13618:         }
                   13619:     }
                   13620:     my ($count,$codebasecount) = (0,0);
                   13621:     my $mm = new File::MMagic;
                   13622:     my $mime_type = $mm->checktype_contents($content);
                   13623:     if ($mime_type eq 'text/html') {
                   13624:         my $parse_result = 
                   13625:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13626:                                                     \%codebase,\$content);
                   13627:         if ($parse_result eq 'ok') {
                   13628:             foreach my $i (@changes) {
                   13629:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13630:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13631:                 if ($allfiles{$ref}) {
                   13632:                     my $newname =  $orig;
                   13633:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13634:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13635:                     if ($attrib_regexp =~ /:/) {
                   13636:                         $attrib_regexp =~ s/\:/|/g;
                   13637:                     }
                   13638:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13639:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13640:                         $count += $numchg;
1.1123    raeburn  13641:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13642:                         delete($allfiles{$ref});
1.987     raeburn  13643:                     }
                   13644:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13645:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13646:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13647:                         $codebasecount ++;
                   13648:                     }
                   13649:                 }
                   13650:             }
1.1123    raeburn  13651:             my $skiprewrites;
1.987     raeburn  13652:             if ($count || $codebasecount) {
                   13653:                 my $saveresult;
1.1071    raeburn  13654:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13655:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13656:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13657:                     if ($url eq $container) {
                   13658:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13659:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13660:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13661:                                             $fname.'</span>').'</p>';
1.987     raeburn  13662:                     } else {
                   13663:                          $output = '<p class="LC_error">'.
                   13664:                                    &mt('Error: update failed for: [_1].',
                   13665:                                    '<span class="LC_filename">'.
                   13666:                                    $container.'</span>').'</p>';
                   13667:                     }
1.1123    raeburn  13668:                     if ($context eq 'syllabus') {
                   13669:                         unless ($saveresult eq 'ok') {
                   13670:                             $skiprewrites = 1;
                   13671:                         }
                   13672:                     }
1.987     raeburn  13673:                 } else {
1.1317    raeburn  13674:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13675:                         print $fh $content;
                   13676:                         close($fh);
                   13677:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13678:                                   $count,'<span class="LC_filename">'.
                   13679:                                   $container.'</span>').'</p>';
1.661     raeburn  13680:                     } else {
1.987     raeburn  13681:                          $output = '<p class="LC_error">'.
                   13682:                                    &mt('Error: could not update [_1].',
                   13683:                                    '<span class="LC_filename">'.
                   13684:                                    $container.'</span>').'</p>';
1.661     raeburn  13685:                     }
                   13686:                 }
                   13687:             }
1.1123    raeburn  13688:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13689:                 my ($actionurl,$state);
                   13690:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13691:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13692:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13693:                                               \%codebase,
                   13694:                                               {'context' => 'rewrites',
                   13695:                                                'ignore_remote_references' => 1,});
                   13696:                 if (ref($mapping) eq 'HASH') {
                   13697:                     my $rewrites = 0;
                   13698:                     foreach my $key (keys(%{$mapping})) {
                   13699:                         next if ($key =~ m{^https?://});
                   13700:                         my $ref = $mapping->{$key};
                   13701:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13702:                         my $attrib;
                   13703:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13704:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13705:                         }
                   13706:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13707:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13708:                             $rewrites += $numchg;
                   13709:                         }
                   13710:                     }
                   13711:                     if ($rewrites) {
                   13712:                         my $saveresult; 
                   13713:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13714:                         if ($url eq $container) {
                   13715:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13716:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13717:                                             $count,'<span class="LC_filename">'.
                   13718:                                             $fname.'</span>').'</p>';
                   13719:                         } else {
                   13720:                             $output .= '<p class="LC_error">'.
                   13721:                                        &mt('Error: could not update links in [_1].',
                   13722:                                        '<span class="LC_filename">'.
                   13723:                                        $container.'</span>').'</p>';
                   13724: 
                   13725:                         }
                   13726:                     }
                   13727:                 }
                   13728:             }
1.987     raeburn  13729:         } else {
                   13730:             &logthis('Failed to parse '.$container.
                   13731:                      ' to modify references: '.$parse_result);
1.661     raeburn  13732:         }
                   13733:     }
1.1071    raeburn  13734:     if (wantarray) {
                   13735:         return ($output,$count,$codebasecount);
                   13736:     } else {
                   13737:         return $output;
                   13738:     }
1.661     raeburn  13739: }
                   13740: 
                   13741: sub check_for_existing {
                   13742:     my ($path,$fname,$element) = @_;
                   13743:     my ($state,$msg);
                   13744:     if (-d $path.'/'.$fname) {
                   13745:         $state = 'exists';
                   13746:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13747:     } elsif (-e $path.'/'.$fname) {
                   13748:         $state = 'exists';
                   13749:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13750:     }
                   13751:     if ($state eq 'exists') {
                   13752:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13753:     }
                   13754:     return ($state,$msg);
                   13755: }
                   13756: 
                   13757: sub check_for_upload {
                   13758:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13759:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13760:     my $filesize = length($env{'form.'.$element});
                   13761:     if (!$filesize) {
                   13762:         my $msg = '<span class="LC_error">'.
                   13763:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13764:                       '<span class="LC_filename">'.$fname.'</span>',
                   13765:                       $filesize).'<br />'.
1.1007    raeburn  13766:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13767:                   '</span>';
                   13768:         return ('zero_bytes',$msg);
                   13769:     }
                   13770:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13771:     my $getpropath = 1;
1.1021    raeburn  13772:     my ($dirlistref,$listerror) =
                   13773:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13774:     my $found_file = 0;
                   13775:     my $locked_file = 0;
1.991     raeburn  13776:     my @lockers;
                   13777:     my $navmap;
                   13778:     if ($env{'request.course.id'}) {
                   13779:         $navmap = Apache::lonnavmaps::navmap->new();
                   13780:     }
1.1021    raeburn  13781:     if (ref($dirlistref) eq 'ARRAY') {
                   13782:         foreach my $line (@{$dirlistref}) {
                   13783:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13784:             if ($file_name eq $fname){
                   13785:                 $file_name = $path.$file_name;
                   13786:                 if ($group ne '') {
                   13787:                     $file_name = $group.$file_name;
                   13788:                 }
                   13789:                 $found_file = 1;
                   13790:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13791:                     foreach my $lock (@lockers) {
                   13792:                         if (ref($lock) eq 'ARRAY') {
                   13793:                             my ($symb,$crsid) = @{$lock};
                   13794:                             if ($crsid eq $env{'request.course.id'}) {
                   13795:                                 if (ref($navmap)) {
                   13796:                                     my $res = $navmap->getBySymb($symb);
                   13797:                                     foreach my $part (@{$res->parts()}) { 
                   13798:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13799:                                         unless (($slot_status == $res->RESERVED) ||
                   13800:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13801:                                             $locked_file = 1;
                   13802:                                         }
1.991     raeburn  13803:                                     }
1.1021    raeburn  13804:                                 } else {
                   13805:                                     $locked_file = 1;
1.991     raeburn  13806:                                 }
                   13807:                             } else {
                   13808:                                 $locked_file = 1;
                   13809:                             }
                   13810:                         }
1.1021    raeburn  13811:                    }
                   13812:                 } else {
                   13813:                     my @info = split(/\&/,$rest);
                   13814:                     my $currsize = $info[6]/1000;
                   13815:                     if ($currsize < $filesize) {
                   13816:                         my $extra = $filesize - $currsize;
                   13817:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13818:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13819:                                       &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   13820:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13821:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13822:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13823:                             return ('will_exceed_quota',$msg);
                   13824:                         }
1.984     raeburn  13825:                     }
                   13826:                 }
1.661     raeburn  13827:             }
                   13828:         }
                   13829:     }
                   13830:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13831:         my $msg = '<p class="LC_warning">'.
                   13832:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13833:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13834:         return ('will_exceed_quota',$msg);
                   13835:     } elsif ($found_file) {
                   13836:         if ($locked_file) {
1.1179    bisitz   13837:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13838:             $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   13839:             $msg .= '</p>';
1.661     raeburn  13840:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13841:             return ('file_locked',$msg);
                   13842:         } else {
1.1179    bisitz   13843:             my $msg = '<p class="LC_error">';
1.984     raeburn  13844:             $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   13845:             $msg .= '</p>';
1.984     raeburn  13846:             return ('existingfile',$msg);
1.661     raeburn  13847:         }
                   13848:     }
                   13849: }
                   13850: 
1.987     raeburn  13851: sub check_for_traversal {
                   13852:     my ($path,$url,$toplevel) = @_;
                   13853:     my @parts=split(/\//,$path);
                   13854:     my $cleanpath;
                   13855:     my $fullpath = $url;
                   13856:     for (my $i=0;$i<@parts;$i++) {
                   13857:         next if ($parts[$i] eq '.');
                   13858:         if ($parts[$i] eq '..') {
                   13859:             $fullpath =~ s{([^/]+/)$}{};
                   13860:         } else {
                   13861:             $fullpath .= $parts[$i].'/';
                   13862:         }
                   13863:     }
                   13864:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13865:         $cleanpath = $1;
                   13866:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13867:         my $curr_toprel = $1;
                   13868:         my @parts = split(/\//,$curr_toprel);
                   13869:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13870:         my @urlparts = split(/\//,$url_toprel);
                   13871:         my $doubledots;
                   13872:         my $startdiff = -1;
                   13873:         for (my $i=0; $i<@urlparts; $i++) {
                   13874:             if ($startdiff == -1) {
                   13875:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13876:                     $startdiff = $i;
                   13877:                     $doubledots .= '../';
                   13878:                 }
                   13879:             } else {
                   13880:                 $doubledots .= '../';
                   13881:             }
                   13882:         }
                   13883:         if ($startdiff > -1) {
                   13884:             $cleanpath = $doubledots;
                   13885:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13886:                 $cleanpath .= $parts[$i].'/';
                   13887:             }
                   13888:         }
                   13889:     }
                   13890:     $cleanpath =~ s{(/)$}{};
                   13891:     return $cleanpath;
                   13892: }
1.31      albertel 13893: 
1.1053    raeburn  13894: sub is_archive_file {
                   13895:     my ($mimetype) = @_;
                   13896:     if (($mimetype eq 'application/octet-stream') ||
                   13897:         ($mimetype eq 'application/x-stuffit') ||
                   13898:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13899:         return 1;
                   13900:     }
                   13901:     return;
                   13902: }
                   13903: 
                   13904: sub decompress_form {
1.1065    raeburn  13905:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13906:     my %lt = &Apache::lonlocal::texthash (
                   13907:         this => 'This file is an archive file.',
1.1067    raeburn  13908:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13909:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13910:         youm => 'You may wish to extract its contents.',
                   13911:         extr => 'Extract contents',
1.1067    raeburn  13912:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13913:         proa => 'Process automatically?',
1.1053    raeburn  13914:         yes  => 'Yes',
                   13915:         no   => 'No',
1.1067    raeburn  13916:         fold => 'Title for folder containing movie',
                   13917:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13918:     );
1.1065    raeburn  13919:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13920:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13921:     my $info = &list_archive_contents($fileloc,\@paths);
                   13922:     if (@paths) {
                   13923:         foreach my $path (@paths) {
                   13924:             $path =~ s{^/}{};
1.1067    raeburn  13925:             if ($path =~ m{^([^/]+)/$}) {
                   13926:                 $topdir = $1;
                   13927:             }
1.1065    raeburn  13928:             if ($path =~ m{^([^/]+)/}) {
                   13929:                 $toplevel{$1} = $path;
                   13930:             } else {
                   13931:                 $toplevel{$path} = $path;
                   13932:             }
                   13933:         }
                   13934:     }
1.1067    raeburn  13935:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13936:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13937:                         "$topdir/media/",
                   13938:                         "$topdir/media/$topdir.mp4",
                   13939:                         "$topdir/media/FirstFrame.png",
                   13940:                         "$topdir/media/player.swf",
                   13941:                         "$topdir/media/swfobject.js",
                   13942:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13943:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13944:                          "$topdir/$topdir.mp4",
                   13945:                          "$topdir/$topdir\_config.xml",
                   13946:                          "$topdir/$topdir\_controller.swf",
                   13947:                          "$topdir/$topdir\_embed.css",
                   13948:                          "$topdir/$topdir\_First_Frame.png",
                   13949:                          "$topdir/$topdir\_player.html",
                   13950:                          "$topdir/$topdir\_Thumbnails.png",
                   13951:                          "$topdir/playerProductInstall.swf",
                   13952:                          "$topdir/scripts/",
                   13953:                          "$topdir/scripts/config_xml.js",
                   13954:                          "$topdir/scripts/handlebars.js",
                   13955:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13956:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13957:                          "$topdir/scripts/modernizr.js",
                   13958:                          "$topdir/scripts/player-min.js",
                   13959:                          "$topdir/scripts/swfobject.js",
                   13960:                          "$topdir/skins/",
                   13961:                          "$topdir/skins/configuration_express.xml",
                   13962:                          "$topdir/skins/express_show/",
                   13963:                          "$topdir/skins/express_show/player-min.css",
                   13964:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13965:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13966:                          "$topdir/$topdir.mp4",
                   13967:                          "$topdir/$topdir\_config.xml",
                   13968:                          "$topdir/$topdir\_controller.swf",
                   13969:                          "$topdir/$topdir\_embed.css",
                   13970:                          "$topdir/$topdir\_First_Frame.png",
                   13971:                          "$topdir/$topdir\_player.html",
                   13972:                          "$topdir/$topdir\_Thumbnails.png",
                   13973:                          "$topdir/playerProductInstall.swf",
                   13974:                          "$topdir/scripts/",
                   13975:                          "$topdir/scripts/config_xml.js",
                   13976:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13977:                          "$topdir/skins/",
                   13978:                          "$topdir/skins/configuration_express.xml",
                   13979:                          "$topdir/skins/express_show/",
                   13980:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13981:                          "$topdir/skins/express_show/spritesheet.png",
                   13982:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13983:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13984:         if (@diffs == 0) {
1.1164    raeburn  13985:             $is_camtasia = 6;
                   13986:         } else {
1.1197    raeburn  13987:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13988:             if (@diffs == 0) {
                   13989:                 $is_camtasia = 8;
1.1197    raeburn  13990:             } else {
                   13991:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13992:                 if (@diffs == 0) {
                   13993:                     $is_camtasia = 8;
                   13994:                 }
1.1164    raeburn  13995:             }
1.1067    raeburn  13996:         }
                   13997:     }
                   13998:     my $output;
                   13999:     if ($is_camtasia) {
                   14000:         $output = <<"ENDCAM";
                   14001: <script type="text/javascript" language="Javascript">
                   14002: // <![CDATA[
                   14003: 
                   14004: function camtasiaToggle() {
                   14005:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   14006:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  14007:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  14008:                 document.getElementById('camtasia_titles').style.display='block';
                   14009:             } else {
                   14010:                 document.getElementById('camtasia_titles').style.display='none';
                   14011:             }
                   14012:         }
                   14013:     }
                   14014:     return;
                   14015: }
                   14016: 
                   14017: // ]]>
                   14018: </script>
                   14019: <p>$lt{'camt'}</p>
                   14020: ENDCAM
1.1065    raeburn  14021:     } else {
1.1067    raeburn  14022:         $output = '<p>'.$lt{'this'};
                   14023:         if ($info eq '') {
                   14024:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   14025:         } else {
                   14026:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   14027:                        '<div><pre>'.$info.'</pre></div>';
                   14028:         }
1.1065    raeburn  14029:     }
1.1067    raeburn  14030:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  14031:     my $duplicates;
                   14032:     my $num = 0;
                   14033:     if (ref($dirlist) eq 'ARRAY') {
                   14034:         foreach my $item (@{$dirlist}) {
                   14035:             if (ref($item) eq 'ARRAY') {
                   14036:                 if (exists($toplevel{$item->[0]})) {
                   14037:                     $duplicates .= 
                   14038:                         &start_data_table_row().
                   14039:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14040:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   14041:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   14042:                         'value="1" />'.&mt('Yes').'</label>'.
                   14043:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   14044:                         '<td>'.$item->[0].'</td>';
                   14045:                     if ($item->[2]) {
                   14046:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   14047:                     } else {
                   14048:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   14049:                     }
                   14050:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   14051:                                    '<td>'.
                   14052:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   14053:                                    '</td>'.
                   14054:                                    &end_data_table_row();
                   14055:                     $num ++;
                   14056:                 }
                   14057:             }
                   14058:         }
                   14059:     }
                   14060:     my $itemcount;
                   14061:     if (@paths > 0) {
                   14062:         $itemcount = scalar(@paths);
                   14063:     } else {
                   14064:         $itemcount = 1;
                   14065:     }
1.1067    raeburn  14066:     if ($is_camtasia) {
                   14067:         $output .= $lt{'auto'}.'<br />'.
                   14068:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  14069:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  14070:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   14071:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   14072:                    $lt{'no'}.'</label></span><br />'.
                   14073:                    '<div id="camtasia_titles" style="display:block">'.
                   14074:                    &Apache::lonhtmlcommon::start_pick_box().
                   14075:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   14076:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   14077:                    &Apache::lonhtmlcommon::row_closure().
                   14078:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   14079:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   14080:                    &Apache::lonhtmlcommon::row_closure(1).
                   14081:                    &Apache::lonhtmlcommon::end_pick_box().
                   14082:                    '</div>';
                   14083:     }
1.1065    raeburn  14084:     $output .= 
                   14085:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  14086:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   14087:         "\n";
1.1065    raeburn  14088:     if ($duplicates ne '') {
                   14089:         $output .= '<p><span class="LC_warning">'.
                   14090:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   14091:                    &start_data_table().
                   14092:                    &start_data_table_header_row().
                   14093:                    '<th>'.&mt('Overwrite?').'</th>'.
                   14094:                    '<th>'.&mt('Name').'</th>'.
                   14095:                    '<th>'.&mt('Type').'</th>'.
                   14096:                    '<th>'.&mt('Size').'</th>'.
                   14097:                    '<th>'.&mt('Last modified').'</th>'.
                   14098:                    &end_data_table_header_row().
                   14099:                    $duplicates.
                   14100:                    &end_data_table().
                   14101:                    '</p>';
                   14102:     }
1.1067    raeburn  14103:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  14104:     if (ref($hiddenelements) eq 'HASH') {
                   14105:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   14106:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   14107:         }
                   14108:     }
                   14109:     $output .= <<"END";
1.1067    raeburn  14110: <br />
1.1053    raeburn  14111: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   14112: </form>
                   14113: $noextract
                   14114: END
                   14115:     return $output;
                   14116: }
                   14117: 
1.1065    raeburn  14118: sub decompression_utility {
                   14119:     my ($program) = @_;
                   14120:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   14121:     my $location;
                   14122:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   14123:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   14124:                          '/usr/sbin/') {
                   14125:             if (-x $dir.$program) {
                   14126:                 $location = $dir.$program;
                   14127:                 last;
                   14128:             }
                   14129:         }
                   14130:     }
                   14131:     return $location;
                   14132: }
                   14133: 
                   14134: sub list_archive_contents {
                   14135:     my ($file,$pathsref) = @_;
                   14136:     my (@cmd,$output);
                   14137:     my $needsregexp;
                   14138:     if ($file =~ /\.zip$/) {
                   14139:         @cmd = (&decompression_utility('unzip'),"-l");
                   14140:         $needsregexp = 1;
                   14141:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   14142:              ($file =~ /\.tgz$/)) {
                   14143:         @cmd = (&decompression_utility('tar'),"-ztf");
                   14144:     } elsif ($file =~ /\.tar\.bz2$/) {
                   14145:         @cmd = (&decompression_utility('tar'),"-jtf");
                   14146:     } elsif ($file =~ m|\.tar$|) {
                   14147:         @cmd = (&decompression_utility('tar'),"-tf");
                   14148:     }
                   14149:     if (@cmd) {
                   14150:         undef($!);
                   14151:         undef($@);
                   14152:         if (open(my $fh,"-|", @cmd, $file)) {
                   14153:             while (my $line = <$fh>) {
                   14154:                 $output .= $line;
                   14155:                 chomp($line);
                   14156:                 my $item;
                   14157:                 if ($needsregexp) {
                   14158:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   14159:                 } else {
                   14160:                     $item = $line;
                   14161:                 }
                   14162:                 if ($item ne '') {
                   14163:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14164:                         push(@{$pathsref},$item);
                   14165:                     } 
                   14166:                 }
                   14167:             }
                   14168:             close($fh);
                   14169:         }
                   14170:     }
                   14171:     return $output;
                   14172: }
                   14173: 
1.1053    raeburn  14174: sub decompress_uploaded_file {
                   14175:     my ($file,$dir) = @_;
                   14176:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14177:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14178:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14179:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14180:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14181:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14182:     my $decompressed = $env{'cgi.decompressed'};
                   14183:     &Apache::lonnet::delenv('cgi.file');
                   14184:     &Apache::lonnet::delenv('cgi.dir');
                   14185:     &Apache::lonnet::delenv('cgi.decompressed');
                   14186:     return ($decompressed,$result);
                   14187: }
                   14188: 
1.1055    raeburn  14189: sub process_decompression {
                   14190:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14191:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14192:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14193:                &mt('Unexpected file path.').'</p>'."\n";
                   14194:     }
                   14195:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14196:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14197:                &mt('Unexpected course context.').'</p>'."\n";
                   14198:     }
1.1293    raeburn  14199:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14200:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14201:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14202:     }
1.1055    raeburn  14203:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14204:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14205:         $error = &mt('Filename not a supported archive file type.').
                   14206:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14207:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14208:     } else {
                   14209:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14210:         if ($docuhome eq 'no_host') {
                   14211:             $error = &mt('Could not determine home server for course.');
                   14212:         } else {
                   14213:             my @ids=&Apache::lonnet::current_machine_ids();
                   14214:             my $currdir = "$dir_root/$destination";
                   14215:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14216:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14217:                        "$dir_root/$destination";
                   14218:             } else {
                   14219:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14220:                        "$dir_root/$docudom/$docuname/$destination";
                   14221:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14222:                     $error = &mt('Archive file not found.');
                   14223:                 }
                   14224:             }
1.1065    raeburn  14225:             my (@to_overwrite,@to_skip);
                   14226:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14227:                 my $total = $env{'form.archive_overwrite_total'};
                   14228:                 for (my $i=0; $i<$total; $i++) {
                   14229:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14230:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14231:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14232:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14233:                     }
                   14234:                 }
                   14235:             }
                   14236:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14237:             my $numoverwrite = scalar(@to_overwrite);
                   14238:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14239:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14240:             } elsif ($dir eq '') {
1.1055    raeburn  14241:                 $error = &mt('Directory containing archive file unavailable.');
                   14242:             } elsif (!$error) {
1.1065    raeburn  14243:                 my ($decompressed,$display);
1.1292    raeburn  14244:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14245:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14246:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14247:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14248:                         ($decompressed,$display) = 
                   14249:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14250:                         foreach my $item (@to_skip) {
                   14251:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14252:                                 if (-f "$dir/$tempdir/$item") { 
                   14253:                                     unlink("$dir/$tempdir/$item");
                   14254:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14255:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14256:                                 }
                   14257:                             }
                   14258:                         }
                   14259:                         foreach my $item (@to_overwrite) {
                   14260:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14261:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14262:                                     if (-f "$dir/$item") {
                   14263:                                         unlink("$dir/$item");
                   14264:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14265:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14266:                                     }
                   14267:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14268:                                 }
1.1065    raeburn  14269:                             }
                   14270:                         }
1.1292    raeburn  14271:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14272:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14273:                         }
1.1065    raeburn  14274:                     }
                   14275:                 } else {
                   14276:                     ($decompressed,$display) = 
                   14277:                         &decompress_uploaded_file($file,$dir);
                   14278:                 }
1.1055    raeburn  14279:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14280:                     $output = '<p class="LC_info">'.
                   14281:                               &mt('Files extracted successfully from archive.').
                   14282:                               '</p>'."\n";
1.1055    raeburn  14283:                     my ($warning,$result,@contents);
                   14284:                     my ($newdirlistref,$newlisterror) =
                   14285:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14286:                                                  $docuname,1);
                   14287:                     my (%is_dir,%changes,@newitems);
                   14288:                     my $dirptr = 16384;
1.1065    raeburn  14289:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14290:                         foreach my $dir_line (@{$newdirlistref}) {
                   14291:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14292:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14293:                                 push(@newitems,$item);
                   14294:                                 if ($dirptr&$testdir) {
                   14295:                                     $is_dir{$item} = 1;
                   14296:                                 }
                   14297:                                 $changes{$item} = 1;
                   14298:                             }
                   14299:                         }
                   14300:                     }
                   14301:                     if (keys(%changes) > 0) {
                   14302:                         foreach my $item (sort(@newitems)) {
                   14303:                             if ($changes{$item}) {
                   14304:                                 push(@contents,$item);
                   14305:                             }
                   14306:                         }
                   14307:                     }
                   14308:                     if (@contents > 0) {
1.1067    raeburn  14309:                         my $wantform;
                   14310:                         unless ($env{'form.autoextract_camtasia'}) {
                   14311:                             $wantform = 1;
                   14312:                         }
1.1056    raeburn  14313:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14314:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14315:                                                                 $currdir,\%is_dir,
                   14316:                                                                 \%children,\%parent,
1.1056    raeburn  14317:                                                                 \@contents,\%dirorder,
                   14318:                                                                 \%titles,$wantform);
1.1055    raeburn  14319:                         if ($datatable ne '') {
                   14320:                             $output .= &archive_options_form('decompressed',$datatable,
                   14321:                                                              $count,$hiddenelem);
1.1065    raeburn  14322:                             my $startcount = 6;
1.1055    raeburn  14323:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14324:                                                            \%titles,\%children);
1.1055    raeburn  14325:                         }
1.1067    raeburn  14326:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14327:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14328:                             my %displayed;
                   14329:                             my $total = 1;
                   14330:                             $env{'form.archive_directory'} = [];
                   14331:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14332:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14333:                                 $path =~ s{/$}{};
                   14334:                                 my $item;
                   14335:                                 if ($path ne '') {
                   14336:                                     $item = "$path/$titles{$i}";
                   14337:                                 } else {
                   14338:                                     $item = $titles{$i};
                   14339:                                 }
                   14340:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14341:                                 if ($item eq $contents[0]) {
                   14342:                                     push(@{$env{'form.archive_directory'}},$i);
                   14343:                                     $env{'form.archive_'.$i} = 'display';
                   14344:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14345:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14346:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14347:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14348:                                     $env{'form.archive_'.$i} = 'display';
                   14349:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14350:                                     $displayed{'web'} = $i;
                   14351:                                 } else {
1.1164    raeburn  14352:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14353:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14354:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14355:                                         push(@{$env{'form.archive_directory'}},$i);
                   14356:                                     }
                   14357:                                     $env{'form.archive_'.$i} = 'dependency';
                   14358:                                 }
                   14359:                                 $total ++;
                   14360:                             }
                   14361:                             for (my $i=1; $i<$total; $i++) {
                   14362:                                 next if ($i == $displayed{'web'});
                   14363:                                 next if ($i == $displayed{'folder'});
                   14364:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14365:                             }
                   14366:                             $env{'form.phase'} = 'decompress_cleanup';
                   14367:                             $env{'form.archivedelete'} = 1;
                   14368:                             $env{'form.archive_count'} = $total-1;
                   14369:                             $output .=
                   14370:                                 &process_extracted_files('coursedocs',$docudom,
                   14371:                                                          $docuname,$destination,
                   14372:                                                          $dir_root,$hiddenelem);
                   14373:                         }
1.1055    raeburn  14374:                     } else {
                   14375:                         $warning = &mt('No new items extracted from archive file.');
                   14376:                     }
                   14377:                 } else {
                   14378:                     $output = $display;
                   14379:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14380:                 }
                   14381:             }
                   14382:         }
                   14383:     }
                   14384:     if ($error) {
                   14385:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14386:                    $error.'</p>'."\n";
                   14387:     }
                   14388:     if ($warning) {
                   14389:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14390:     }
                   14391:     return $output;
                   14392: }
                   14393: 
                   14394: sub get_extracted {
1.1056    raeburn  14395:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14396:         $titles,$wantform) = @_;
1.1055    raeburn  14397:     my $count = 0;
                   14398:     my $depth = 0;
                   14399:     my $datatable;
1.1056    raeburn  14400:     my @hierarchy;
1.1055    raeburn  14401:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14402:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14403:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14404:     foreach my $item (@{$contents}) {
                   14405:         $count ++;
1.1056    raeburn  14406:         @{$dirorder->{$count}} = @hierarchy;
                   14407:         $titles->{$count} = $item;
1.1055    raeburn  14408:         &archive_hierarchy($depth,$count,$parent,$children);
                   14409:         if ($wantform) {
                   14410:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14411:                                        $currdir,$depth,$count);
                   14412:         }
                   14413:         if ($is_dir->{$item}) {
                   14414:             $depth ++;
1.1056    raeburn  14415:             push(@hierarchy,$count);
                   14416:             $parent->{$depth} = $count;
1.1055    raeburn  14417:             $datatable .=
                   14418:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14419:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14420:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14421:             $depth --;
1.1056    raeburn  14422:             pop(@hierarchy);
1.1055    raeburn  14423:         }
                   14424:     }
                   14425:     return ($count,$datatable);
                   14426: }
                   14427: 
                   14428: sub recurse_extracted_archive {
1.1056    raeburn  14429:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14430:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14431:     my $result='';
1.1056    raeburn  14432:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14433:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14434:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14435:         return $result;
                   14436:     }
                   14437:     my $dirptr = 16384;
                   14438:     my ($newdirlistref,$newlisterror) =
                   14439:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14440:     if (ref($newdirlistref) eq 'ARRAY') {
                   14441:         foreach my $dir_line (@{$newdirlistref}) {
                   14442:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14443:             unless ($item =~ /^\.+$/) {
                   14444:                 $$count ++;
1.1056    raeburn  14445:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14446:                 $titles->{$$count} = $item;
1.1055    raeburn  14447:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14448: 
1.1055    raeburn  14449:                 my $is_dir;
                   14450:                 if ($dirptr&$testdir) {
                   14451:                     $is_dir = 1;
                   14452:                 }
                   14453:                 if ($wantform) {
                   14454:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14455:                 }
                   14456:                 if ($is_dir) {
                   14457:                     $$depth ++;
1.1056    raeburn  14458:                     push(@{$hierarchy},$$count);
                   14459:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14460:                     $result .=
                   14461:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14462:                                                    $docuname,$depth,$count,
1.1056    raeburn  14463:                                                    $hierarchy,$dirorder,$children,
                   14464:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14465:                     $$depth --;
1.1056    raeburn  14466:                     pop(@{$hierarchy});
1.1055    raeburn  14467:                 }
                   14468:             }
                   14469:         }
                   14470:     }
                   14471:     return $result;
                   14472: }
                   14473: 
                   14474: sub archive_hierarchy {
                   14475:     my ($depth,$count,$parent,$children) =@_;
                   14476:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14477:         if (exists($parent->{$depth})) {
                   14478:              $children->{$parent->{$depth}} .= $count.':';
                   14479:         }
                   14480:     }
                   14481:     return;
                   14482: }
                   14483: 
                   14484: sub archive_row {
                   14485:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14486:     my ($name) = ($item =~ m{([^/]+)$});
                   14487:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14488:                                        'display'    => 'Add as file',
1.1055    raeburn  14489:                                        'dependency' => 'Include as dependency',
                   14490:                                        'discard'    => 'Discard',
                   14491:                                       );
                   14492:     if ($is_dir) {
1.1059    raeburn  14493:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14494:     }
1.1056    raeburn  14495:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14496:     my $offset = 0;
1.1055    raeburn  14497:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14498:         $offset ++;
1.1065    raeburn  14499:         if ($action ne 'display') {
                   14500:             $offset ++;
                   14501:         }  
1.1055    raeburn  14502:         $output .= '<td><span class="LC_nobreak">'.
                   14503:                    '<label><input type="radio" name="archive_'.$count.
                   14504:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14505:         my $text = $choices{$action};
                   14506:         if ($is_dir) {
                   14507:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14508:             if ($action eq 'display') {
1.1059    raeburn  14509:                 $text = &mt('Add as folder');
1.1055    raeburn  14510:             }
1.1056    raeburn  14511:         } else {
                   14512:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14513: 
                   14514:         }
                   14515:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14516:         if ($action eq 'dependency') {
                   14517:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14518:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14519:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14520:                        '<option value=""></option>'."\n".
                   14521:                        '</select>'."\n".
                   14522:                        '</div>';
1.1059    raeburn  14523:         } elsif ($action eq 'display') {
                   14524:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14525:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14526:                        '</div>';
1.1055    raeburn  14527:         }
1.1056    raeburn  14528:         $output .= '</td>';
1.1055    raeburn  14529:     }
                   14530:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14531:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14532:     for (my $i=0; $i<$depth; $i++) {
                   14533:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14534:     }
                   14535:     if ($is_dir) {
                   14536:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14537:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14538:     } else {
                   14539:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14540:     }
                   14541:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14542:                &end_data_table_row();
                   14543:     return $output;
                   14544: }
                   14545: 
                   14546: sub archive_options_form {
1.1065    raeburn  14547:     my ($form,$display,$count,$hiddenelem) = @_;
                   14548:     my %lt = &Apache::lonlocal::texthash(
                   14549:                perm => 'Permanently remove archive file?',
                   14550:                hows => 'How should each extracted item be incorporated in the course?',
                   14551:                cont => 'Content actions for all',
                   14552:                addf => 'Add as folder/file',
                   14553:                incd => 'Include as dependency for a displayed file',
                   14554:                disc => 'Discard',
                   14555:                no   => 'No',
                   14556:                yes  => 'Yes',
                   14557:                save => 'Save',
                   14558:     );
                   14559:     my $output = <<"END";
                   14560: <form name="$form" method="post" action="">
                   14561: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14562: <label>
                   14563:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14564: </label>
                   14565: &nbsp;
                   14566: <label>
                   14567:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14568: </span>
                   14569: </p>
                   14570: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14571: <br />$lt{'hows'}
                   14572: <div class="LC_columnSection">
                   14573:   <fieldset>
                   14574:     <legend>$lt{'cont'}</legend>
                   14575:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14576:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14577:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14578:   </fieldset>
                   14579: </div>
                   14580: END
                   14581:     return $output.
1.1055    raeburn  14582:            &start_data_table()."\n".
1.1065    raeburn  14583:            $display."\n".
1.1055    raeburn  14584:            &end_data_table()."\n".
                   14585:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14586:            $hiddenelem.
1.1065    raeburn  14587:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14588:            '</form>';
                   14589: }
                   14590: 
                   14591: sub archive_javascript {
1.1056    raeburn  14592:     my ($startcount,$numitems,$titles,$children) = @_;
                   14593:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14594:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14595:     my $scripttag = <<START;
                   14596: <script type="text/javascript">
                   14597: // <![CDATA[
                   14598: 
                   14599: function checkAll(form,prefix) {
                   14600:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14601:     for (var i=0; i < form.elements.length; i++) {
                   14602:         var id = form.elements[i].id;
                   14603:         if ((id != '') && (id != undefined)) {
                   14604:             if (idstr.test(id)) {
                   14605:                 if (form.elements[i].type == 'radio') {
                   14606:                     form.elements[i].checked = true;
1.1056    raeburn  14607:                     var nostart = i-$startcount;
1.1059    raeburn  14608:                     var offset = nostart%7;
                   14609:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14610:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14611:                 }
                   14612:             }
                   14613:         }
                   14614:     }
                   14615: }
                   14616: 
                   14617: function propagateCheck(form,count) {
                   14618:     if (count > 0) {
1.1059    raeburn  14619:         var startelement = $startcount + ((count-1) * 7);
                   14620:         for (var j=1; j<6; j++) {
                   14621:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14622:                 var item = startelement + j; 
                   14623:                 if (form.elements[item].type == 'radio') {
                   14624:                     if (form.elements[item].checked) {
                   14625:                         containerCheck(form,count,j);
                   14626:                         break;
                   14627:                     }
1.1055    raeburn  14628:                 }
                   14629:             }
                   14630:         }
                   14631:     }
                   14632: }
                   14633: 
                   14634: numitems = $numitems
1.1056    raeburn  14635: var titles = new Array(numitems);
                   14636: var parents = new Array(numitems);
1.1055    raeburn  14637: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14638:     parents[i] = new Array;
1.1055    raeburn  14639: }
1.1059    raeburn  14640: var maintitle = '$maintitle';
1.1055    raeburn  14641: 
                   14642: START
                   14643: 
1.1056    raeburn  14644:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14645:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14646:         for (my $i=0; $i<@contents; $i ++) {
                   14647:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14648:         }
                   14649:     }
                   14650: 
1.1056    raeburn  14651:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14652:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14653:     }
                   14654: 
1.1055    raeburn  14655:     $scripttag .= <<END;
                   14656: 
                   14657: function containerCheck(form,count,offset) {
                   14658:     if (count > 0) {
1.1056    raeburn  14659:         dependencyCheck(form,count,offset);
1.1059    raeburn  14660:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14661:         form.elements[item].checked = true;
                   14662:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14663:             if (parents[count].length > 0) {
                   14664:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14665:                     containerCheck(form,parents[count][j],offset);
                   14666:                 }
                   14667:             }
                   14668:         }
                   14669:     }
                   14670: }
                   14671: 
                   14672: function dependencyCheck(form,count,offset) {
                   14673:     if (count > 0) {
1.1059    raeburn  14674:         var chosen = (offset+$startcount)+7*(count-1);
                   14675:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14676:         var currtype = form.elements[depitem].type;
                   14677:         if (form.elements[chosen].value == 'dependency') {
                   14678:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14679:             form.elements[depitem].options.length = 0;
                   14680:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14681:             for (var i=1; i<=numitems; i++) {
                   14682:                 if (i == count) {
                   14683:                     continue;
                   14684:                 }
1.1059    raeburn  14685:                 var startelement = $startcount + (i-1) * 7;
                   14686:                 for (var j=1; j<6; j++) {
                   14687:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14688:                         var item = startelement + j;
                   14689:                         if (form.elements[item].type == 'radio') {
                   14690:                             if (form.elements[item].checked) {
                   14691:                                 if (form.elements[item].value == 'display') {
                   14692:                                     var n = form.elements[depitem].options.length;
                   14693:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14694:                                 }
                   14695:                             }
                   14696:                         }
                   14697:                     }
                   14698:                 }
                   14699:             }
                   14700:         } else {
                   14701:             document.getElementById('arc_depon_'+count).style.display='none';
                   14702:             form.elements[depitem].options.length = 0;
                   14703:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14704:         }
1.1059    raeburn  14705:         titleCheck(form,count,offset);
1.1056    raeburn  14706:     }
                   14707: }
                   14708: 
                   14709: function propagateSelect(form,count,offset) {
                   14710:     if (count > 0) {
1.1065    raeburn  14711:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14712:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14713:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14714:             if (parents[count].length > 0) {
                   14715:                 for (var j=0; j<parents[count].length; j++) {
                   14716:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14717:                 }
                   14718:             }
                   14719:         }
                   14720:     }
                   14721: }
1.1056    raeburn  14722: 
                   14723: function containerSelect(form,count,offset,picked) {
                   14724:     if (count > 0) {
1.1065    raeburn  14725:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14726:         if (form.elements[item].type == 'radio') {
                   14727:             if (form.elements[item].value == 'dependency') {
                   14728:                 if (form.elements[item+1].type == 'select-one') {
                   14729:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14730:                         if (form.elements[item+1].options[i].value == picked) {
                   14731:                             form.elements[item+1].selectedIndex = i;
                   14732:                             break;
                   14733:                         }
                   14734:                     }
                   14735:                 }
                   14736:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14737:                     if (parents[count].length > 0) {
                   14738:                         for (var j=0; j<parents[count].length; j++) {
                   14739:                             containerSelect(form,parents[count][j],offset,picked);
                   14740:                         }
                   14741:                     }
                   14742:                 }
                   14743:             }
                   14744:         }
                   14745:     }
                   14746: }
                   14747: 
1.1059    raeburn  14748: function titleCheck(form,count,offset) {
                   14749:     if (count > 0) {
                   14750:         var chosen = (offset+$startcount)+7*(count-1);
                   14751:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14752:         var currtype = form.elements[depitem].type;
                   14753:         if (form.elements[chosen].value == 'display') {
                   14754:             document.getElementById('arc_title_'+count).style.display='block';
                   14755:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14756:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14757:             }
                   14758:         } else {
                   14759:             document.getElementById('arc_title_'+count).style.display='none';
                   14760:             if (currtype == 'text') { 
                   14761:                 document.getElementById('archive_title_'+count).value='';
                   14762:             }
                   14763:         }
                   14764:     }
                   14765:     return;
                   14766: }
                   14767: 
1.1055    raeburn  14768: // ]]>
                   14769: </script>
                   14770: END
                   14771:     return $scripttag;
                   14772: }
                   14773: 
                   14774: sub process_extracted_files {
1.1067    raeburn  14775:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14776:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14777:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14778:     my @ids=&Apache::lonnet::current_machine_ids();
                   14779:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14780:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14781:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14782:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14783:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14784:         $pathtocheck = "$dir_root/$destination";
                   14785:         $dir = $dir_root;
                   14786:         $ishome = 1;
                   14787:     } else {
                   14788:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14789:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14790:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14791:     }
                   14792:     my $currdir = "$dir_root/$destination";
                   14793:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14794:     if ($env{'form.folderpath'}) {
                   14795:         my @items = split('&',$env{'form.folderpath'});
                   14796:         $folders{'0'} = $items[-2];
1.1099    raeburn  14797:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14798:             $containers{'0'}='page';
                   14799:         } else {  
                   14800:             $containers{'0'}='sequence';
                   14801:         }
1.1055    raeburn  14802:     }
                   14803:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14804:     if ($numitems) {
                   14805:         for (my $i=1; $i<=$numitems; $i++) {
                   14806:             my $path = $env{'form.archive_content_'.$i};
                   14807:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14808:                 my $item = $1;
                   14809:                 $toplevelitems{$item} = $i;
                   14810:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14811:                     $is_dir{$item} = 1;
                   14812:                 }
                   14813:             }
                   14814:         }
                   14815:     }
1.1067    raeburn  14816:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14817:     if (keys(%toplevelitems) > 0) {
                   14818:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14819:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14820:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14821:     }
1.1066    raeburn  14822:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14823:     if ($numitems) {
                   14824:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14825:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14826:             my $path = $env{'form.archive_content_'.$i};
                   14827:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14828:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14829:                     if ($prefix ne '' && $path ne '') {
                   14830:                         if (-e $prefix.$path) {
1.1066    raeburn  14831:                             if ((@archdirs > 0) && 
                   14832:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14833:                                 $todeletedir{$prefix.$path} = 1;
                   14834:                             } else {
                   14835:                                 $todelete{$prefix.$path} = 1;
                   14836:                             }
1.1055    raeburn  14837:                         }
                   14838:                     }
                   14839:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14840:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14841:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14842:                     $docstitle = $env{'form.archive_title_'.$i};
                   14843:                     if ($docstitle eq '') {
                   14844:                         $docstitle = $title;
                   14845:                     }
1.1055    raeburn  14846:                     $outer = 0;
1.1056    raeburn  14847:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14848:                         if (@{$dirorder{$i}} > 0) {
                   14849:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14850:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14851:                                     $outer = $item;
                   14852:                                     last;
                   14853:                                 }
                   14854:                             }
                   14855:                         }
                   14856:                     }
                   14857:                     my ($errtext,$fatal) = 
                   14858:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14859:                                                '/'.$folders{$outer}.'.'.
                   14860:                                                $containers{$outer});
                   14861:                     next if ($fatal);
                   14862:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14863:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14864:                             $mapinner{$i} = time;
1.1055    raeburn  14865:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14866:                             $containers{$i} = 'sequence';
                   14867:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14868:                                       $folders{$i}.'.'.$containers{$i};
                   14869:                             my $newidx = &LONCAPA::map::getresidx();
                   14870:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14871:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14872:                             push(@LONCAPA::map::order,$newidx);
                   14873:                             my ($outtext,$errtext) =
                   14874:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14875:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14876:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14877:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14878:                             unless ($errtext) {
1.1294    raeburn  14879:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14880:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14881:                                             '</li>'."\n";
1.1067    raeburn  14882:                             }
1.1055    raeburn  14883:                         }
                   14884:                     } else {
                   14885:                         if ($context eq 'coursedocs') {
                   14886:                             my $newidx=&LONCAPA::map::getresidx();
                   14887:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14888:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14889:                                       $title;
1.1392    raeburn  14890:                             if (($outer !~ /\D/) &&
                   14891:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14892:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14893:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14894:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14895:                                 }
                   14896:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14897:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14898:                                 }
                   14899:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14900:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14901:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14902:                                         unless ($ishome) {
                   14903:                                             my $fetch = "$newdest{$i}/$title";
                   14904:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14905:                                             $prompttofetch{$fetch} = 1;
                   14906:                                         }
1.1292    raeburn  14907:                                     }
1.1067    raeburn  14908:                                 }
1.1294    raeburn  14909:                                 $LONCAPA::map::resources[$newidx]=
                   14910:                                     $docstitle.':'.$url.':false:normal:res';
                   14911:                                 push(@LONCAPA::map::order, $newidx);
                   14912:                                 my ($outtext,$errtext)=
                   14913:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14914:                                                             $docuname.'/'.$folders{$outer}.
                   14915:                                                             '.'.$containers{$outer},1,1);
                   14916:                                 unless ($errtext) {
                   14917:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14918:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14919:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14920:                                                    '</li>'."\n";
                   14921:                                     }
1.1067    raeburn  14922:                                 }
1.1294    raeburn  14923:                             } else {
                   14924:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14925:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14926:                             }
1.1055    raeburn  14927:                         }
                   14928:                     }
1.1086    raeburn  14929:                 }
                   14930:             } else {
1.1294    raeburn  14931:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14932:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14933:             }
                   14934:         }
                   14935:         for (my $i=1; $i<=$numitems; $i++) {
                   14936:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14937:             my $path = $env{'form.archive_content_'.$i};
                   14938:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14939:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14940:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14941:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14942:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14943:                         my ($itemidx,$fullpath,$relpath);
                   14944:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14945:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14946:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14947:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14948:                                     $itemidx = $j;
1.1056    raeburn  14949:                                 }
                   14950:                             }
1.1086    raeburn  14951:                         }
                   14952:                         if ($itemidx eq '') {
                   14953:                             $itemidx =  0;
                   14954:                         } 
                   14955:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14956:                             if ($mapinner{$referrer{$i}}) {
                   14957:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14958:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14959:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14960:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14961:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14962:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14963:                                             if (!-e $fullpath) {
                   14964:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14965:                                             }
                   14966:                                         }
1.1086    raeburn  14967:                                     } else {
                   14968:                                         last;
1.1056    raeburn  14969:                                     }
1.1086    raeburn  14970:                                 }
                   14971:                             }
                   14972:                         } elsif ($newdest{$referrer{$i}}) {
                   14973:                             $fullpath = $newdest{$referrer{$i}};
                   14974:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14975:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14976:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14977:                                     last;
                   14978:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14979:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14980:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14981:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14982:                                         if (!-e $fullpath) {
                   14983:                                             mkdir($fullpath,0755);
1.1056    raeburn  14984:                                         }
                   14985:                                     }
1.1086    raeburn  14986:                                 } else {
                   14987:                                     last;
1.1056    raeburn  14988:                                 }
1.1055    raeburn  14989:                             }
                   14990:                         }
1.1086    raeburn  14991:                         if ($fullpath ne '') {
                   14992:                             if (-e "$prefix$path") {
1.1292    raeburn  14993:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14994:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14995:                                 }
1.1086    raeburn  14996:                             }
                   14997:                             if (-e "$fullpath/$title") {
                   14998:                                 my $showpath;
                   14999:                                 if ($relpath ne '') {
                   15000:                                     $showpath = "$relpath/$title";
                   15001:                                 } else {
                   15002:                                     $showpath = "/$title";
                   15003:                                 } 
1.1294    raeburn  15004:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   15005:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   15006:                                            '</li>'."\n";
1.1292    raeburn  15007:                                 unless ($ishome) {
                   15008:                                     my $fetch = "$fullpath/$title";
                   15009:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   15010:                                     $prompttofetch{$fetch} = 1;
                   15011:                                 }
1.1086    raeburn  15012:                             }
                   15013:                         }
1.1055    raeburn  15014:                     }
1.1086    raeburn  15015:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   15016:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  15017:                                     &HTML::Entities::encode($path,'<>&"'),
                   15018:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   15019:                                 '<br />';
1.1055    raeburn  15020:                 }
                   15021:             } else {
1.1294    raeburn  15022:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  15023:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  15024:             }
                   15025:         }
                   15026:         if (keys(%todelete)) {
                   15027:             foreach my $key (keys(%todelete)) {
                   15028:                 unlink($key);
1.1066    raeburn  15029:             }
                   15030:         }
                   15031:         if (keys(%todeletedir)) {
                   15032:             foreach my $key (keys(%todeletedir)) {
                   15033:                 rmdir($key);
                   15034:             }
                   15035:         }
                   15036:         foreach my $dir (sort(keys(%is_dir))) {
                   15037:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   15038:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  15039:             }
                   15040:         }
1.1067    raeburn  15041:         if ($result ne '') {
                   15042:             $output .= '<ul>'."\n".
                   15043:                        $result."\n".
                   15044:                        '</ul>';
                   15045:         }
                   15046:         unless ($ishome) {
                   15047:             my $replicationfail;
                   15048:             foreach my $item (keys(%prompttofetch)) {
                   15049:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   15050:                 unless ($fetchresult eq 'ok') {
                   15051:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   15052:                 }
                   15053:             }
                   15054:             if ($replicationfail) {
                   15055:                 $output .= '<p class="LC_error">'.
                   15056:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   15057:                            $replicationfail.
                   15058:                            '</ul></p>';
                   15059:             }
                   15060:         }
1.1055    raeburn  15061:     } else {
                   15062:         $warning = &mt('No items found in archive.');
                   15063:     }
                   15064:     if ($error) {
                   15065:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   15066:                    $error.'</p>'."\n";
                   15067:     }
                   15068:     if ($warning) {
                   15069:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   15070:     }
                   15071:     return $output;
                   15072: }
                   15073: 
1.1066    raeburn  15074: sub cleanup_empty_dirs {
                   15075:     my ($path) = @_;
                   15076:     if (($path ne '') && (-d $path)) {
                   15077:         if (opendir(my $dirh,$path)) {
                   15078:             my @dircontents = grep(!/^\./,readdir($dirh));
                   15079:             my $numitems = 0;
                   15080:             foreach my $item (@dircontents) {
                   15081:                 if (-d "$path/$item") {
1.1111    raeburn  15082:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  15083:                     if (-e "$path/$item") {
                   15084:                         $numitems ++;
                   15085:                     }
                   15086:                 } else {
                   15087:                     $numitems ++;
                   15088:                 }
                   15089:             }
                   15090:             if ($numitems == 0) {
                   15091:                 rmdir($path);
                   15092:             }
                   15093:             closedir($dirh);
                   15094:         }
                   15095:     }
                   15096:     return;
                   15097: }
                   15098: 
1.41      ng       15099: =pod
1.45      matthew  15100: 
1.1162    raeburn  15101: =item * &get_folder_hierarchy()
1.1068    raeburn  15102: 
                   15103: Provides hierarchy of names of folders/sub-folders containing the current
                   15104: item,
                   15105: 
                   15106: Inputs: 3
                   15107:      - $navmap - navmaps object
                   15108: 
                   15109:      - $map - url for map (either the trigger itself, or map containing
                   15110:                            the resource, which is the trigger).
                   15111: 
                   15112:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   15113: 
                   15114: Outputs: 1 @pathitems - array of folder/subfolder names.
                   15115: 
                   15116: =cut
                   15117: 
                   15118: sub get_folder_hierarchy {
                   15119:     my ($navmap,$map,$showitem) = @_;
                   15120:     my @pathitems;
                   15121:     if (ref($navmap)) {
                   15122:         my $mapres = $navmap->getResourceByUrl($map);
                   15123:         if (ref($mapres)) {
                   15124:             my $pcslist = $mapres->map_hierarchy();
                   15125:             if ($pcslist ne '') {
                   15126:                 my @pcs = split(/,/,$pcslist);
                   15127:                 foreach my $pc (@pcs) {
                   15128:                     if ($pc == 1) {
1.1129    raeburn  15129:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  15130:                     } else {
                   15131:                         my $res = $navmap->getByMapPc($pc);
                   15132:                         if (ref($res)) {
                   15133:                             my $title = $res->compTitle();
                   15134:                             $title =~ s/\W+/_/g;
                   15135:                             if ($title ne '') {
                   15136:                                 push(@pathitems,$title);
                   15137:                             }
                   15138:                         }
                   15139:                     }
                   15140:                 }
                   15141:             }
1.1071    raeburn  15142:             if ($showitem) {
                   15143:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  15144:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  15145:                 } else {
                   15146:                     my $maptitle = $mapres->compTitle();
                   15147:                     $maptitle =~ s/\W+/_/g;
                   15148:                     if ($maptitle ne '') {
                   15149:                         push(@pathitems,$maptitle);
                   15150:                     }
1.1068    raeburn  15151:                 }
                   15152:             }
                   15153:         }
                   15154:     }
                   15155:     return @pathitems;
                   15156: }
                   15157: 
                   15158: =pod
                   15159: 
1.1015    raeburn  15160: =item * &get_turnedin_filepath()
                   15161: 
                   15162: Determines path in a user's portfolio file for storage of files uploaded
                   15163: to a specific essayresponse or dropbox item.
                   15164: 
                   15165: Inputs: 3 required + 1 optional.
                   15166: $symb is symb for resource, $uname and $udom are for current user (required).
                   15167: $caller is optional (can be "submission", if routine is called when storing
                   15168: an upoaded file when "Submit Answer" button was pressed).
                   15169: 
                   15170: Returns array containing $path and $multiresp. 
                   15171: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15172: than one file upload item.  Callers of routine should append partid as a 
                   15173: subdirectory to $path in cases where $multiresp is 1.
                   15174: 
                   15175: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15176: 
                   15177: =cut
                   15178: 
                   15179: sub get_turnedin_filepath {
                   15180:     my ($symb,$uname,$udom,$caller) = @_;
                   15181:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15182:     my $turnindir;
                   15183:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15184:     $turnindir = $userhash{'turnindir'};
                   15185:     my ($path,$multiresp);
                   15186:     if ($turnindir eq '') {
                   15187:         if ($caller eq 'submission') {
                   15188:             $turnindir = &mt('turned in');
                   15189:             $turnindir =~ s/\W+/_/g;
                   15190:             my %newhash = (
                   15191:                             'turnindir' => $turnindir,
                   15192:                           );
                   15193:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15194:         }
                   15195:     }
                   15196:     if ($turnindir ne '') {
                   15197:         $path = '/'.$turnindir.'/';
                   15198:         my ($multipart,$turnin,@pathitems);
                   15199:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15200:         if (defined($navmap)) {
                   15201:             my $mapres = $navmap->getResourceByUrl($map);
                   15202:             if (ref($mapres)) {
                   15203:                 my $pcslist = $mapres->map_hierarchy();
                   15204:                 if ($pcslist ne '') {
                   15205:                     foreach my $pc (split(/,/,$pcslist)) {
                   15206:                         my $res = $navmap->getByMapPc($pc);
                   15207:                         if (ref($res)) {
                   15208:                             my $title = $res->compTitle();
                   15209:                             $title =~ s/\W+/_/g;
                   15210:                             if ($title ne '') {
1.1149    raeburn  15211:                                 if (($pc > 1) && (length($title) > 12)) {
                   15212:                                     $title = substr($title,0,12);
                   15213:                                 }
1.1015    raeburn  15214:                                 push(@pathitems,$title);
                   15215:                             }
                   15216:                         }
                   15217:                     }
                   15218:                 }
                   15219:                 my $maptitle = $mapres->compTitle();
                   15220:                 $maptitle =~ s/\W+/_/g;
                   15221:                 if ($maptitle ne '') {
1.1149    raeburn  15222:                     if (length($maptitle) > 12) {
                   15223:                         $maptitle = substr($maptitle,0,12);
                   15224:                     }
1.1015    raeburn  15225:                     push(@pathitems,$maptitle);
                   15226:                 }
                   15227:                 unless ($env{'request.state'} eq 'construct') {
                   15228:                     my $res = $navmap->getBySymb($symb);
                   15229:                     if (ref($res)) {
                   15230:                         my $partlist = $res->parts();
                   15231:                         my $totaluploads = 0;
                   15232:                         if (ref($partlist) eq 'ARRAY') {
                   15233:                             foreach my $part (@{$partlist}) {
                   15234:                                 my @types = $res->responseType($part);
                   15235:                                 my @ids = $res->responseIds($part);
                   15236:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15237:                                     if ($types[$i] eq 'essay') {
                   15238:                                         my $partid = $part.'_'.$ids[$i];
                   15239:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15240:                                             $totaluploads ++;
                   15241:                                         }
                   15242:                                     }
                   15243:                                 }
                   15244:                             }
                   15245:                             if ($totaluploads > 1) {
                   15246:                                 $multiresp = 1;
                   15247:                             }
                   15248:                         }
                   15249:                     }
                   15250:                 }
                   15251:             } else {
                   15252:                 return;
                   15253:             }
                   15254:         } else {
                   15255:             return;
                   15256:         }
                   15257:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15258:         $restitle =~ s/\W+/_/g;
                   15259:         if ($restitle eq '') {
                   15260:             $restitle = ($resurl =~ m{/[^/]+$});
                   15261:             if ($restitle eq '') {
                   15262:                 $restitle = time;
                   15263:             }
                   15264:         }
1.1149    raeburn  15265:         if (length($restitle) > 12) {
                   15266:             $restitle = substr($restitle,0,12);
                   15267:         }
1.1015    raeburn  15268:         push(@pathitems,$restitle);
                   15269:         $path .= join('/',@pathitems);
                   15270:     }
                   15271:     return ($path,$multiresp);
                   15272: }
                   15273: 
                   15274: =pod
                   15275: 
1.464     albertel 15276: =back
1.41      ng       15277: 
1.112     bowersj2 15278: =head1 CSV Upload/Handling functions
1.38      albertel 15279: 
1.41      ng       15280: =over 4
                   15281: 
1.648     raeburn  15282: =item * &upfile_store($r)
1.41      ng       15283: 
                   15284: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15285: needs $env{'form.upfile'}
1.41      ng       15286: returns $datatoken to be put into hidden field
                   15287: 
                   15288: =cut
1.31      albertel 15289: 
                   15290: sub upfile_store {
                   15291:     my $r=shift;
1.258     albertel 15292:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15293:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15294:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15295:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15296: 
1.1299    raeburn  15297:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15298:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15299:                                      time.'_'.$$);
                   15300:     return if ($datatoken eq '');
                   15301: 
1.31      albertel 15302:     {
1.158     raeburn  15303:         my $datafile = $r->dir_config('lonDaemons').
                   15304:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15305:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15306:             print $fh $env{'form.upfile'};
1.158     raeburn  15307:             close($fh);
                   15308:         }
1.31      albertel 15309:     }
                   15310:     return $datatoken;
                   15311: }
                   15312: 
1.56      matthew  15313: =pod
                   15314: 
1.1290    raeburn  15315: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15316: 
                   15317: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15318: $datatoken is the name to assign to the temporary file.
1.258     albertel 15319: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15320: 
                   15321: =cut
1.31      albertel 15322: 
                   15323: sub load_tmp_file {
1.1290    raeburn  15324:     my ($r,$datatoken) = @_;
                   15325:     return if ($datatoken eq '');
1.31      albertel 15326:     my @studentdata=();
                   15327:     {
1.158     raeburn  15328:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15329:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15330:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15331:             @studentdata=<$fh>;
                   15332:             close($fh);
                   15333:         }
1.31      albertel 15334:     }
1.258     albertel 15335:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15336: }
                   15337: 
1.1290    raeburn  15338: sub valid_datatoken {
                   15339:     my ($datatoken) = @_;
1.1325    raeburn  15340:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15341:         return $datatoken;
                   15342:     }
                   15343:     return;
                   15344: }
                   15345: 
1.56      matthew  15346: =pod
                   15347: 
1.648     raeburn  15348: =item * &upfile_record_sep()
1.41      ng       15349: 
                   15350: Separate uploaded file into records
                   15351: returns array of records,
1.258     albertel 15352: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15353: 
                   15354: =cut
1.31      albertel 15355: 
                   15356: sub upfile_record_sep {
1.258     albertel 15357:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15358:     } else {
1.248     albertel 15359: 	my @records;
1.258     albertel 15360: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15361: 	    if ($line=~/^\s*$/) { next; }
                   15362: 	    push(@records,$line);
                   15363: 	}
                   15364: 	return @records;
1.31      albertel 15365:     }
                   15366: }
                   15367: 
1.56      matthew  15368: =pod
                   15369: 
1.648     raeburn  15370: =item * &record_sep($record)
1.41      ng       15371: 
1.258     albertel 15372: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15373: 
                   15374: =cut
                   15375: 
1.263     www      15376: sub takeleft {
                   15377:     my $index=shift;
                   15378:     return substr('0000'.$index,-4,4);
                   15379: }
                   15380: 
1.31      albertel 15381: sub record_sep {
                   15382:     my $record=shift;
                   15383:     my %components=();
1.258     albertel 15384:     if ($env{'form.upfiletype'} eq 'xml') {
                   15385:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15386:         my $i=0;
1.356     albertel 15387:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15388:             $field=~s/^(\"|\')//;
                   15389:             $field=~s/(\"|\')$//;
1.263     www      15390:             $components{&takeleft($i)}=$field;
1.31      albertel 15391:             $i++;
                   15392:         }
1.258     albertel 15393:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15394:         my $i=0;
1.356     albertel 15395:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15396:             $field=~s/^(\"|\')//;
                   15397:             $field=~s/(\"|\')$//;
1.263     www      15398:             $components{&takeleft($i)}=$field;
1.31      albertel 15399:             $i++;
                   15400:         }
                   15401:     } else {
1.561     www      15402:         my $separator=',';
1.480     banghart 15403:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15404:             $separator=';';
1.480     banghart 15405:         }
1.31      albertel 15406:         my $i=0;
1.561     www      15407: # the character we are looking for to indicate the end of a quote or a record 
                   15408:         my $looking_for=$separator;
                   15409: # do not add the characters to the fields
                   15410:         my $ignore=0;
                   15411: # we just encountered a separator (or the beginning of the record)
                   15412:         my $just_found_separator=1;
                   15413: # store the field we are working on here
                   15414:         my $field='';
                   15415: # work our way through all characters in record
                   15416:         foreach my $character ($record=~/(.)/g) {
                   15417:             if ($character eq $looking_for) {
                   15418:                if ($character ne $separator) {
                   15419: # Found the end of a quote, again looking for separator
                   15420:                   $looking_for=$separator;
                   15421:                   $ignore=1;
                   15422:                } else {
                   15423: # Found a separator, store away what we got
                   15424:                   $components{&takeleft($i)}=$field;
                   15425: 	          $i++;
                   15426:                   $just_found_separator=1;
                   15427:                   $ignore=0;
                   15428:                   $field='';
                   15429:                }
                   15430:                next;
                   15431:             }
                   15432: # single or double quotation marks after a separator indicate beginning of a quote
                   15433: # we are now looking for the end of the quote and need to ignore separators
                   15434:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15435:                $looking_for=$character;
                   15436:                next;
                   15437:             }
                   15438: # ignore would be true after we reached the end of a quote
                   15439:             if ($ignore) { next; }
                   15440:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15441:             $field.=$character;
                   15442:             $just_found_separator=0; 
1.31      albertel 15443:         }
1.561     www      15444: # catch the very last entry, since we never encountered the separator
                   15445:         $components{&takeleft($i)}=$field;
1.31      albertel 15446:     }
                   15447:     return %components;
                   15448: }
                   15449: 
1.144     matthew  15450: ######################################################
                   15451: ######################################################
                   15452: 
1.56      matthew  15453: =pod
                   15454: 
1.648     raeburn  15455: =item * &upfile_select_html()
1.41      ng       15456: 
1.144     matthew  15457: Return HTML code to select a file from the users machine and specify 
                   15458: the file type.
1.41      ng       15459: 
                   15460: =cut
                   15461: 
1.144     matthew  15462: ######################################################
                   15463: ######################################################
1.31      albertel 15464: sub upfile_select_html {
1.144     matthew  15465:     my %Types = (
                   15466:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15467:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15468:                  space => &mt('Space separated'),
                   15469:                  tab   => &mt('Tabulator separated'),
                   15470: #                 xml   => &mt('HTML/XML'),
                   15471:                  );
                   15472:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15473:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15474:     foreach my $type (sort(keys(%Types))) {
                   15475:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15476:     }
                   15477:     $Str .= "</select>\n";
                   15478:     return $Str;
1.31      albertel 15479: }
                   15480: 
1.301     albertel 15481: sub get_samples {
                   15482:     my ($records,$toget) = @_;
                   15483:     my @samples=({});
                   15484:     my $got=0;
                   15485:     foreach my $rec (@$records) {
                   15486: 	my %temp = &record_sep($rec);
                   15487: 	if (! grep(/\S/, values(%temp))) { next; }
                   15488: 	if (%temp) {
                   15489: 	    $samples[$got]=\%temp;
                   15490: 	    $got++;
                   15491: 	    if ($got == $toget) { last; }
                   15492: 	}
                   15493:     }
                   15494:     return \@samples;
                   15495: }
                   15496: 
1.144     matthew  15497: ######################################################
                   15498: ######################################################
                   15499: 
1.56      matthew  15500: =pod
                   15501: 
1.648     raeburn  15502: =item * &csv_print_samples($r,$records)
1.41      ng       15503: 
                   15504: Prints a table of sample values from each column uploaded $r is an
                   15505: Apache Request ref, $records is an arrayref from
                   15506: &Apache::loncommon::upfile_record_sep
                   15507: 
                   15508: =cut
                   15509: 
1.144     matthew  15510: ######################################################
                   15511: ######################################################
1.31      albertel 15512: sub csv_print_samples {
                   15513:     my ($r,$records) = @_;
1.662     bisitz   15514:     my $samples = &get_samples($records,5);
1.301     albertel 15515: 
1.594     raeburn  15516:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15517:               &start_data_table_header_row());
1.356     albertel 15518:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15519:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15520:     $r->print(&end_data_table_header_row());
1.301     albertel 15521:     foreach my $hash (@$samples) {
1.594     raeburn  15522: 	$r->print(&start_data_table_row());
1.356     albertel 15523: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15524: 	    $r->print('<td>');
1.356     albertel 15525: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15526: 	    $r->print('</td>');
                   15527: 	}
1.594     raeburn  15528: 	$r->print(&end_data_table_row());
1.31      albertel 15529:     }
1.594     raeburn  15530:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15531: }
                   15532: 
1.144     matthew  15533: ######################################################
                   15534: ######################################################
                   15535: 
1.56      matthew  15536: =pod
                   15537: 
1.648     raeburn  15538: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15539: 
                   15540: Prints a table to create associations between values and table columns.
1.144     matthew  15541: 
1.41      ng       15542: $r is an Apache Request ref,
                   15543: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15544: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15545: 
                   15546: =cut
                   15547: 
1.144     matthew  15548: ######################################################
                   15549: ######################################################
1.31      albertel 15550: sub csv_print_select_table {
                   15551:     my ($r,$records,$d) = @_;
1.301     albertel 15552:     my $i=0;
                   15553:     my $samples = &get_samples($records,1);
1.144     matthew  15554:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15555: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15556:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15557:               '<th>'.&mt('Column').'</th>'.
                   15558:               &end_data_table_header_row()."\n");
1.356     albertel 15559:     foreach my $array_ref (@$d) {
                   15560: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15561: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15562: 
1.875     bisitz   15563: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15564: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15565: 	$r->print('<option value="none"></option>');
1.356     albertel 15566: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15567: 	    $r->print('<option value="'.$sample.'"'.
                   15568:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15569:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15570: 	}
1.594     raeburn  15571: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15572: 	$i++;
                   15573:     }
1.594     raeburn  15574:     $r->print(&end_data_table());
1.31      albertel 15575:     $i--;
                   15576:     return $i;
                   15577: }
1.56      matthew  15578: 
1.144     matthew  15579: ######################################################
                   15580: ######################################################
                   15581: 
1.56      matthew  15582: =pod
1.31      albertel 15583: 
1.648     raeburn  15584: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15585: 
                   15586: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15587: 
                   15588: $r is an Apache Request ref,
                   15589: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15590: $d is an array of 2 element arrays (internal name, displayed name)
                   15591: 
                   15592: =cut
                   15593: 
1.144     matthew  15594: ######################################################
                   15595: ######################################################
1.31      albertel 15596: sub csv_samples_select_table {
                   15597:     my ($r,$records,$d) = @_;
                   15598:     my $i=0;
1.144     matthew  15599:     #
1.662     bisitz   15600:     my $max_samples = 5;
                   15601:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15602:     $r->print(&start_data_table().
                   15603:               &start_data_table_header_row().'<th>'.
                   15604:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15605:               &end_data_table_header_row());
1.301     albertel 15606: 
                   15607:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15608: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15609: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15610: 	foreach my $option (@$d) {
                   15611: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15612: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15613:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15614:                       $display.'</option>');
1.31      albertel 15615: 	}
                   15616: 	$r->print('</select></td><td>');
1.662     bisitz   15617: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15618: 	    if (defined($samples->[$line]{$key})) { 
                   15619: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15620: 	    }
                   15621: 	}
1.594     raeburn  15622: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15623: 	$i++;
                   15624:     }
1.594     raeburn  15625:     $r->print(&end_data_table());
1.31      albertel 15626:     $i--;
                   15627:     return($i);
1.115     matthew  15628: }
                   15629: 
1.144     matthew  15630: ######################################################
                   15631: ######################################################
                   15632: 
1.115     matthew  15633: =pod
                   15634: 
1.648     raeburn  15635: =item * &clean_excel_name($name)
1.115     matthew  15636: 
                   15637: Returns a replacement for $name which does not contain any illegal characters.
                   15638: 
                   15639: =cut
                   15640: 
1.144     matthew  15641: ######################################################
                   15642: ######################################################
1.115     matthew  15643: sub clean_excel_name {
                   15644:     my ($name) = @_;
                   15645:     $name =~ s/[:\*\?\/\\]//g;
                   15646:     if (length($name) > 31) {
                   15647:         $name = substr($name,0,31);
                   15648:     }
                   15649:     return $name;
1.25      albertel 15650: }
1.84      albertel 15651: 
1.85      albertel 15652: =pod
                   15653: 
1.648     raeburn  15654: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15655: 
                   15656: Returns either 1 or undef
                   15657: 
                   15658: 1 if the part is to be hidden, undef if it is to be shown
                   15659: 
                   15660: Arguments are:
                   15661: 
                   15662: $id the id of the part to be checked
                   15663: $symb, optional the symb of the resource to check
                   15664: $udom, optional the domain of the user to check for
                   15665: $uname, optional the username of the user to check for
                   15666: 
                   15667: =cut
1.84      albertel 15668: 
                   15669: sub check_if_partid_hidden {
                   15670:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15671:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15672: 					 $symb,$udom,$uname);
1.141     albertel 15673:     my $truth=1;
                   15674:     #if the string starts with !, then the list is the list to show not hide
                   15675:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15676:     my @hiddenlist=split(/,/,$hiddenparts);
                   15677:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15678: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15679:     }
1.141     albertel 15680:     return !$truth;
1.84      albertel 15681: }
1.127     matthew  15682: 
1.138     matthew  15683: 
                   15684: ############################################################
                   15685: ############################################################
                   15686: 
                   15687: =pod
                   15688: 
1.157     matthew  15689: =back 
                   15690: 
1.138     matthew  15691: =head1 cgi-bin script and graphing routines
                   15692: 
1.157     matthew  15693: =over 4
                   15694: 
1.648     raeburn  15695: =item * &get_cgi_id()
1.138     matthew  15696: 
                   15697: Inputs: none
                   15698: 
                   15699: Returns an id which can be used to pass environment variables
                   15700: to various cgi-bin scripts.  These environment variables will
                   15701: be removed from the users environment after a given time by
                   15702: the routine &Apache::lonnet::transfer_profile_to_env.
                   15703: 
                   15704: =cut
                   15705: 
                   15706: ############################################################
                   15707: ############################################################
1.152     albertel 15708: my $uniq=0;
1.136     matthew  15709: sub get_cgi_id {
1.154     albertel 15710:     $uniq=($uniq+1)%100000;
1.280     albertel 15711:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15712: }
                   15713: 
1.127     matthew  15714: ############################################################
                   15715: ############################################################
                   15716: 
                   15717: =pod
                   15718: 
1.648     raeburn  15719: =item * &DrawBarGraph()
1.127     matthew  15720: 
1.138     matthew  15721: Facilitates the plotting of data in a (stacked) bar graph.
                   15722: Puts plot definition data into the users environment in order for 
                   15723: graph.png to plot it.  Returns an <img> tag for the plot.
                   15724: The bars on the plot are labeled '1','2',...,'n'.
                   15725: 
                   15726: Inputs:
                   15727: 
                   15728: =over 4
                   15729: 
                   15730: =item $Title: string, the title of the plot
                   15731: 
                   15732: =item $xlabel: string, text describing the X-axis of the plot
                   15733: 
                   15734: =item $ylabel: string, text describing the Y-axis of the plot
                   15735: 
                   15736: =item $Max: scalar, the maximum Y value to use in the plot
                   15737: If $Max is < any data point, the graph will not be rendered.
                   15738: 
1.140     matthew  15739: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15740: they are plotted.  If undefined, default values will be used.
                   15741: 
1.178     matthew  15742: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15743: 
1.138     matthew  15744: =item @Values: An array of array references.  Each array reference holds data
                   15745: to be plotted in a stacked bar chart.
                   15746: 
1.239     matthew  15747: =item If the final element of @Values is a hash reference the key/value
                   15748: pairs will be added to the graph definition.
                   15749: 
1.138     matthew  15750: =back
                   15751: 
                   15752: Returns:
                   15753: 
                   15754: An <img> tag which references graph.png and the appropriate identifying
                   15755: information for the plot.
                   15756: 
1.127     matthew  15757: =cut
                   15758: 
                   15759: ############################################################
                   15760: ############################################################
1.134     matthew  15761: sub DrawBarGraph {
1.178     matthew  15762:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15763:     #
                   15764:     if (! defined($colors)) {
                   15765:         $colors = ['#33ff00', 
                   15766:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15767:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15768:                   ]; 
                   15769:     }
1.228     matthew  15770:     my $extra_settings = {};
                   15771:     if (ref($Values[-1]) eq 'HASH') {
                   15772:         $extra_settings = pop(@Values);
                   15773:     }
1.127     matthew  15774:     #
1.136     matthew  15775:     my $identifier = &get_cgi_id();
                   15776:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15777:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15778:         return '';
                   15779:     }
1.225     matthew  15780:     #
                   15781:     my @Labels;
                   15782:     if (defined($labels)) {
                   15783:         @Labels = @$labels;
                   15784:     } else {
                   15785:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15786:             push(@Labels,$i+1);
1.225     matthew  15787:         }
                   15788:     }
                   15789:     #
1.129     matthew  15790:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15791:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15792:     my %ValuesHash;
                   15793:     my $NumSets=1;
                   15794:     foreach my $array (@Values) {
                   15795:         next if (! ref($array));
1.136     matthew  15796:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15797:             join(',',@$array);
1.129     matthew  15798:     }
1.127     matthew  15799:     #
1.136     matthew  15800:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15801:     if ($NumBars < 3) {
                   15802:         $width = 120+$NumBars*32;
1.220     matthew  15803:         $xskip = 1;
1.225     matthew  15804:         $bar_width = 30;
                   15805:     } elsif ($NumBars < 5) {
                   15806:         $width = 120+$NumBars*20;
                   15807:         $xskip = 1;
                   15808:         $bar_width = 20;
1.220     matthew  15809:     } elsif ($NumBars < 10) {
1.136     matthew  15810:         $width = 120+$NumBars*15;
                   15811:         $xskip = 1;
                   15812:         $bar_width = 15;
                   15813:     } elsif ($NumBars <= 25) {
                   15814:         $width = 120+$NumBars*11;
                   15815:         $xskip = 5;
                   15816:         $bar_width = 8;
                   15817:     } elsif ($NumBars <= 50) {
                   15818:         $width = 120+$NumBars*8;
                   15819:         $xskip = 5;
                   15820:         $bar_width = 4;
                   15821:     } else {
                   15822:         $width = 120+$NumBars*8;
                   15823:         $xskip = 5;
                   15824:         $bar_width = 4;
                   15825:     }
                   15826:     #
1.137     matthew  15827:     $Max = 1 if ($Max < 1);
                   15828:     if ( int($Max) < $Max ) {
                   15829:         $Max++;
                   15830:         $Max = int($Max);
                   15831:     }
1.127     matthew  15832:     $Title  = '' if (! defined($Title));
                   15833:     $xlabel = '' if (! defined($xlabel));
                   15834:     $ylabel = '' if (! defined($ylabel));
1.369     www      15835:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15836:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15837:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15838:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15839:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15840:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15841:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15842:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15843:     $ValuesHash{$id.'.height'}   = $height;
                   15844:     $ValuesHash{$id.'.width'}    = $width;
                   15845:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15846:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15847:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15848:     #
1.228     matthew  15849:     # Deal with other parameters
                   15850:     while (my ($key,$value) = each(%$extra_settings)) {
                   15851:         $ValuesHash{$id.'.'.$key} = $value;
                   15852:     }
                   15853:     #
1.646     raeburn  15854:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15855:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15856: }
                   15857: 
                   15858: ############################################################
                   15859: ############################################################
                   15860: 
                   15861: =pod
                   15862: 
1.648     raeburn  15863: =item * &DrawXYGraph()
1.137     matthew  15864: 
1.138     matthew  15865: Facilitates the plotting of data in an XY graph.
                   15866: Puts plot definition data into the users environment in order for 
                   15867: graph.png to plot it.  Returns an <img> tag for the plot.
                   15868: 
                   15869: Inputs:
                   15870: 
                   15871: =over 4
                   15872: 
                   15873: =item $Title: string, the title of the plot
                   15874: 
                   15875: =item $xlabel: string, text describing the X-axis of the plot
                   15876: 
                   15877: =item $ylabel: string, text describing the Y-axis of the plot
                   15878: 
                   15879: =item $Max: scalar, the maximum Y value to use in the plot
                   15880: If $Max is < any data point, the graph will not be rendered.
                   15881: 
                   15882: =item $colors: Array ref containing the hex color codes for the data to be 
                   15883: plotted in.  If undefined, default values will be used.
                   15884: 
                   15885: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15886: 
                   15887: =item $Ydata: Array ref containing Array refs.  
1.185     www      15888: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15889: 
                   15890: =item %Values: hash indicating or overriding any default values which are 
                   15891: passed to graph.png.  
                   15892: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15893: 
                   15894: =back
                   15895: 
                   15896: Returns:
                   15897: 
                   15898: An <img> tag which references graph.png and the appropriate identifying
                   15899: information for the plot.
                   15900: 
1.137     matthew  15901: =cut
                   15902: 
                   15903: ############################################################
                   15904: ############################################################
                   15905: sub DrawXYGraph {
                   15906:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15907:     #
                   15908:     # Create the identifier for the graph
                   15909:     my $identifier = &get_cgi_id();
                   15910:     my $id = 'cgi.'.$identifier;
                   15911:     #
                   15912:     $Title  = '' if (! defined($Title));
                   15913:     $xlabel = '' if (! defined($xlabel));
                   15914:     $ylabel = '' if (! defined($ylabel));
                   15915:     my %ValuesHash = 
                   15916:         (
1.369     www      15917:          $id.'.title'  => &escape($Title),
                   15918:          $id.'.xlabel' => &escape($xlabel),
                   15919:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15920:          $id.'.y_max_value'=> $Max,
                   15921:          $id.'.labels'     => join(',',@$Xlabels),
                   15922:          $id.'.PlotType'   => 'XY',
                   15923:          );
                   15924:     #
                   15925:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15926:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15927:     }
                   15928:     #
                   15929:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15930:         return '';
                   15931:     }
                   15932:     my $NumSets=1;
1.138     matthew  15933:     foreach my $array (@{$Ydata}){
1.137     matthew  15934:         next if (! ref($array));
                   15935:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15936:     }
1.138     matthew  15937:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15938:     #
                   15939:     # Deal with other parameters
                   15940:     while (my ($key,$value) = each(%Values)) {
                   15941:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15942:     }
                   15943:     #
1.646     raeburn  15944:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15945:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15946: }
                   15947: 
                   15948: ############################################################
                   15949: ############################################################
                   15950: 
                   15951: =pod
                   15952: 
1.648     raeburn  15953: =item * &DrawXYYGraph()
1.138     matthew  15954: 
                   15955: Facilitates the plotting of data in an XY graph with two Y axes.
                   15956: Puts plot definition data into the users environment in order for 
                   15957: graph.png to plot it.  Returns an <img> tag for the plot.
                   15958: 
                   15959: Inputs:
                   15960: 
                   15961: =over 4
                   15962: 
                   15963: =item $Title: string, the title of the plot
                   15964: 
                   15965: =item $xlabel: string, text describing the X-axis of the plot
                   15966: 
                   15967: =item $ylabel: string, text describing the Y-axis of the plot
                   15968: 
                   15969: =item $colors: Array ref containing the hex color codes for the data to be 
                   15970: plotted in.  If undefined, default values will be used.
                   15971: 
                   15972: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15973: 
                   15974: =item $Ydata1: The first data set
                   15975: 
                   15976: =item $Min1: The minimum value of the left Y-axis
                   15977: 
                   15978: =item $Max1: The maximum value of the left Y-axis
                   15979: 
                   15980: =item $Ydata2: The second data set
                   15981: 
                   15982: =item $Min2: The minimum value of the right Y-axis
                   15983: 
                   15984: =item $Max2: The maximum value of the left Y-axis
                   15985: 
                   15986: =item %Values: hash indicating or overriding any default values which are 
                   15987: passed to graph.png.  
                   15988: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15989: 
                   15990: =back
                   15991: 
                   15992: Returns:
                   15993: 
                   15994: An <img> tag which references graph.png and the appropriate identifying
                   15995: information for the plot.
1.136     matthew  15996: 
                   15997: =cut
                   15998: 
                   15999: ############################################################
                   16000: ############################################################
1.137     matthew  16001: sub DrawXYYGraph {
                   16002:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   16003:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  16004:     #
                   16005:     # Create the identifier for the graph
                   16006:     my $identifier = &get_cgi_id();
                   16007:     my $id = 'cgi.'.$identifier;
                   16008:     #
                   16009:     $Title  = '' if (! defined($Title));
                   16010:     $xlabel = '' if (! defined($xlabel));
                   16011:     $ylabel = '' if (! defined($ylabel));
                   16012:     my %ValuesHash = 
                   16013:         (
1.369     www      16014:          $id.'.title'  => &escape($Title),
                   16015:          $id.'.xlabel' => &escape($xlabel),
                   16016:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  16017:          $id.'.labels' => join(',',@$Xlabels),
                   16018:          $id.'.PlotType' => 'XY',
                   16019:          $id.'.NumSets' => 2,
1.137     matthew  16020:          $id.'.two_axes' => 1,
                   16021:          $id.'.y1_max_value' => $Max1,
                   16022:          $id.'.y1_min_value' => $Min1,
                   16023:          $id.'.y2_max_value' => $Max2,
                   16024:          $id.'.y2_min_value' => $Min2,
1.136     matthew  16025:          );
                   16026:     #
1.137     matthew  16027:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   16028:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   16029:     }
                   16030:     #
                   16031:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   16032:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  16033:         return '';
                   16034:     }
                   16035:     my $NumSets=1;
1.137     matthew  16036:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  16037:         next if (! ref($array));
                   16038:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  16039:     }
                   16040:     #
                   16041:     # Deal with other parameters
                   16042:     while (my ($key,$value) = each(%Values)) {
                   16043:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  16044:     }
                   16045:     #
1.646     raeburn  16046:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 16047:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  16048: }
                   16049: 
                   16050: ############################################################
                   16051: ############################################################
                   16052: 
                   16053: =pod
                   16054: 
1.157     matthew  16055: =back 
                   16056: 
1.139     matthew  16057: =head1 Statistics helper routines?  
                   16058: 
                   16059: Bad place for them but what the hell.
                   16060: 
1.157     matthew  16061: =over 4
                   16062: 
1.648     raeburn  16063: =item * &chartlink()
1.139     matthew  16064: 
                   16065: Returns a link to the chart for a specific student.  
                   16066: 
                   16067: Inputs:
                   16068: 
                   16069: =over 4
                   16070: 
                   16071: =item $linktext: The text of the link
                   16072: 
                   16073: =item $sname: The students username
                   16074: 
                   16075: =item $sdomain: The students domain
                   16076: 
                   16077: =back
                   16078: 
1.157     matthew  16079: =back
                   16080: 
1.139     matthew  16081: =cut
                   16082: 
                   16083: ############################################################
                   16084: ############################################################
                   16085: sub chartlink {
                   16086:     my ($linktext, $sname, $sdomain) = @_;
                   16087:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      16088:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 16089:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  16090:        '">'.$linktext.'</a>';
1.153     matthew  16091: }
                   16092: 
                   16093: #######################################################
                   16094: #######################################################
                   16095: 
                   16096: =pod
                   16097: 
                   16098: =head1 Course Environment Routines
1.157     matthew  16099: 
                   16100: =over 4
1.153     matthew  16101: 
1.648     raeburn  16102: =item * &restore_course_settings()
1.153     matthew  16103: 
1.648     raeburn  16104: =item * &store_course_settings()
1.153     matthew  16105: 
                   16106: Restores/Store indicated form parameters from the course environment.
                   16107: Will not overwrite existing values of the form parameters.
                   16108: 
                   16109: Inputs: 
                   16110: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   16111: 
                   16112: a hash ref describing the data to be stored.  For example:
                   16113:    
                   16114: %Save_Parameters = ('Status' => 'scalar',
                   16115:     'chartoutputmode' => 'scalar',
                   16116:     'chartoutputdata' => 'scalar',
                   16117:     'Section' => 'array',
1.373     raeburn  16118:     'Group' => 'array',
1.153     matthew  16119:     'StudentData' => 'array',
                   16120:     'Maps' => 'array');
                   16121: 
                   16122: Returns: both routines return nothing
                   16123: 
1.631     raeburn  16124: =back
                   16125: 
1.153     matthew  16126: =cut
                   16127: 
                   16128: #######################################################
                   16129: #######################################################
                   16130: sub store_course_settings {
1.496     albertel 16131:     return &store_settings($env{'request.course.id'},@_);
                   16132: }
                   16133: 
                   16134: sub store_settings {
1.153     matthew  16135:     # save to the environment
                   16136:     # appenv the same items, just to be safe
1.300     albertel 16137:     my $udom  = $env{'user.domain'};
                   16138:     my $uname = $env{'user.name'};
1.496     albertel 16139:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16140:     my %SaveHash;
                   16141:     my %AppHash;
                   16142:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 16143:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 16144:         my $envname = 'environment.'.$basename;
1.258     albertel 16145:         if (exists($env{'form.'.$setting})) {
1.153     matthew  16146:             # Save this value away
                   16147:             if ($type eq 'scalar' &&
1.258     albertel 16148:                 (! exists($env{$envname}) || 
                   16149:                  $env{$envname} ne $env{'form.'.$setting})) {
                   16150:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   16151:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  16152:             } elsif ($type eq 'array') {
                   16153:                 my $stored_form;
1.258     albertel 16154:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  16155:                     $stored_form = join(',',
                   16156:                                         map {
1.369     www      16157:                                             &escape($_);
1.258     albertel 16158:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  16159:                 } else {
                   16160:                     $stored_form = 
1.369     www      16161:                         &escape($env{'form.'.$setting});
1.153     matthew  16162:                 }
                   16163:                 # Determine if the array contents are the same.
1.258     albertel 16164:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16165:                     $SaveHash{$basename} = $stored_form;
                   16166:                     $AppHash{$envname}   = $stored_form;
                   16167:                 }
                   16168:             }
                   16169:         }
                   16170:     }
                   16171:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16172:                                           $udom,$uname);
1.153     matthew  16173:     if ($put_result !~ /^(ok|delayed)/) {
                   16174:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16175:                                  'got error:'.$put_result);
                   16176:     }
                   16177:     # Make sure these settings stick around in this session, too
1.646     raeburn  16178:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16179:     return;
                   16180: }
                   16181: 
                   16182: sub restore_course_settings {
1.499     albertel 16183:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16184: }
                   16185: 
                   16186: sub restore_settings {
                   16187:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16188:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16189:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16190:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16191:             '.'.$setting;
1.258     albertel 16192:         if (exists($env{$envname})) {
1.153     matthew  16193:             if ($type eq 'scalar') {
1.258     albertel 16194:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16195:             } elsif ($type eq 'array') {
1.258     albertel 16196:                 $env{'form.'.$setting} = [ 
1.153     matthew  16197:                                            map { 
1.369     www      16198:                                                &unescape($_); 
1.258     albertel 16199:                                            } split(',',$env{$envname})
1.153     matthew  16200:                                            ];
                   16201:             }
                   16202:         }
                   16203:     }
1.127     matthew  16204: }
                   16205: 
1.618     raeburn  16206: #######################################################
                   16207: #######################################################
                   16208: 
                   16209: =pod
                   16210: 
                   16211: =head1 Domain E-mail Routines  
                   16212: 
                   16213: =over 4
                   16214: 
1.648     raeburn  16215: =item * &build_recipient_list()
1.618     raeburn  16216: 
1.1144    raeburn  16217: Build recipient lists for following types of e-mail:
1.766     raeburn  16218: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16219: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16220: module change checking, student/employee ID conflict checks, as
                   16221: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16222: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16223: 
                   16224: Inputs:
1.619     raeburn  16225: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16226: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16227: requestsmail, updatesmail, or idconflictsmail).
                   16228: 
1.619     raeburn  16229: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16230: 
1.619     raeburn  16231: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16232: i.e., predates configuration by DC via domainprefs.pm
                   16233: 
                   16234: $requname username of requester (if mailing type is helpdeskmail)
                   16235: 
                   16236: $requdom domain of requester (if mailing type is helpdeskmail)
                   16237: 
                   16238: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16239: 
1.618     raeburn  16240: 
1.655     raeburn  16241: Returns: comma separated list of addresses to which to send e-mail.
                   16242: 
                   16243: =back
1.618     raeburn  16244: 
                   16245: =cut
                   16246: 
                   16247: ############################################################
                   16248: ############################################################
                   16249: sub build_recipient_list {
1.1297    raeburn  16250:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16251:     my @recipients;
1.1270    raeburn  16252:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16253:     my %domconfig =
1.1270    raeburn  16254:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16255:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16256:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16257:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16258:                 my @contacts = ('adminemail','supportemail');
                   16259:                 foreach my $item (@contacts) {
                   16260:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16261:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16262:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16263:                             push(@recipients,$addr);
                   16264:                         }
1.619     raeburn  16265:                     }
1.1270    raeburn  16266:                 }
                   16267:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16268:                 if ($mailing eq 'helpdeskmail') {
                   16269:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16270:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16271:                         my @ok_bccs;
                   16272:                         foreach my $bcc (@bccs) {
                   16273:                             $bcc =~ s/^\s+//g;
                   16274:                             $bcc =~ s/\s+$//g;
                   16275:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16276:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16277:                                     push(@ok_bccs,$bcc);
                   16278:                                 }
                   16279:                             }
                   16280:                         }
                   16281:                         if (@ok_bccs > 0) {
                   16282:                             $allbcc = join(', ',@ok_bccs);
                   16283:                         }
                   16284:                     }
                   16285:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16286:                 }
                   16287:             }
1.766     raeburn  16288:         } elsif ($origmail ne '') {
1.1270    raeburn  16289:             $lastresort = $origmail;
1.618     raeburn  16290:         }
1.1297    raeburn  16291:         if ($mailing eq 'helpdeskmail') {
                   16292:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16293:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16294:                 my ($inststatus,$inststatus_checked);
                   16295:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16296:                     ($env{'user.domain'} ne 'public')) {
                   16297:                     $inststatus_checked = 1;
                   16298:                     $inststatus = $env{'environment.inststatus'};
                   16299:                 }
                   16300:                 unless ($inststatus_checked) {
                   16301:                     if (($requname ne '') && ($requdom ne '')) {
                   16302:                         if (($requname =~ /^$match_username$/) &&
                   16303:                             ($requdom =~ /^$match_domain$/) &&
                   16304:                             (&Apache::lonnet::domain($requdom))) {
                   16305:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16306:                                                                       $requdom);
                   16307:                             unless ($requhome eq 'no_host') {
                   16308:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16309:                                 $inststatus = $userenv{'inststatus'};
                   16310:                                 $inststatus_checked = 1;
                   16311:                             }
                   16312:                         }
                   16313:                     }
                   16314:                 }
                   16315:                 unless ($inststatus_checked) {
                   16316:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16317:                         my %srch = (srchby     => 'email',
                   16318:                                     srchdomain => $defdom,
                   16319:                                     srchterm   => $reqemail,
                   16320:                                     srchtype   => 'exact');
                   16321:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16322:                         foreach my $uname (keys(%srch_results)) {
                   16323:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16324:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16325:                                 $inststatus_checked = 1;
                   16326:                                 last;
                   16327:                             }
                   16328:                         }
                   16329:                         unless ($inststatus_checked) {
                   16330:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16331:                             if ($dirsrchres eq 'ok') {
                   16332:                                 foreach my $uname (keys(%srch_results)) {
                   16333:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16334:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16335:                                         $inststatus_checked = 1;
                   16336:                                         last;
                   16337:                                     }
                   16338:                                 }
                   16339:                             }
                   16340:                         }
                   16341:                     }
                   16342:                 }
                   16343:                 if ($inststatus ne '') {
                   16344:                     foreach my $status (split(/\:/,$inststatus)) {
                   16345:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16346:                             my @contacts = ('adminemail','supportemail');
                   16347:                             foreach my $item (@contacts) {
                   16348:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16349:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16350:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16351:                                         push(@recipients,$addr);
                   16352:                                     }
                   16353:                                 }
                   16354:                             }
                   16355:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16356:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16357:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16358:                                 my @ok_bccs;
                   16359:                                 foreach my $bcc (@bccs) {
                   16360:                                     $bcc =~ s/^\s+//g;
                   16361:                                     $bcc =~ s/\s+$//g;
                   16362:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16363:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16364:                                             push(@ok_bccs,$bcc);
                   16365:                                         }
                   16366:                                     }
                   16367:                                 }
                   16368:                                 if (@ok_bccs > 0) {
                   16369:                                     $allbcc = join(', ',@ok_bccs);
                   16370:                                 }
                   16371:                             }
                   16372:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16373:                             last;
                   16374:                         }
                   16375:                     }
                   16376:                 }
                   16377:             }
                   16378:         }
1.619     raeburn  16379:     } elsif ($origmail ne '') {
1.1270    raeburn  16380:         $lastresort = $origmail;
                   16381:     }
1.1297    raeburn  16382:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16383:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16384:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16385:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16386:             my %what = (
                   16387:                           perlvar => 1,
                   16388:                        );
                   16389:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16390:             if ($primary) {
                   16391:                 my $gotaddr;
                   16392:                 my ($result,$returnhash) =
                   16393:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16394:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16395:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16396:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16397:                         $gotaddr = 1;
                   16398:                     }
                   16399:                 }
                   16400:                 unless ($gotaddr) {
                   16401:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16402:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16403:                     unless ($uintdom eq $intdom) {
                   16404:                         my %domconfig =
                   16405:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16406:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16407:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16408:                                 my @contacts = ('adminemail','supportemail');
                   16409:                                 foreach my $item (@contacts) {
                   16410:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16411:                                         my $addr = $domconfig{'contacts'}{$item};
                   16412:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16413:                                             push(@recipients,$addr);
                   16414:                                         }
                   16415:                                     }
                   16416:                                 }
                   16417:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16418:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16419:                                 }
                   16420:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16421:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16422:                                     my @ok_bccs;
                   16423:                                     foreach my $bcc (@bccs) {
                   16424:                                         $bcc =~ s/^\s+//g;
                   16425:                                         $bcc =~ s/\s+$//g;
                   16426:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16427:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16428:                                                 push(@ok_bccs,$bcc);
                   16429:                                             }
                   16430:                                         }
                   16431:                                     }
                   16432:                                     if (@ok_bccs > 0) {
                   16433:                                         $allbcc = join(', ',@ok_bccs);
                   16434:                                     }
                   16435:                                 }
                   16436:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16437:                             }
                   16438:                         }
                   16439:                     }
                   16440:                 }
                   16441:             }
                   16442:         }
1.618     raeburn  16443:     }
1.688     raeburn  16444:     if (defined($defmail)) {
                   16445:         if ($defmail ne '') {
                   16446:             push(@recipients,$defmail);
                   16447:         }
1.618     raeburn  16448:     }
                   16449:     if ($otheremails) {
1.619     raeburn  16450:         my @others;
                   16451:         if ($otheremails =~ /,/) {
                   16452:             @others = split(/,/,$otheremails);
1.618     raeburn  16453:         } else {
1.619     raeburn  16454:             push(@others,$otheremails);
                   16455:         }
                   16456:         foreach my $addr (@others) {
                   16457:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16458:                 push(@recipients,$addr);
                   16459:             }
1.618     raeburn  16460:         }
                   16461:     }
1.1298    raeburn  16462:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16463:         if ((!@recipients) && ($lastresort ne '')) {
                   16464:             push(@recipients,$lastresort);
                   16465:         }
                   16466:     } elsif ($lastresort ne '') {
                   16467:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16468:             push(@recipients,$lastresort);
                   16469:         }
                   16470:     }
1.1271    raeburn  16471:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16472:     if (wantarray) {
                   16473:         return ($recipientlist,$allbcc,$addtext);
                   16474:     } else {
                   16475:         return $recipientlist;
                   16476:     }
1.618     raeburn  16477: }
                   16478: 
1.127     matthew  16479: ############################################################
                   16480: ############################################################
1.154     albertel 16481: 
1.655     raeburn  16482: =pod
                   16483: 
1.1224    musolffc 16484: =over 4
                   16485: 
1.1223    musolffc 16486: =item * &mime_email()
                   16487: 
                   16488: Sends an email with a possible attachment
                   16489: 
                   16490: Inputs:
                   16491: 
                   16492: =over 4
                   16493: 
                   16494: from -              Sender's email address
                   16495: 
1.1343    raeburn  16496: replyto -           Reply-To email address
                   16497: 
1.1223    musolffc 16498: to -                Email address of recipient
                   16499: 
                   16500: subject -           Subject of email
                   16501: 
                   16502: body -              Body of email
                   16503: 
                   16504: cc_string -         Carbon copy email address
                   16505: 
                   16506: bcc -               Blind carbon copy email address
                   16507: 
                   16508: attachment_path -   Path of file to be attached
                   16509: 
                   16510: file_name -         Name of file to be attached
                   16511: 
                   16512: attachment_text -   The body of an attachment of type "TEXT"
                   16513: 
                   16514: =back
                   16515: 
                   16516: =back
                   16517: 
                   16518: =cut
                   16519: 
                   16520: ############################################################
                   16521: ############################################################
                   16522: 
                   16523: sub mime_email {
1.1343    raeburn  16524:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16525:         $file_name,$attachment_text) = @_;
                   16526:  
1.1223    musolffc 16527:     my $msg = MIME::Lite->new(
                   16528:              From    => $from,
                   16529:              To      => $to,
                   16530:              Subject => $subject,
                   16531:              Type    =>'TEXT',
                   16532:              Data    => $body,
                   16533:              );
1.1343    raeburn  16534:     if ($replyto ne '') {
                   16535:         $msg->add("Reply-To" => $replyto);
                   16536:     }
1.1223    musolffc 16537:     if ($cc_string ne '') {
                   16538:         $msg->add("Cc" => $cc_string);
                   16539:     }
                   16540:     if ($bcc ne '') {
                   16541:         $msg->add("Bcc" => $bcc);
                   16542:     }
                   16543:     $msg->attr("content-type"         => "text/plain");
                   16544:     $msg->attr("content-type.charset" => "UTF-8");
                   16545:     # Attach file if given
                   16546:     if ($attachment_path) {
                   16547:         unless ($file_name) {
                   16548:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16549:         }
                   16550:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16551:         $msg->attach(Type     => $type,
                   16552:                      Path     => $attachment_path,
                   16553:                      Filename => $file_name
                   16554:                      );
                   16555:     # Otherwise attach text if given
                   16556:     } elsif ($attachment_text) {
                   16557:         $msg->attach(Type => 'TEXT',
                   16558:                      Data => $attachment_text);
                   16559:     }
                   16560:     # Send it
                   16561:     $msg->send('sendmail');
                   16562: }
                   16563: 
                   16564: ############################################################
                   16565: ############################################################
                   16566: 
                   16567: =pod
                   16568: 
1.655     raeburn  16569: =head1 Course Catalog Routines
                   16570: 
                   16571: =over 4
                   16572: 
                   16573: =item * &gather_categories()
                   16574: 
                   16575: Converts category definitions - keys of categories hash stored in  
                   16576: coursecategories in configuration.db on the primary library server in a 
                   16577: domain - to an array.  Also generates javascript and idx hash used to 
                   16578: generate Domain Coordinator interface for editing Course Categories.
                   16579: 
                   16580: Inputs:
1.663     raeburn  16581: 
1.655     raeburn  16582: categories (reference to hash of category definitions).
1.663     raeburn  16583: 
1.655     raeburn  16584: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16585:       categories and subcategories).
1.663     raeburn  16586: 
1.655     raeburn  16587: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16588:       editing Course Categories).
1.663     raeburn  16589: 
1.655     raeburn  16590: jsarray (reference to array of categories used to create Javascript arrays for
                   16591:          Domain Coordinator interface for editing Course Categories).
                   16592: 
                   16593: Returns: nothing
                   16594: 
                   16595: Side effects: populates cats, idx and jsarray. 
                   16596: 
                   16597: =cut
                   16598: 
                   16599: sub gather_categories {
                   16600:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16601:     my %counters;
                   16602:     my $num = 0;
                   16603:     foreach my $item (keys(%{$categories})) {
                   16604:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16605:         if ($container eq '' && $depth == 0) {
                   16606:             $cats->[$depth][$categories->{$item}] = $cat;
                   16607:         } else {
                   16608:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16609:         }
                   16610:         my ($escitem,$tail) = split(/:/,$item,2);
                   16611:         if ($counters{$tail} eq '') {
                   16612:             $counters{$tail} = $num;
                   16613:             $num ++;
                   16614:         }
                   16615:         if (ref($idx) eq 'HASH') {
                   16616:             $idx->{$item} = $counters{$tail};
                   16617:         }
                   16618:         if (ref($jsarray) eq 'ARRAY') {
                   16619:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16620:         }
                   16621:     }
                   16622:     return;
                   16623: }
                   16624: 
                   16625: =pod
                   16626: 
                   16627: =item * &extract_categories()
                   16628: 
                   16629: Used to generate breadcrumb trails for course categories.
                   16630: 
                   16631: Inputs:
1.663     raeburn  16632: 
1.655     raeburn  16633: categories (reference to hash of category definitions).
1.663     raeburn  16634: 
1.655     raeburn  16635: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16636:       categories and subcategories).
1.663     raeburn  16637: 
1.655     raeburn  16638: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16639: 
1.655     raeburn  16640: allitems (reference to hash - key is category key 
                   16641:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16642: 
1.655     raeburn  16643: idx (reference to hash of counters used in Domain Coordinator interface for
                   16644:       editing Course Categories).
1.663     raeburn  16645: 
1.655     raeburn  16646: jsarray (reference to array of categories used to create Javascript arrays for
                   16647:          Domain Coordinator interface for editing Course Categories).
                   16648: 
1.665     raeburn  16649: subcats (reference to hash of arrays containing all subcategories within each 
                   16650:          category, -recursive)
                   16651: 
1.1321    raeburn  16652: maxd (reference to hash used to hold max depth for all top-level categories).
                   16653: 
1.655     raeburn  16654: Returns: nothing
                   16655: 
                   16656: Side effects: populates trails and allitems hash references.
                   16657: 
                   16658: =cut
                   16659: 
                   16660: sub extract_categories {
1.1321    raeburn  16661:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16662:     if (ref($categories) eq 'HASH') {
                   16663:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16664:         if (ref($cats->[0]) eq 'ARRAY') {
                   16665:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16666:                 my $name = $cats->[0][$i];
                   16667:                 my $item = &escape($name).'::0';
                   16668:                 my $trailstr;
                   16669:                 if ($name eq 'instcode') {
                   16670:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16671:                 } elsif ($name eq 'communities') {
                   16672:                     $trailstr = &mt('Communities');
1.1239    raeburn  16673:                 } elsif ($name eq 'placement') {
                   16674:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16675:                 } else {
                   16676:                     $trailstr = $name;
                   16677:                 }
                   16678:                 if ($allitems->{$item} eq '') {
                   16679:                     push(@{$trails},$trailstr);
                   16680:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16681:                 }
                   16682:                 my @parents = ($name);
                   16683:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16684:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16685:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16686:                         if (ref($subcats) eq 'HASH') {
                   16687:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16688:                         }
1.1321    raeburn  16689:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16690:                     }
                   16691:                 } else {
                   16692:                     if (ref($subcats) eq 'HASH') {
                   16693:                         $subcats->{$item} = [];
1.655     raeburn  16694:                     }
1.1321    raeburn  16695:                     if (ref($maxd) eq 'HASH') {
                   16696:                         $maxd->{$name} = 1;
                   16697:                     }
1.655     raeburn  16698:                 }
                   16699:             }
                   16700:         }
                   16701:     }
                   16702:     return;
                   16703: }
                   16704: 
                   16705: =pod
                   16706: 
1.1162    raeburn  16707: =item * &recurse_categories()
1.655     raeburn  16708: 
                   16709: Recursively used to generate breadcrumb trails for course categories.
                   16710: 
                   16711: Inputs:
1.663     raeburn  16712: 
1.655     raeburn  16713: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16714:       categories and subcategories).
1.663     raeburn  16715: 
1.655     raeburn  16716: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16717: 
                   16718: category (current course category, for which breadcrumb trail is being generated).
                   16719: 
                   16720: trails (reference to array of breadcrumb trails for each category).
                   16721: 
1.655     raeburn  16722: allitems (reference to hash - key is category key
                   16723:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16724: 
1.655     raeburn  16725: parents (array containing containers directories for current category, 
                   16726:          back to top level). 
                   16727: 
                   16728: Returns: nothing
                   16729: 
                   16730: Side effects: populates trails and allitems hash references
                   16731: 
                   16732: =cut
                   16733: 
                   16734: sub recurse_categories {
1.1321    raeburn  16735:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16736:     my $shallower = $depth - 1;
                   16737:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16738:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16739:             my $name = $cats->[$depth]{$category}[$k];
                   16740:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16741:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16742:             if ($allitems->{$item} eq '') {
                   16743:                 push(@{$trails},$trailstr);
                   16744:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16745:             }
                   16746:             my $deeper = $depth+1;
                   16747:             push(@{$parents},$category);
1.665     raeburn  16748:             if (ref($subcats) eq 'HASH') {
                   16749:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16750:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16751:                     my $higher;
                   16752:                     if ($j > 0) {
                   16753:                         $higher = &escape($parents->[$j]).':'.
                   16754:                                   &escape($parents->[$j-1]).':'.$j;
                   16755:                     } else {
                   16756:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16757:                     }
                   16758:                     push(@{$subcats->{$higher}},$subcat);
                   16759:                 }
                   16760:             }
                   16761:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16762:                                 $subcats,$maxd);
1.655     raeburn  16763:             pop(@{$parents});
                   16764:         }
                   16765:     } else {
                   16766:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16767:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16768:         if ($allitems->{$item} eq '') {
                   16769:             push(@{$trails},$trailstr);
                   16770:             $allitems->{$item} = scalar(@{$trails})-1;
                   16771:         }
1.1321    raeburn  16772:         if (ref($maxd) eq 'HASH') {
                   16773:             if ($depth > $maxd->{$parents->[0]}) {
                   16774:                 $maxd->{$parents->[0]} = $depth;
                   16775:             }
                   16776:         }
1.655     raeburn  16777:     }
                   16778:     return;
                   16779: }
                   16780: 
1.663     raeburn  16781: =pod
                   16782: 
1.1162    raeburn  16783: =item * &assign_categories_table()
1.663     raeburn  16784: 
                   16785: Create a datatable for display of hierarchical categories in a domain,
                   16786: with checkboxes to allow a course to be categorized. 
                   16787: 
                   16788: Inputs:
                   16789: 
                   16790: cathash - reference to hash of categories defined for the domain (from
                   16791:           configuration.db)
                   16792: 
                   16793: currcat - scalar with an & separated list of categories assigned to a course. 
                   16794: 
1.919     raeburn  16795: type    - scalar contains course type (Course or Community).
                   16796: 
1.1260    raeburn  16797: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16798:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16799: 
1.663     raeburn  16800: Returns: $output (markup to be displayed) 
                   16801: 
                   16802: =cut
                   16803: 
                   16804: sub assign_categories_table {
1.1259    raeburn  16805:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16806:     my $output;
                   16807:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16808:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16809:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16810:         $maxdepth = scalar(@cats);
                   16811:         if (@cats > 0) {
                   16812:             my $itemcount = 0;
                   16813:             if (ref($cats[0]) eq 'ARRAY') {
                   16814:                 my @currcategories;
                   16815:                 if ($currcat ne '') {
                   16816:                     @currcategories = split('&',$currcat);
                   16817:                 }
1.919     raeburn  16818:                 my $table;
1.663     raeburn  16819:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16820:                     my $parent = $cats[0][$i];
1.919     raeburn  16821:                     next if ($parent eq 'instcode');
                   16822:                     if ($type eq 'Community') {
                   16823:                         next unless ($parent eq 'communities');
1.1239    raeburn  16824:                     } elsif ($type eq 'Placement') {
                   16825:                         next unless ($parent eq 'placement');
1.919     raeburn  16826:                     } else {
1.1239    raeburn  16827:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16828:                     }
1.663     raeburn  16829:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16830:                     my $item = &escape($parent).'::0';
                   16831:                     my $checked = '';
                   16832:                     if (@currcategories > 0) {
                   16833:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16834:                             $checked = ' checked="checked"';
1.663     raeburn  16835:                         }
                   16836:                     }
1.919     raeburn  16837:                     my $parent_title = $parent;
                   16838:                     if ($parent eq 'communities') {
                   16839:                         $parent_title = &mt('Communities');
1.1239    raeburn  16840:                     } elsif ($parent eq 'placement') {
                   16841:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16842:                     }
                   16843:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16844:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16845:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16846:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16847:                     my $depth = 1;
                   16848:                     push(@path,$parent);
1.1259    raeburn  16849:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16850:                     pop(@path);
1.919     raeburn  16851:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16852:                     $itemcount ++;
                   16853:                 }
1.919     raeburn  16854:                 if ($itemcount) {
                   16855:                     $output = &Apache::loncommon::start_data_table().
                   16856:                               $table.
                   16857:                               &Apache::loncommon::end_data_table();
                   16858:                 }
1.663     raeburn  16859:             }
                   16860:         }
                   16861:     }
                   16862:     return $output;
                   16863: }
                   16864: 
                   16865: =pod
                   16866: 
1.1162    raeburn  16867: =item * &assign_category_rows()
1.663     raeburn  16868: 
                   16869: Create a datatable row for display of nested categories in a domain,
                   16870: with checkboxes to allow a course to be categorized,called recursively.
                   16871: 
                   16872: Inputs:
                   16873: 
                   16874: itemcount - track row number for alternating colors
                   16875: 
                   16876: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16877:       categories and subcategories.
                   16878: 
                   16879: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16880: 
                   16881: parent - parent of current category item
                   16882: 
                   16883: path - Array containing all categories back up through the hierarchy from the
                   16884:        current category to the top level.
                   16885: 
                   16886: currcategories - reference to array of current categories assigned to the course
                   16887: 
1.1260    raeburn  16888: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16889:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16890: 
1.663     raeburn  16891: Returns: $output (markup to be displayed).
                   16892: 
                   16893: =cut
                   16894: 
                   16895: sub assign_category_rows {
1.1259    raeburn  16896:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16897:     my ($text,$name,$item,$chgstr);
                   16898:     if (ref($cats) eq 'ARRAY') {
                   16899:         my $maxdepth = scalar(@{$cats});
                   16900:         if (ref($cats->[$depth]) eq 'HASH') {
                   16901:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16902:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16903:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16904:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16905:                 for (my $j=0; $j<$numchildren; $j++) {
                   16906:                     $name = $cats->[$depth]{$parent}[$j];
                   16907:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16908:                     my $deeper = $depth+1;
                   16909:                     my $checked = '';
                   16910:                     if (ref($currcategories) eq 'ARRAY') {
                   16911:                         if (@{$currcategories} > 0) {
                   16912:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16913:                                 $checked = ' checked="checked"';
1.663     raeburn  16914:                             }
                   16915:                         }
                   16916:                     }
1.664     raeburn  16917:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16918:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16919:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16920:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16921:                              '</td><td>';
1.663     raeburn  16922:                     if (ref($path) eq 'ARRAY') {
                   16923:                         push(@{$path},$name);
1.1259    raeburn  16924:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16925:                         pop(@{$path});
                   16926:                     }
                   16927:                     $text .= '</td></tr>';
                   16928:                 }
                   16929:                 $text .= '</table></td>';
                   16930:             }
                   16931:         }
                   16932:     }
                   16933:     return $text;
                   16934: }
                   16935: 
1.1181    raeburn  16936: =pod
                   16937: 
                   16938: =back
                   16939: 
                   16940: =cut
                   16941: 
1.655     raeburn  16942: ############################################################
                   16943: ############################################################
                   16944: 
                   16945: 
1.443     albertel 16946: sub commit_customrole {
1.1408    raeburn  16947:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16948:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16949:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16950:                      $context,$othdomby,$requester);
1.630     raeburn  16951:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16952:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16953:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16954:     if (wantarray) {
                   16955:         return ($output,$result);
                   16956:     } else {
                   16957:         return $output;
                   16958:     }
1.443     albertel 16959: }
                   16960: 
                   16961: sub commit_standardrole {
1.1408    raeburn  16962:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   16963:         $othdomby,$requester) = @_;
1.1399    raeburn  16964:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  16965:     if ($context eq 'auto') {
                   16966:         $linefeed = "\n";
                   16967:     } else {
                   16968:         $linefeed = "<br />\n";
                   16969:     }  
1.443     albertel 16970:     if ($three eq 'st') {
1.1399    raeburn  16971:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  16972:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   16973:                                       $requester);
1.541     raeburn  16974:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16975:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16976:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16977:         } else {
1.541     raeburn  16978:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16979:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16980:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16981:             if ($context eq 'auto') {
                   16982:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16983:             } else {
                   16984:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16985:                &mt('Add to classlist').': <b>ok</b>';
                   16986:             }
                   16987:             $output .= $linefeed;
1.443     albertel 16988:         }
                   16989:     } else {
                   16990:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16991:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16992:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  16993:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   16994:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  16995:         if ($context eq 'auto') {
                   16996:             $output .= $result.$linefeed;
                   16997:         } else {
                   16998:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16999:         }
1.443     albertel 17000:     }
1.1399    raeburn  17001:     if (wantarray) {
                   17002:         return ($output,$result);
                   17003:     } else {
                   17004:         return $output;
                   17005:     }
1.443     albertel 17006: }
                   17007: 
                   17008: sub commit_studentrole {
1.1116    raeburn  17009:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  17010:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  17011:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  17012:     if ($context eq 'auto') {
                   17013:         $linefeed = "\n";
                   17014:     } else {
                   17015:         $linefeed = '<br />'."\n";
                   17016:     }
1.443     albertel 17017:     if (defined($one) && defined($two)) {
                   17018:         my $cid=$one.'_'.$two;
                   17019:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   17020:         my $secchange = 0;
                   17021:         my $expire_role_result;
                   17022:         my $modify_section_result;
1.628     raeburn  17023:         if ($oldsec ne '-1') { 
                   17024:             if ($oldsec ne $sec) {
1.443     albertel 17025:                 $secchange = 1;
1.628     raeburn  17026:                 my $now = time;
1.443     albertel 17027:                 my $uurl='/'.$cid;
                   17028:                 $uurl=~s/\_/\//g;
                   17029:                 if ($oldsec) {
                   17030:                     $uurl.='/'.$oldsec;
                   17031:                 }
1.626     raeburn  17032:                 $oldsecurl = $uurl;
1.628     raeburn  17033:                 $expire_role_result = 
1.1408    raeburn  17034:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   17035:                                                 '','','',$context,$othdomby,$requester);
                   17036:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  17037:                     if ($expire_role_result eq 'refused') {
                   17038:                         my @roles = ('st');
                   17039:                         my @statuses = ('previous');
                   17040:                         my @roledoms = ($one);
                   17041:                         my $withsec = 1;
                   17042:                         my %roleshash = 
                   17043:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   17044:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   17045:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   17046:                             my ($oldstart,$oldend) = 
                   17047:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   17048:                             if ($oldend > 0 && $oldend <= $now) {
                   17049:                                 $expire_role_result = 'ok';
                   17050:                             }
                   17051:                         }
                   17052:                     }
                   17053:                 }
1.443     albertel 17054:                 $result = $expire_role_result;
                   17055:             }
                   17056:         }
                   17057:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  17058:             $modify_section_result = 
                   17059:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   17060:                                                            undef,undef,undef,$sec,
                   17061:                                                            $end,$start,'','',$cid,
1.1408    raeburn  17062:                                                            '',$context,$credits,'',
                   17063:                                                            $othdomby,$requester);
1.443     albertel 17064:             if ($modify_section_result =~ /^ok/) {
                   17065:                 if ($secchange == 1) {
1.628     raeburn  17066:                     if ($sec eq '') {
                   17067:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   17068:                     } else {
                   17069:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   17070:                     }
1.443     albertel 17071:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  17072:                     if ($sec eq '') {
                   17073:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   17074:                     } else {
                   17075:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17076:                     }
1.443     albertel 17077:                 } else {
1.628     raeburn  17078:                     if ($sec eq '') {
                   17079:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   17080:                     } else {
                   17081:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   17082:                     }
1.443     albertel 17083:                 }
                   17084:             } else {
1.1115    raeburn  17085:                 if ($secchange) { 
1.628     raeburn  17086:                     $$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;
                   17087:                 } else {
                   17088:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   17089:                 }
1.443     albertel 17090:             }
                   17091:             $result = $modify_section_result;
                   17092:         } elsif ($secchange == 1) {
1.628     raeburn  17093:             if ($oldsec eq '') {
1.1103    raeburn  17094:                 $$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  17095:             } else {
                   17096:                 $$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;
                   17097:             }
1.626     raeburn  17098:             if ($expire_role_result eq 'refused') {
                   17099:                 my $newsecurl = '/'.$cid;
                   17100:                 $newsecurl =~ s/\_/\//g;
                   17101:                 if ($sec ne '') {
                   17102:                     $newsecurl.='/'.$sec;
                   17103:                 }
                   17104:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   17105:                     if ($sec eq '') {
                   17106:                         $$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;
                   17107:                     } else {
                   17108:                         $$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;
                   17109:                     }
                   17110:                 }
                   17111:             }
1.443     albertel 17112:         }
                   17113:     } else {
1.626     raeburn  17114:         $$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 17115:         $result = "error: incomplete course id\n";
                   17116:     }
                   17117:     return $result;
                   17118: }
                   17119: 
1.1108    raeburn  17120: sub show_role_extent {
                   17121:     my ($scope,$context,$role) = @_;
                   17122:     $scope =~ s{^/}{};
                   17123:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   17124:     push(@courseroles,'co');
                   17125:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   17126:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   17127:         $scope =~ s{/}{_};
                   17128:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   17129:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   17130:         my ($audom,$auname) = split(/\//,$scope);
                   17131:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   17132:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   17133:     } else {
                   17134:         $scope =~ s{/$}{};
                   17135:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   17136:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   17137:     }
                   17138: }
                   17139: 
1.443     albertel 17140: ############################################################
                   17141: ############################################################
                   17142: 
1.566     albertel 17143: sub check_clone {
1.578     raeburn  17144:     my ($args,$linefeed) = @_;
1.566     albertel 17145:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   17146:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   17147:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  17148:     my $clonetitle;
                   17149:     my @clonemsg;
1.566     albertel 17150:     my $can_clone = 0;
1.944     raeburn  17151:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  17152:     if ($lctype ne 'community') {
                   17153:         $lctype = 'course';
                   17154:     }
1.566     albertel 17155:     if ($clonehome eq 'no_host') {
1.944     raeburn  17156:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17157:             push(@clonemsg,({
                   17158:                               mt => 'No new community created.',
                   17159:                               args => [],
                   17160:                             },
                   17161:                             {
                   17162:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   17163:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17164:                             }));
1.908     raeburn  17165:         } else {
1.1344    raeburn  17166:             push(@clonemsg,({
                   17167:                               mt => 'No new course created.',
                   17168:                               args => [],
                   17169:                             },
                   17170:                             {
                   17171:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17172:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17173:                             }));
                   17174:         }
1.566     albertel 17175:     } else {
                   17176: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17177:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17178:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17179:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17180:                 push(@clonemsg,({
                   17181:                                   mt => 'No new community created.',
                   17182:                                   args => [],
                   17183:                                 },
                   17184:                                 {
                   17185:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17186:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17187:                                 }));
                   17188:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17189:             }
                   17190:         }
1.1262    raeburn  17191: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17192:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17193: 	    $can_clone = 1;
                   17194: 	} else {
1.1221    raeburn  17195: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17196: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17197:             if ($clonehash{'cloners'} eq '') {
                   17198:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17199:                 if ($domdefs{'canclone'}) {
                   17200:                     unless ($domdefs{'canclone'} eq 'none') {
                   17201:                         if ($domdefs{'canclone'} eq 'domain') {
                   17202:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17203:                                 $can_clone = 1;
                   17204:                             }
                   17205:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17206:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17207:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17208:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17209:                                 $can_clone = 1;
                   17210:                             }
                   17211:                         }
                   17212:                     }
                   17213:                 }
1.578     raeburn  17214:             } else {
1.1221    raeburn  17215: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17216:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17217:                     $can_clone = 1;
1.1221    raeburn  17218:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17219:                     $can_clone = 1;
1.1225    raeburn  17220:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17221:                     $can_clone = 1;
1.1221    raeburn  17222:                 }
                   17223:                 unless ($can_clone) {
1.1225    raeburn  17224:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17225:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17226:                         my (%gotdomdefaults,%gotcodedefaults);
                   17227:                         foreach my $cloner (@cloners) {
                   17228:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17229:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17230:                                 my (%codedefaults,@code_order);
                   17231:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17232:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17233:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17234:                                     }
                   17235:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17236:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17237:                                     }
                   17238:                                 } else {
                   17239:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17240:                                                                             \%codedefaults,
                   17241:                                                                             \@code_order);
                   17242:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17243:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17244:                                 }
                   17245:                                 if (@code_order > 0) {
                   17246:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17247:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17248:                                                                                 $args->{'crscode'})) {
                   17249:                                         $can_clone = 1;
                   17250:                                         last;
                   17251:                                     }
                   17252:                                 }
                   17253:                             }
                   17254:                         }
                   17255:                     }
1.1225    raeburn  17256:                 }
                   17257:             }
                   17258:             unless ($can_clone) {
                   17259:                 my $ccrole = 'cc';
                   17260:                 if ($args->{'crstype'} eq 'Community') {
                   17261:                     $ccrole = 'co';
                   17262:                 }
                   17263: 	        my %roleshash =
                   17264: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17265: 					          $args->{'ccdomain'},
                   17266:                                                   'userroles',['active'],[$ccrole],
                   17267: 					          [$args->{'clonedomain'}]);
                   17268: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17269:                     $can_clone = 1;
                   17270:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17271:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17272:                     $can_clone = 1;
1.1221    raeburn  17273:                 }
                   17274:             }
                   17275:             unless ($can_clone) {
                   17276:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17277:                     push(@clonemsg,({
                   17278:                                       mt => 'No new community created.',
                   17279:                                       args => [],
                   17280:                                     },
                   17281:                                     {
                   17282:                                       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]).',
                   17283:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17284:                                     }));
1.942     raeburn  17285:                 } else {
1.1344    raeburn  17286:                     push(@clonemsg,({
                   17287:                                       mt => 'No new course created.',
                   17288:                                       args => [],
                   17289:                                     },
                   17290:                                     {
                   17291:                                       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]).',
                   17292:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17293:                                     }));
1.1221    raeburn  17294:                 }
1.566     albertel 17295: 	    }
1.578     raeburn  17296:         }
1.566     albertel 17297:     }
1.1344    raeburn  17298:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17299: }
                   17300: 
1.444     albertel 17301: sub construct_course {
1.1262    raeburn  17302:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17303:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17304:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17305:     my $linefeed =  '<br />'."\n";
                   17306:     if ($context eq 'auto') {
                   17307:         $linefeed = "\n";
                   17308:     }
1.566     albertel 17309: 
                   17310: #
                   17311: # Are we cloning?
                   17312: #
1.1344    raeburn  17313:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17314:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17315: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17316:         if (!$can_clone) {
1.1344    raeburn  17317: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17318: 	}
                   17319:     }
                   17320: 
1.444     albertel 17321: #
                   17322: # Open course
                   17323: #
1.1239    raeburn  17324:     my $showncrstype;
                   17325:     if ($args->{'crstype'} eq 'Placement') {
                   17326:         $showncrstype = 'placement test'; 
                   17327:     } else {  
                   17328:         $showncrstype = lc($args->{'crstype'});
                   17329:     }
1.444     albertel 17330:     my %cenv=();
                   17331:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17332:                                              $args->{'cdescr'},
                   17333:                                              $args->{'curl'},
                   17334:                                              $args->{'course_home'},
                   17335:                                              $args->{'nonstandard'},
                   17336:                                              $args->{'crscode'},
                   17337:                                              $args->{'ccuname'}.':'.
                   17338:                                              $args->{'ccdomain'},
1.882     raeburn  17339:                                              $args->{'crstype'},
1.1344    raeburn  17340:                                              $cnum,$context,$category,
                   17341:                                              $callercontext);
1.444     albertel 17342: 
                   17343:     # Note: The testing routines depend on this being output; see 
                   17344:     # Utils::Course. This needs to at least be output as a comment
                   17345:     # if anyone ever decides to not show this, and Utils::Course::new
                   17346:     # will need to be suitably modified.
1.1344    raeburn  17347:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17348:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17349:     } else {
                   17350:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17351:     }
1.943     raeburn  17352:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17353:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17354:     }
                   17355: 
1.444     albertel 17356: #
                   17357: # Check if created correctly
                   17358: #
1.479     albertel 17359:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17360:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17361:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17362:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17363:             $outcome .= &mt_user($user_lh,
                   17364:                             'Course creation failed, unrecognized course home server.');
                   17365:         } else {
                   17366:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17367:         }
                   17368:         $outcome .= $linefeed;
                   17369:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17370:     }
1.541     raeburn  17371:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17372: 
1.444     albertel 17373: #
1.566     albertel 17374: # Do the cloning
                   17375: #   
1.1344    raeburn  17376:     my @clonemsg;
1.566     albertel 17377:     if ($can_clone && $cloneid) {
1.1344    raeburn  17378:         push(@clonemsg,
                   17379:                       {
                   17380:                           mt => 'Created [_1] by cloning from [_2]',
                   17381:                           args => [$showncrstype,$clonetitle],
                   17382:                       });
1.566     albertel 17383: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17384: # Copy all files
1.1344    raeburn  17385:         my @info =
                   17386: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17387: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17388:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17389:                                                      $args->{'tinyurls'});
                   17390:         if (@info) {
                   17391:             push(@clonemsg,@info);
                   17392:         }
1.444     albertel 17393: # Restore URL
1.566     albertel 17394: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17395: # Restore title
1.566     albertel 17396: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17397: # Restore creation date, creator and creation context.
                   17398:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17399:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17400:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17401: # Mark as cloned
1.566     albertel 17402: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17403: # Need to clone grading mode
                   17404:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17405:         $cenv{'grading'}=$newenv{'grading'};
                   17406: # Do not clone these environment entries
                   17407:         &Apache::lonnet::del('environment',
                   17408:                   ['default_enrollment_start_date',
                   17409:                    'default_enrollment_end_date',
                   17410:                    'question.email',
                   17411:                    'policy.email',
                   17412:                    'comment.email',
                   17413:                    'pch.users.denied',
1.725     raeburn  17414:                    'plc.users.denied',
                   17415:                    'hidefromcat',
1.1121    raeburn  17416:                    'checkforpriv',
1.1355    raeburn  17417:                    'categories'],
1.638     www      17418:                    $$crsudom,$$crsunum);
1.1170    raeburn  17419:         if ($args->{'textbook'}) {
                   17420:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17421:         }
1.444     albertel 17422:     }
1.566     albertel 17423: 
1.444     albertel 17424: #
                   17425: # Set environment (will override cloned, if existing)
                   17426: #
                   17427:     my @sections = ();
                   17428:     my @xlists = ();
                   17429:     if ($args->{'crstype'}) {
                   17430:         $cenv{'type'}=$args->{'crstype'};
                   17431:     }
1.1371    raeburn  17432:     if ($args->{'lti'}) {
                   17433:         $cenv{'internal.lti'}=$args->{'lti'};
                   17434:     }
1.444     albertel 17435:     if ($args->{'crsid'}) {
                   17436:         $cenv{'courseid'}=$args->{'crsid'};
                   17437:     }
                   17438:     if ($args->{'crscode'}) {
                   17439:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17440:     }
                   17441:     if ($args->{'crsquota'} ne '') {
                   17442:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17443:     } else {
                   17444:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17445:     }
                   17446:     if ($args->{'ccuname'}) {
                   17447:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17448:                                         ':'.$args->{'ccdomain'};
                   17449:     } else {
                   17450:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17451:     }
1.1116    raeburn  17452:     if ($args->{'defaultcredits'}) {
                   17453:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17454:     }
1.444     albertel 17455:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17456:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17457:     if ($args->{'crssections'}) {
                   17458:         $cenv{'internal.sectionnums'} = '';
                   17459:         if ($args->{'crssections'} =~ m/,/) {
                   17460:             @sections = split/,/,$args->{'crssections'};
                   17461:         } else {
                   17462:             $sections[0] = $args->{'crssections'};
                   17463:         }
                   17464:         if (@sections > 0) {
                   17465:             foreach my $item (@sections) {
                   17466:                 my ($sec,$gp) = split/:/,$item;
                   17467:                 my $class = $args->{'crscode'}.$sec;
                   17468:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17469:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17470:                 if ($addcheck eq 'ok') {
                   17471:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17472:                         push(@oklcsecs,$gp);
                   17473:                     }
                   17474:                 } else {
1.1263    raeburn  17475:                     push(@badclasses,$class);
1.444     albertel 17476:                 }
                   17477:             }
                   17478:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17479:         }
                   17480:     }
                   17481: # do not hide course coordinator from staff listing, 
                   17482: # even if privileged
                   17483:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17484: # add course coordinator's domain to domains to check for privileged users
                   17485: # if different to course domain
                   17486:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17487:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17488:     }
1.444     albertel 17489: # add crosslistings
                   17490:     if ($args->{'crsxlist'}) {
                   17491:         $cenv{'internal.crosslistings'}='';
                   17492:         if ($args->{'crsxlist'} =~ m/,/) {
                   17493:             @xlists = split/,/,$args->{'crsxlist'};
                   17494:         } else {
                   17495:             $xlists[0] = $args->{'crsxlist'};
                   17496:         }
                   17497:         if (@xlists > 0) {
                   17498:             foreach my $item (@xlists) {
                   17499:                 my ($xl,$gp) = split/:/,$item;
                   17500:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17501:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17502:                 if ($addcheck eq 'ok') {
                   17503:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17504:                         push(@oklcsecs,$gp);
                   17505:                     }
                   17506:                 } else {
1.1263    raeburn  17507:                     push(@badclasses,$xl);
1.444     albertel 17508:                 }
                   17509:             }
                   17510:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17511:         }
                   17512:     }
                   17513:     if ($args->{'autoadds'}) {
                   17514:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17515:     }
                   17516:     if ($args->{'autodrops'}) {
                   17517:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17518:     }
                   17519: # check for notification of enrollment changes
                   17520:     my @notified = ();
                   17521:     if ($args->{'notify_owner'}) {
                   17522:         if ($args->{'ccuname'} ne '') {
                   17523:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17524:         }
                   17525:     }
                   17526:     if ($args->{'notify_dc'}) {
                   17527:         if ($uname ne '') { 
1.630     raeburn  17528:             push(@notified,$uname.':'.$udom);
1.444     albertel 17529:         }
                   17530:     }
                   17531:     if (@notified > 0) {
                   17532:         my $notifylist;
                   17533:         if (@notified > 1) {
                   17534:             $notifylist = join(',',@notified);
                   17535:         } else {
                   17536:             $notifylist = $notified[0];
                   17537:         }
                   17538:         $cenv{'internal.notifylist'} = $notifylist;
                   17539:     }
                   17540:     if (@badclasses > 0) {
                   17541:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17542:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17543:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17544:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17545:         );
1.1264    raeburn  17546:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17547:                            &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  17548:         if ($context eq 'auto') {
                   17549:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17550:         } else {
1.566     albertel 17551:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17552:         }
                   17553:         foreach my $item (@badclasses) {
1.541     raeburn  17554:             if ($context eq 'auto') {
1.1261    raeburn  17555:                 $outcome .= " - $item\n";
1.541     raeburn  17556:             } else {
1.1261    raeburn  17557:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17558:             }
1.1261    raeburn  17559:         }
                   17560:         if ($context eq 'auto') {
                   17561:             $outcome .= $linefeed;
                   17562:         } else {
                   17563:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17564:         } 
1.444     albertel 17565:     }
                   17566:     if ($args->{'no_end_date'}) {
                   17567:         $args->{'endaccess'} = 0;
                   17568:     }
1.1412    raeburn  17569: #  If an official course with institutional sections is created by cloning 
                   17570: #  an existing course, section-specific hiding of course totals in student's
                   17571: #  view of grades as copied from cloned course, will be checked for valid 
                   17572: #  sections.
                   17573:     if (($can_clone && $cloneid) &&
                   17574:         ($cenv{'internal.coursecode'} ne '') &&
                   17575:         ($cenv{'grading'} eq 'standard') &&
                   17576:         ($cenv{'hidetotals'} ne '') &&
                   17577:         ($cenv{'hidetotals'} ne 'all')) {
                   17578:         my @hidesecs;
                   17579:         my $deletehidetotals;
                   17580:         if (@oklcsecs) {
                   17581:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17582:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17583:                     push(@hidesecs,$sec);
                   17584:                 }
                   17585:             }
                   17586:             if (@hidesecs) {
                   17587:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17588:             } else {
                   17589:                 $deletehidetotals = 1;
                   17590:             }
                   17591:         } else {
                   17592:             $deletehidetotals = 1;
                   17593:         }
                   17594:         if ($deletehidetotals) {
                   17595:             delete($cenv{'hidetotals'});
                   17596:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17597:         }
                   17598:     }
1.444     albertel 17599:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17600:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17601:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17602:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17603:     if ($args->{'showphotos'}) {
                   17604:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17605:     }
                   17606:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17607:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17608:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17609:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17610:             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'); 
                   17611:             if ($context eq 'auto') {
                   17612:                 $outcome .= $krb_msg;
                   17613:             } else {
1.566     albertel 17614:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17615:             }
                   17616:             $outcome .= $linefeed;
1.444     albertel 17617:         }
                   17618:     }
                   17619:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17620:        if ($args->{'setpolicy'}) {
                   17621:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17622:        }
                   17623:        if ($args->{'setcontent'}) {
                   17624:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17625:        }
1.1251    raeburn  17626:        if ($args->{'setcomment'}) {
                   17627:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17628:        }
1.444     albertel 17629:     }
                   17630:     if ($args->{'reshome'}) {
                   17631: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17632: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17633:     }
                   17634: #
                   17635: # course has keyed access
                   17636: #
                   17637:     if ($args->{'setkeys'}) {
                   17638:        $cenv{'keyaccess'}='yes';
                   17639:     }
                   17640: # if specified, key authority is not course, but user
                   17641: # only active if keyaccess is yes
                   17642:     if ($args->{'keyauth'}) {
1.487     albertel 17643: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17644: 	$user = &LONCAPA::clean_username($user);
                   17645: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17646: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17647: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17648: 	}
                   17649:     }
                   17650: 
1.1166    raeburn  17651: #
1.1167    raeburn  17652: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17653: #
                   17654:     if ($args->{'uniquecode'}) {
                   17655:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17656:         if ($code) {
                   17657:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17658:             my %crsinfo =
                   17659:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17660:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17661:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17662:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17663:             } 
1.1166    raeburn  17664:             if (ref($coderef)) {
                   17665:                 $$coderef = $code;
                   17666:             }
                   17667:         }
                   17668:     }
                   17669: 
1.444     albertel 17670:     if ($args->{'disresdis'}) {
                   17671:         $cenv{'pch.roles.denied'}='st';
                   17672:     }
                   17673:     if ($args->{'disablechat'}) {
                   17674:         $cenv{'plc.roles.denied'}='st';
                   17675:     }
                   17676: 
                   17677:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17678:     # course
                   17679:     $cenv{'course.helper.not.run'} = 1;
                   17680:     #
                   17681:     # Use new Randomseed
                   17682:     #
                   17683:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17684:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17685:     #
                   17686:     # The encryption code and receipt prefix for this course
                   17687:     #
                   17688:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17689:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17690:     #
                   17691:     # By default, use standard grading
                   17692:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17693: 
1.541     raeburn  17694:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17695:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17696: #
                   17697: # Open all assignments
                   17698: #
                   17699:     if ($args->{'openall'}) {
1.1341    raeburn  17700:        my $opendate = time;
                   17701:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17702:            $opendate = $args->{'openallfrom'};
                   17703:        }
1.444     albertel 17704:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17705:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17706:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17707:        $outcome .= &mt('All assignments open starting [_1]',
                   17708:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17709:                    &Apache::lonnet::cput
                   17710:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17711:    }
                   17712: #
                   17713: # Set first page
                   17714: #
                   17715:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17716: 	    || ($cloneid)) {
                   17717: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17718: 
                   17719: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17720:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17721: 
1.444     albertel 17722:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17723:         my $title; my $url;
                   17724:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17725: 	    $title=&mt('Syllabus');
1.444     albertel 17726:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17727:         } else {
1.963     raeburn  17728:             $title=&mt('Table of Contents');
1.444     albertel 17729:             $url='/adm/navmaps';
                   17730:         }
1.445     albertel 17731: 
                   17732:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17733: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17734: 
                   17735: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17736:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17737:     }
1.566     albertel 17738: 
1.1237    raeburn  17739: # 
                   17740: # Set params for Placement Tests
                   17741: #
1.1239    raeburn  17742:     if ($args->{'crstype'} eq 'Placement') {
                   17743:        my %storecontent; 
                   17744:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17745:        my %defaults = (
                   17746:                         buttonshide   => { value => 'yes',
                   17747:                                            type => 'string_yesno',},
                   17748:                         type          => { value => 'randomizetry',
                   17749:                                            type  => 'string_questiontype',},
                   17750:                         maxtries      => { value => 1,
                   17751:                                            type => 'int_pos',},
                   17752:                         problemstatus => { value => 'no',
                   17753:                                            type  => 'string_problemstatus',},
                   17754:                       );
                   17755:        foreach my $key (keys(%defaults)) {
                   17756:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17757:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17758:        }
1.1237    raeburn  17759:        &Apache::lonnet::cput
                   17760:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17761:     }
                   17762: 
1.1344    raeburn  17763:     return (1,$outcome,\@clonemsg);
1.444     albertel 17764: }
                   17765: 
1.1166    raeburn  17766: sub make_unique_code {
                   17767:     my ($cdom,$cnum) = @_;
                   17768:     # get lock on uniquecodes db
                   17769:     my $lockhash = {
                   17770:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17771:                                                   ':'.$env{'user.domain'},
                   17772:                    };
                   17773:     my $tries = 0;
                   17774:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17775:     my ($code,$error);
                   17776:   
                   17777:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17778:         $tries ++;
                   17779:         sleep 1;
                   17780:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17781:     }
                   17782:     if ($gotlock eq 'ok') {
                   17783:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17784:         my $gotcode;
                   17785:         my $attempts = 0;
                   17786:         while ((!$gotcode) && ($attempts < 100)) {
                   17787:             $code = &generate_code();
                   17788:             if (!exists($currcodes{$code})) {
                   17789:                 $gotcode = 1;
                   17790:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17791:                     $error = 'nostore';
                   17792:                 }
                   17793:             }
                   17794:             $attempts ++;
                   17795:         }
                   17796:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17797:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17798:     } else {
                   17799:         $error = 'nolock';
                   17800:     }
                   17801:     return ($code,$error);
                   17802: }
                   17803: 
                   17804: sub generate_code {
                   17805:     my $code;
                   17806:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17807:     for (my $i=0; $i<6; $i++) {
                   17808:         my $lettnum = int (rand 2);
                   17809:         my $item = '';
                   17810:         if ($lettnum) {
                   17811:             $item = $letts[int( rand(18) )];
                   17812:         } else {
                   17813:             $item = 1+int( rand(8) );
                   17814:         }
                   17815:         $code .= $item;
                   17816:     }
                   17817:     return $code;
                   17818: }
                   17819: 
1.444     albertel 17820: ############################################################
                   17821: ############################################################
                   17822: 
1.1237    raeburn  17823: # Community, Course and Placement Test
1.378     raeburn  17824: sub course_type {
                   17825:     my ($cid) = @_;
                   17826:     if (!defined($cid)) {
                   17827:         $cid = $env{'request.course.id'};
                   17828:     }
1.404     albertel 17829:     if (defined($env{'course.'.$cid.'.type'})) {
                   17830:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17831:     } else {
                   17832:         return 'Course';
1.377     raeburn  17833:     }
                   17834: }
1.156     albertel 17835: 
1.406     raeburn  17836: sub group_term {
                   17837:     my $crstype = &course_type();
                   17838:     my %names = (
                   17839:                   'Course' => 'group',
1.865     raeburn  17840:                   'Community' => 'group',
1.1237    raeburn  17841:                   'Placement' => 'group',
1.406     raeburn  17842:                 );
                   17843:     return $names{$crstype};
                   17844: }
                   17845: 
1.902     raeburn  17846: sub course_types {
1.1310    raeburn  17847:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17848:     my %typename = (
                   17849:                          official   => 'Official course',
                   17850:                          unofficial => 'Unofficial course',
                   17851:                          community  => 'Community',
1.1165    raeburn  17852:                          textbook   => 'Textbook course',
1.1237    raeburn  17853:                          placement  => 'Placement test',
1.1310    raeburn  17854:                          lti        => 'LTI provider',
1.902     raeburn  17855:                    );
                   17856:     return (\@types,\%typename);
                   17857: }
                   17858: 
1.156     albertel 17859: sub icon {
                   17860:     my ($file)=@_;
1.505     albertel 17861:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17862:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17863:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17864:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17865: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17866: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17867: 	            $curfext.".gif") {
                   17868: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17869: 		$curfext.".gif";
                   17870: 	}
                   17871:     }
1.249     albertel 17872:     return &lonhttpdurl($iconname);
1.154     albertel 17873: } 
1.84      albertel 17874: 
1.575     albertel 17875: sub lonhttpdurl {
1.692     www      17876: #
                   17877: # Had been used for "small fry" static images on separate port 8080.
                   17878: # Modify here if lightweight http functionality desired again.
                   17879: # Currently eliminated due to increasing firewall issues.
                   17880: #
1.575     albertel 17881:     my ($url)=@_;
1.692     www      17882:     return $url;
1.215     albertel 17883: }
                   17884: 
1.213     albertel 17885: sub connection_aborted {
                   17886:     my ($r)=@_;
                   17887:     $r->print(" ");$r->rflush();
                   17888:     my $c = $r->connection;
                   17889:     return $c->aborted();
                   17890: }
                   17891: 
1.221     foxr     17892: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17893: #    strings as 'strings'.
                   17894: sub escape_single {
1.221     foxr     17895:     my ($input) = @_;
1.223     albertel 17896:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17897:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17898:     return $input;
                   17899: }
1.223     albertel 17900: 
1.222     foxr     17901: #  Same as escape_single, but escape's "'s  This 
                   17902: #  can be used for  "strings"
                   17903: sub escape_double {
                   17904:     my ($input) = @_;
                   17905:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17906:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17907:     return $input;
                   17908: }
1.223     albertel 17909:  
1.222     foxr     17910: #   Escapes the last element of a full URL.
                   17911: sub escape_url {
                   17912:     my ($url)   = @_;
1.238     raeburn  17913:     my @urlslices = split(/\//, $url,-1);
1.369     www      17914:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17915:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17916: }
1.462     albertel 17917: 
1.820     raeburn  17918: sub compare_arrays {
                   17919:     my ($arrayref1,$arrayref2) = @_;
                   17920:     my (@difference,%count);
                   17921:     @difference = ();
                   17922:     %count = ();
                   17923:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17924:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17925:         foreach my $element (keys(%count)) {
                   17926:             if ($count{$element} == 1) {
                   17927:                 push(@difference,$element);
                   17928:             }
                   17929:         }
                   17930:     }
                   17931:     return @difference;
                   17932: }
                   17933: 
1.1322    raeburn  17934: sub lon_status_items {
                   17935:     my %defaults = (
                   17936:                      E         => 100,
                   17937:                      W         => 4,
                   17938:                      N         => 1,
1.1324    raeburn  17939:                      U         => 5,
1.1322    raeburn  17940:                      threshold => 200,
                   17941:                      sysmail   => 2500,
                   17942:                    );
                   17943:     my %names = (
                   17944:                    E => 'Errors',
                   17945:                    W => 'Warnings',
                   17946:                    N => 'Notices',
1.1324    raeburn  17947:                    U => 'Unsent',
1.1322    raeburn  17948:                 );
                   17949:     return (\%defaults,\%names);
                   17950: }
                   17951: 
1.817     bisitz   17952: # -------------------------------------------------------- Initialize user login
1.462     albertel 17953: sub init_user_environment {
1.463     albertel 17954:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17955:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17956: 
                   17957:     my $public=($username eq 'public' && $domain eq 'public');
                   17958: 
1.1415    raeburn  17959:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17960:         $coauthorenv);
1.462     albertel 17961:     my $now=time;
                   17962: 
                   17963:     if ($public) {
                   17964: 	my $max_public=100;
                   17965: 	my $oldest;
                   17966: 	my $oldest_time=0;
                   17967: 	for(my $next=1;$next<=$max_public;$next++) {
                   17968: 	    if (-e $lonids."/publicuser_$next.id") {
                   17969: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17970: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17971: 		    $oldest_time=$mtime;
                   17972: 		    $oldest=$next;
                   17973: 		}
                   17974: 	    } else {
                   17975: 		$cookie="publicuser_$next";
                   17976: 		last;
                   17977: 	    }
                   17978: 	}
                   17979: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17980:     } else {
1.1275    raeburn  17981: 	# See if old ID present, if so, remove if this isn't a robot,
                   17982: 	# killing any existing non-robot sessions
1.463     albertel 17983: 	if (!$args->{'robot'}) {
                   17984: 	    opendir(DIR,$lonids);
                   17985: 	    while ($filename=readdir(DIR)) {
                   17986: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17987:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17988:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17989:                         my $linkedfile;
1.1320    raeburn  17990:                         if (exists($oldenv{'user.linkedenv'})) {
                   17991:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17992:                         }
1.1320    raeburn  17993:                         untie(%oldenv);
                   17994:                         if (unlink("$lonids/$filename")) {
                   17995:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17996:                                 if (-l "$lonids/$linkedfile.id") {
                   17997:                                     unlink("$lonids/$linkedfile.id");
                   17998:                                 }
1.1295    raeburn  17999:                             }
                   18000:                         }
                   18001:                     } else {
                   18002:                         unlink($lonids.'/'.$filename);
                   18003:                     }
1.463     albertel 18004: 		}
1.462     albertel 18005: 	    }
1.463     albertel 18006: 	    closedir(DIR);
1.1204    raeburn  18007: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   18008:             my $namespace = 'nohist_courseeditor';
                   18009:             my $lockingkey = 'paste'."\0".'locked_num';
                   18010:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   18011:                                                 $domain,$username);
                   18012:             if (exists($lockhash{$lockingkey})) {
                   18013:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   18014:                 unless ($delresult eq 'ok') {
                   18015:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   18016:                 }
                   18017:             }
1.462     albertel 18018: 	}
                   18019: # Give them a new cookie
1.463     albertel 18020: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      18021: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 18022: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 18023:     
                   18024: # Initialize roles
                   18025: 
1.1414    raeburn  18026: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  18027:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 18028:     }
                   18029: # ------------------------------------ Check browser type and MathML capability
                   18030: 
1.1194    raeburn  18031:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   18032:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 18033: 
                   18034: # ------------------------------------------------------------- Get environment
                   18035: 
                   18036:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   18037:     my ($tmp) = keys(%userenv);
1.1275    raeburn  18038:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 18039: 	undef(%userenv);
                   18040:     }
                   18041:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   18042: 	$form->{'interface'}=$userenv{'interface'};
                   18043:     }
                   18044:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   18045: 
                   18046: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   18047:     foreach my $option ('interface','localpath','localres') {
                   18048:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 18049:     }
                   18050: # --------------------------------------------------------- Write first profile
                   18051: 
                   18052:     {
1.1350    raeburn  18053:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 18054: 	my %initial_env = 
                   18055: 	    ("user.name"          => $username,
                   18056: 	     "user.domain"        => $domain,
                   18057: 	     "user.home"          => $authhost,
                   18058: 	     "browser.type"       => $clientbrowser,
                   18059: 	     "browser.version"    => $clientversion,
                   18060: 	     "browser.mathml"     => $clientmathml,
                   18061: 	     "browser.unicode"    => $clientunicode,
                   18062: 	     "browser.os"         => $clientos,
1.1137    raeburn  18063:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  18064:              "browser.info"       => $clientinfo,
1.1194    raeburn  18065:              "browser.osversion"  => $clientosversion,
1.462     albertel 18066: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   18067: 	     "request.course.fn"  => '',
                   18068: 	     "request.course.uri" => '',
                   18069: 	     "request.course.sec" => '',
                   18070: 	     "request.role"       => 'cm',
                   18071: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  18072: 	     "request.host"       => $ip,);
1.462     albertel 18073: 
                   18074:         if ($form->{'localpath'}) {
                   18075: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   18076: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   18077:         }
                   18078: 	
                   18079: 	if ($form->{'interface'}) {
                   18080: 	    $form->{'interface'}=~s/\W//gs;
                   18081: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   18082: 	    $env{'browser.interface'}=$form->{'interface'};
                   18083: 	}
                   18084: 
1.1157    raeburn  18085:         if ($form->{'iptoken'}) {
                   18086:             my $lonhost = $r->dir_config('lonHostID');
                   18087:             $initial_env{"user.noloadbalance"} = $lonhost;
                   18088:             $env{'user.noloadbalance'} = $lonhost;
                   18089:         }
                   18090: 
1.1268    raeburn  18091:         if ($form->{'noloadbalance'}) {
                   18092:             my @hosts = &Apache::lonnet::current_machine_ids();
                   18093:             my $hosthere = $form->{'noloadbalance'};
                   18094:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   18095:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   18096:                 $env{'user.noloadbalance'} = $hosthere;
                   18097:             }
                   18098:         }
                   18099: 
1.1016    raeburn  18100:         unless ($domain eq 'public') {
1.1273    raeburn  18101:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   18102:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   18103: 
1.1414    raeburn  18104:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   18105:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  18106:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   18107:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   18108:             }
1.980     raeburn  18109: 
1.1311    raeburn  18110:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  18111:                 $userenv{'canrequest.'.$crstype} =
                   18112:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   18113:                                                       'reload','requestcourses',
                   18114:                                                       \%userenv,\%domdef,\%is_adv);
                   18115:             }
1.724     raeburn  18116: 
1.1418    raeburn  18117:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   18118:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   18119:                 if ($userenv{'authoreditors'}) {
                   18120:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   18121:                 } elsif ($domdef{'editors'} ne '') {
                   18122:                     $userenv{'editors'} = $domdef{'editors'};
                   18123:                 } else {
                   18124:                     $userenv{'editors'} = 'edit,xml';
                   18125:                 }
1.1431    raeburn  18126:                 if ($userenv{'authorarchive'}) {
                   18127:                     $userenv{'canarchive'} = 1;
                   18128:                 } elsif (($userenv{'authorarchive'} eq '') &&
                   18129:                          ($domdef{'archive'})) {
                   18130:                     $userenv{'canarchive'} = 1;
                   18131:                 }
1.1418    raeburn  18132:             }
                   18133: 
1.1273    raeburn  18134:             $userenv{'canrequest.author'} =
                   18135:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   18136:                                                   'reload','requestauthor',
1.980     raeburn  18137:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  18138:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   18139:                                                  $domain,$username);
                   18140:             my $reqstatus = $reqauthor{'author_status'};
                   18141:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   18142:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   18143:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   18144:                                                       $reqauthor{'author'}{'timestamp'};
                   18145:                 }
1.1092    raeburn  18146:             }
1.1287    raeburn  18147:             my ($types,$typename) = &course_types();
                   18148:             if (ref($types) eq 'ARRAY') {
                   18149:                 my @options = ('approval','validate','autolimit');
                   18150:                 my $optregex = join('|',@options);
                   18151:                 my (%willtrust,%trustchecked);
                   18152:                 foreach my $type (@{$types}) {
                   18153:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   18154:                     if ($dom_str ne '') {
                   18155:                         my $updatedstr = '';
                   18156:                         my @possdomains = split(',',$dom_str);
                   18157:                         foreach my $entry (@possdomains) {
                   18158:                             my ($extdom,$extopt) = split(':',$entry);
                   18159:                             unless ($trustchecked{$extdom}) {
                   18160:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   18161:                                 $trustchecked{$extdom} = 1;
                   18162:                             }
                   18163:                             if ($willtrust{$extdom}) {
                   18164:                                 $updatedstr .= $entry.',';
                   18165:                             }
                   18166:                         }
                   18167:                         $updatedstr =~ s/,$//;
                   18168:                         if ($updatedstr) {
                   18169:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18170:                         } else {
                   18171:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18172:                         }
                   18173:                     }
                   18174:                 }
                   18175:             }
1.1092    raeburn  18176:         }
1.462     albertel 18177: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18178: 
1.462     albertel 18179: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18180: 		 &GDBM_WRCREAT(),0640)) {
                   18181: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18182: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18183: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18184:             if (ref($firstaccenv) eq 'HASH') {
                   18185:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18186:             }
                   18187:             if (ref($timerintenv) eq 'HASH') {
                   18188:                 &_add_to_env(\%disk_env,$timerintenv);
                   18189:             }
1.1414    raeburn  18190:             if (ref($coauthorenv) eq 'HASH') {
                   18191:                 if (keys(%{$coauthorenv})) {
                   18192:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18193:                 }
                   18194:             }
1.463     albertel 18195: 	    if (ref($args->{'extra_env'})) {
                   18196: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18197: 	    }
1.462     albertel 18198: 	    untie(%disk_env);
                   18199: 	} else {
1.705     tempelho 18200: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18201: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18202: 	    return 'error: '.$!;
                   18203: 	}
                   18204:     }
                   18205:     $env{'request.role'}='cm';
                   18206:     $env{'request.role.adv'}=$env{'user.adv'};
                   18207:     $env{'browser.type'}=$clientbrowser;
                   18208: 
                   18209:     return $cookie;
                   18210: 
                   18211: }
                   18212: 
                   18213: sub _add_to_env {
                   18214:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18215:     if (ref($env_data) eq 'HASH') {
                   18216:         while (my ($key,$value) = each(%$env_data)) {
                   18217: 	    $idf->{$prefix.$key} = $value;
                   18218: 	    $env{$prefix.$key}   = $value;
                   18219:         }
1.462     albertel 18220:     }
                   18221: }
                   18222: 
1.685     tempelho 18223: # --- Get the symbolic name of a problem and the url
                   18224: sub get_symb {
                   18225:     my ($request,$silent) = @_;
1.726     raeburn  18226:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18227:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18228:     if ($symb eq '') {
                   18229:         if (!$silent) {
1.1071    raeburn  18230:             if (ref($request)) { 
                   18231:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18232:             }
1.685     tempelho 18233:             return ();
                   18234:         }
                   18235:     }
                   18236:     &Apache::lonenc::check_decrypt(\$symb);
                   18237:     return ($symb);
                   18238: }
                   18239: 
                   18240: # --------------------------------------------------------------Get annotation
                   18241: 
                   18242: sub get_annotation {
                   18243:     my ($symb,$enc) = @_;
                   18244: 
                   18245:     my $key = $symb;
                   18246:     if (!$enc) {
                   18247:         $key =
                   18248:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18249:     }
                   18250:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18251:     return $annotation{$key};
                   18252: }
                   18253: 
                   18254: sub clean_symb {
1.731     raeburn  18255:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18256: 
                   18257:     &Apache::lonenc::check_decrypt(\$symb);
                   18258:     my $enc = $env{'request.enc'};
1.731     raeburn  18259:     if ($delete_enc) {
1.730     raeburn  18260:         delete($env{'request.enc'});
                   18261:     }
1.685     tempelho 18262: 
                   18263:     return ($symb,$enc);
                   18264: }
1.462     albertel 18265: 
1.1181    raeburn  18266: ############################################################
                   18267: ############################################################
                   18268: 
                   18269: =pod
                   18270: 
                   18271: =head1 Routines for building display used to search for courses
                   18272: 
                   18273: 
                   18274: =over 4
                   18275: 
                   18276: =item * &build_filters()
                   18277: 
                   18278: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18279: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18280: and quotacheck.pl
                   18281: 
1.1181    raeburn  18282: 
                   18283: Inputs:
                   18284: 
                   18285: filterlist - anonymous array of fields to include as potential filters 
                   18286: 
                   18287: crstype - course type
                   18288: 
                   18289: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18290:               to pop-open a course selector (will contain "extra element"). 
                   18291: 
                   18292: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18293: 
                   18294: filter - anonymous hash of criteria and their values
                   18295: 
                   18296: action - form action
                   18297: 
                   18298: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18299: 
1.1182    raeburn  18300: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18301: 
                   18302: cloneruname - username of owner of new course who wants to clone
                   18303: 
                   18304: clonerudom - domain of owner of new course who wants to clone
                   18305: 
                   18306: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18307: 
                   18308: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18309: 
                   18310: codedom - domain
                   18311: 
                   18312: formname - value of form element named "form". 
                   18313: 
                   18314: fixeddom - domain, if fixed.
                   18315: 
                   18316: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18317: 
                   18318: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18319: 
                   18320: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18321: 
                   18322: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18323: 
                   18324: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18325: 
                   18326: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18327: 
                   18328: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18329: 
1.1182    raeburn  18330: 
1.1181    raeburn  18331: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18332: 
1.1182    raeburn  18333: 
1.1181    raeburn  18334: Side Effects: None
                   18335: 
                   18336: =cut
                   18337: 
                   18338: # ---------------------------------------------- search for courses based on last activity etc.
                   18339: 
                   18340: sub build_filters {
                   18341:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18342:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18343:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18344:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18345:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18346:     my ($list,$jscript);
1.1181    raeburn  18347:     my $onchange = 'javascript:updateFilters(this)';
                   18348:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18349:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18350:         $typeselectform,$instcodetitle);
                   18351:     if ($formname eq '') {
                   18352:         $formname = $caller;
                   18353:     }
                   18354:     foreach my $item (@{$filterlist}) {
                   18355:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18356:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18357:             if ($item eq 'domainfilter') {
                   18358:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18359:             } elsif ($item eq 'coursefilter') {
                   18360:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18361:             } elsif ($item eq 'ownerfilter') {
                   18362:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18363:             } elsif ($item eq 'ownerdomfilter') {
                   18364:                 $filter->{'ownerdomfilter'} =
                   18365:                     &LONCAPA::clean_domain($filter->{$item});
                   18366:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18367:                                                        'ownerdomfilter',1);
                   18368:             } elsif ($item eq 'personfilter') {
                   18369:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18370:             } elsif ($item eq 'persondomfilter') {
                   18371:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18372:                                                         'persondomfilter',1);
                   18373:             } else {
                   18374:                 $filter->{$item} =~ s/\W//g;
                   18375:             }
                   18376:             if (!$filter->{$item}) {
                   18377:                 $filter->{$item} = '';
                   18378:             }
                   18379:         }
                   18380:         if ($item eq 'domainfilter') {
                   18381:             my $allow_blank = 1;
                   18382:             if ($formname eq 'portform') {
                   18383:                 $allow_blank=0;
                   18384:             } elsif ($formname eq 'studentform') {
                   18385:                 $allow_blank=0;
                   18386:             }
                   18387:             if ($fixeddom) {
                   18388:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18389:                                     ' value="'.$codedom.'" />'.
                   18390:                                     &Apache::lonnet::domain($codedom,'description');
                   18391:             } else {
                   18392:                 $domainselectform = &select_dom_form($filter->{$item},
                   18393:                                                      'domainfilter',
                   18394:                                                       $allow_blank,'',$onchange);
                   18395:             }
                   18396:         } else {
                   18397:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18398:         }
                   18399:     }
                   18400: 
                   18401:     # last course activity filter and selection
                   18402:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18403: 
                   18404:     # course created filter and selection
                   18405:     if (exists($filter->{'createdfilter'})) {
                   18406:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18407:     }
                   18408: 
1.1239    raeburn  18409:     my $prefix = $crstype;
                   18410:     if ($crstype eq 'Placement') {
                   18411:         $prefix = 'Placement Test'
                   18412:     }
1.1181    raeburn  18413:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18414:                 'cac' => "$prefix Activity",
                   18415:                 'ccr' => "$prefix Created",
                   18416:                 'cde' => "$prefix Title",
                   18417:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18418:                 'ins' => 'Institutional Code',
                   18419:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18420:                 'cow' => "$prefix Owner/Co-owner",
                   18421:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18422:                 'cog' => 'Type',
                   18423:              );
                   18424: 
                   18425:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18426:         my $typeval = 'Course';
                   18427:         if ($crstype eq 'Community') {
                   18428:             $typeval = 'Community';
1.1239    raeburn  18429:         } elsif ($crstype eq 'Placement') {
                   18430:             $typeval = 'Placement';
1.1181    raeburn  18431:         }
                   18432:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18433:     } else {
                   18434:         $typeselectform =  '<select name="type" size="1"';
                   18435:         if ($onchange) {
                   18436:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18437:         }
                   18438:         $typeselectform .= '>'."\n";
1.1237    raeburn  18439:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18440:             my $shown;
                   18441:             if ($posstype eq 'Placement') {
                   18442:                 $shown = &mt('Placement Test');
                   18443:             } else {
                   18444:                 $shown = &mt($posstype);
                   18445:             }
1.1181    raeburn  18446:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18447:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18448:         }
                   18449:         $typeselectform.="</select>";
                   18450:     }
                   18451: 
                   18452:     my ($cloneableonlyform,$cloneabletitle);
                   18453:     if (exists($filter->{'cloneableonly'})) {
                   18454:         my $cloneableon = '';
                   18455:         my $cloneableoff = ' checked="checked"';
                   18456:         if ($filter->{'cloneableonly'}) {
                   18457:             $cloneableon = $cloneableoff;
                   18458:             $cloneableoff = '';
                   18459:         }
                   18460:         $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>';
                   18461:         if ($formname eq 'ccrs') {
1.1187    bisitz   18462:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18463:         } else {
                   18464:             $cloneabletitle = &mt('Cloneable by you');
                   18465:         }
                   18466:     }
                   18467:     my $officialjs;
                   18468:     if ($crstype eq 'Course') {
                   18469:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18470: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18471: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18472:             if ($codedom) { 
1.1181    raeburn  18473:                 $officialjs = 1;
                   18474:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18475:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18476:                                                                   $officialjs,$codetitlesref);
                   18477:                 if ($jscript) {
1.1182    raeburn  18478:                     $jscript = '<script type="text/javascript">'."\n".
                   18479:                                '// <![CDATA['."\n".
                   18480:                                $jscript."\n".
                   18481:                                '// ]]>'."\n".
                   18482:                                '</script>'."\n";
1.1181    raeburn  18483:                 }
                   18484:             }
                   18485:             if ($instcodeform eq '') {
                   18486:                 $instcodeform =
                   18487:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18488:                     $list->{'instcodefilter'}.'" />';
                   18489:                 $instcodetitle = $lt{'ins'};
                   18490:             } else {
                   18491:                 $instcodetitle = $lt{'inc'};
                   18492:             }
                   18493:             if ($fixeddom) {
                   18494:                 $instcodetitle .= '<br />('.$codedom.')';
                   18495:             }
                   18496:         }
                   18497:     }
                   18498:     my $output = qq|
                   18499: <form method="post" name="filterpicker" action="$action">
                   18500: <input type="hidden" name="form" value="$formname" />
                   18501: |;
                   18502:     if ($formname eq 'modifycourse') {
                   18503:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18504:                    '<input type="hidden" name="prevphase" value="'.
                   18505:                    $prevphase.'" />'."\n";
1.1198    musolffc 18506:     } elsif ($formname eq 'quotacheck') {
                   18507:         $output .= qq|
                   18508: <input type="hidden" name="sortby" value="" />
                   18509: <input type="hidden" name="sortorder" value="" />
                   18510: |;
                   18511:     } else {
1.1181    raeburn  18512:         my $name_input;
                   18513:         if ($cnameelement ne '') {
                   18514:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18515:                           $cnameelement.'" />';
                   18516:         }
                   18517:         $output .= qq|
1.1182    raeburn  18518: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18519: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18520: $name_input
                   18521: $roleelement
                   18522: $multelement
                   18523: $typeelement
                   18524: |;
                   18525:         if ($formname eq 'portform') {
                   18526:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18527:         }
                   18528:     }
                   18529:     if ($fixeddom) {
                   18530:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18531:     }
                   18532:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18533:     if ($sincefilterform) {
                   18534:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18535:                   .$sincefilterform
                   18536:                   .&Apache::lonhtmlcommon::row_closure();
                   18537:     }
                   18538:     if ($createdfilterform) {
                   18539:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18540:                   .$createdfilterform
                   18541:                   .&Apache::lonhtmlcommon::row_closure();
                   18542:     }
                   18543:     if ($domainselectform) {
                   18544:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18545:                   .$domainselectform
                   18546:                   .&Apache::lonhtmlcommon::row_closure();
                   18547:     }
                   18548:     if ($typeselectform) {
                   18549:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18550:             $output .= $typeselectform;
                   18551:         } else {
                   18552:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18553:                       .$typeselectform
                   18554:                       .&Apache::lonhtmlcommon::row_closure();
                   18555:         }
                   18556:     }
                   18557:     if ($instcodeform) {
                   18558:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18559:                   .$instcodeform
                   18560:                   .&Apache::lonhtmlcommon::row_closure();
                   18561:     }
                   18562:     if (exists($filter->{'ownerfilter'})) {
                   18563:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18564:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18565:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18566:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18567:                    $ownerdomselectform.'</td></tr></table>'.
                   18568:                    &Apache::lonhtmlcommon::row_closure();
                   18569:     }
                   18570:     if (exists($filter->{'personfilter'})) {
                   18571:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18572:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18573:                    '<input type="text" name="personfilter" size="20" value="'.
                   18574:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18575:                    $persondomselectform.'</td></tr></table>'.
                   18576:                    &Apache::lonhtmlcommon::row_closure();
                   18577:     }
                   18578:     if (exists($filter->{'coursefilter'})) {
                   18579:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18580:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18581:                   .$list->{'coursefilter'}.'" />'
                   18582:                   .&Apache::lonhtmlcommon::row_closure();
                   18583:     }
                   18584:     if ($cloneableonlyform) {
                   18585:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18586:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18587:     }
                   18588:     if (exists($filter->{'descriptfilter'})) {
                   18589:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18590:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18591:                   .$list->{'descriptfilter'}.'" />'
                   18592:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18593:     }
                   18594:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18595:                '<input type="hidden" name="updater" value="" />'."\n".
                   18596:                '<input type="submit" name="gosearch" value="'.
                   18597:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18598:     return $jscript.$clonewarning.$output;
                   18599: }
                   18600: 
                   18601: =pod 
                   18602: 
                   18603: =item * &timebased_select_form()
                   18604: 
1.1182    raeburn  18605: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18606: filter e.g., Course Activity, Course Created, when searching for courses
                   18607: or communities
                   18608: 
                   18609: Inputs:
                   18610: 
                   18611: item - name of form element (sincefilter or createdfilter)
                   18612: 
                   18613: filter - anonymous hash of criteria and their values
                   18614: 
                   18615: Returns: HTML for a select box contained a blank, then six time selections,
                   18616:          with value set in incoming form variables currently selected. 
                   18617: 
                   18618: Side Effects: None
                   18619: 
                   18620: =cut
                   18621: 
                   18622: sub timebased_select_form {
                   18623:     my ($item,$filter) = @_;
                   18624:     if (ref($filter) eq 'HASH') {
                   18625:         $filter->{$item} =~ s/[^\d-]//g;
                   18626:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18627:         return &select_form(
                   18628:                             $filter->{$item},
                   18629:                             $item,
                   18630:                             {      '-1' => '',
                   18631:                                 '86400' => &mt('today'),
                   18632:                                '604800' => &mt('last week'),
                   18633:                               '2592000' => &mt('last month'),
                   18634:                               '7776000' => &mt('last three months'),
                   18635:                              '15552000' => &mt('last six months'),
                   18636:                              '31104000' => &mt('last year'),
                   18637:                     'select_form_order' =>
                   18638:                            ['-1','86400','604800','2592000','7776000',
                   18639:                             '15552000','31104000']});
                   18640:     }
                   18641: }
                   18642: 
                   18643: =pod
                   18644: 
                   18645: =item * &js_changer()
                   18646: 
                   18647: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18648: when course type or domain is changed, and also to hide 'Searching ...' on
                   18649: page load completion for page showing search result.
1.1181    raeburn  18650: 
                   18651: Inputs: None
                   18652: 
1.1183    raeburn  18653: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18654: 
                   18655: Side Effects: None
                   18656: 
                   18657: =cut
                   18658: 
                   18659: sub js_changer {
                   18660:     return <<ENDJS;
                   18661: <script type="text/javascript">
                   18662: // <![CDATA[
                   18663: function updateFilters(caller) {
                   18664:     if (typeof(caller) != "undefined") {
                   18665:         document.filterpicker.updater.value = caller.name;
                   18666:     }
                   18667:     document.filterpicker.submit();
                   18668: }
1.1183    raeburn  18669: 
                   18670: function hideSearching() {
                   18671:     if (document.getElementById('searching')) {
                   18672:         document.getElementById('searching').style.display = 'none';
                   18673:     }
                   18674:     return;
                   18675: }
                   18676: 
1.1181    raeburn  18677: // ]]>
                   18678: </script>
                   18679: 
                   18680: ENDJS
                   18681: }
                   18682: 
                   18683: =pod
                   18684: 
1.1182    raeburn  18685: =item * &search_courses()
                   18686: 
                   18687: Process selected filters form course search form and pass to lonnet::courseiddump
                   18688: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18689: 
                   18690: Inputs:
                   18691: 
                   18692: dom - domain being searched 
                   18693: 
                   18694: type - course type ('Course' or 'Community' or '.' if any).
                   18695: 
                   18696: filter - anonymous hash of criteria and their values
                   18697: 
                   18698: numtitles - for institutional codes - number of categories
                   18699: 
                   18700: cloneruname - optional username of new course owner
                   18701: 
                   18702: clonerudom - optional domain of new course owner
                   18703: 
1.1221    raeburn  18704: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18705:             (used when DC is using course creation form)
                   18706: 
                   18707: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18708: 
1.1221    raeburn  18709: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18710:            (and so can clone automatically)
                   18711: 
                   18712: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18713: 
                   18714: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18715:               courses to clone 
1.1182    raeburn  18716: 
                   18717: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18718: 
                   18719: 
                   18720: Side Effects: None
                   18721: 
                   18722: =cut
                   18723: 
                   18724: 
                   18725: sub search_courses {
1.1221    raeburn  18726:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18727:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18728:     my (%courses,%showcourses,$cloner);
                   18729:     if (($filter->{'ownerfilter'} ne '') ||
                   18730:         ($filter->{'ownerdomfilter'} ne '')) {
                   18731:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18732:                                        $filter->{'ownerdomfilter'};
                   18733:     }
                   18734:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18735:         if (!$filter->{$item}) {
                   18736:             $filter->{$item}='.';
                   18737:         }
                   18738:     }
                   18739:     my $now = time;
                   18740:     my $timefilter =
                   18741:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18742:     my ($createdbefore,$createdafter);
                   18743:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18744:         $createdbefore = $now;
                   18745:         $createdafter = $now-$filter->{'createdfilter'};
                   18746:     }
                   18747:     my ($instcodefilter,$regexpok);
                   18748:     if ($numtitles) {
                   18749:         if ($env{'form.official'} eq 'on') {
                   18750:             $instcodefilter =
                   18751:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18752:             $regexpok = 1;
                   18753:         } elsif ($env{'form.official'} eq 'off') {
                   18754:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18755:             unless ($instcodefilter eq '') {
                   18756:                 $regexpok = -1;
                   18757:             }
                   18758:         }
                   18759:     } else {
                   18760:         $instcodefilter = $filter->{'instcodefilter'};
                   18761:     }
                   18762:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18763:     if ($type eq '') { $type = '.'; }
                   18764: 
                   18765:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18766:         $cloner = $cloneruname.':'.$clonerudom;
                   18767:     }
                   18768:     %courses = &Apache::lonnet::courseiddump($dom,
                   18769:                                              $filter->{'descriptfilter'},
                   18770:                                              $timefilter,
                   18771:                                              $instcodefilter,
                   18772:                                              $filter->{'combownerfilter'},
                   18773:                                              $filter->{'coursefilter'},
                   18774:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18775:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18776:                                              $filter->{'cloneableonly'},
                   18777:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18778:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18779:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18780:         my $ccrole;
                   18781:         if ($type eq 'Community') {
                   18782:             $ccrole = 'co';
                   18783:         } else {
                   18784:             $ccrole = 'cc';
                   18785:         }
                   18786:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18787:                                                      $filter->{'persondomfilter'},
                   18788:                                                      'userroles',undef,
                   18789:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18790:                                                      $dom);
                   18791:         foreach my $role (keys(%rolehash)) {
                   18792:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18793:             my $cid = $cdom.'_'.$cnum;
                   18794:             if (exists($courses{$cid})) {
                   18795:                 if (ref($courses{$cid}) eq 'HASH') {
                   18796:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18797:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18798:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18799:                         }
                   18800:                     } else {
                   18801:                         $courses{$cid}{roles} = [$courserole];
                   18802:                     }
                   18803:                     $showcourses{$cid} = $courses{$cid};
                   18804:                 }
                   18805:             }
                   18806:         }
                   18807:         %courses = %showcourses;
                   18808:     }
                   18809:     return %courses;
                   18810: }
                   18811: 
                   18812: =pod
                   18813: 
1.1181    raeburn  18814: =back
                   18815: 
1.1207    raeburn  18816: =head1 Routines for version requirements for current course.
                   18817: 
                   18818: =over 4
                   18819: 
                   18820: =item * &check_release_required()
                   18821: 
                   18822: Compares required LON-CAPA version with version on server, and
                   18823: if required version is newer looks for a server with the required version.
                   18824: 
                   18825: Looks first at servers in user's owen domain; if none suitable, looks at
                   18826: servers in course's domain are permitted to host sessions for user's domain.
                   18827: 
                   18828: Inputs:
                   18829: 
                   18830: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18831: 
                   18832: $courseid - Course ID of current course
                   18833: 
                   18834: $rolecode - User's current role in course (for switchserver query string).
                   18835: 
                   18836: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18837: 
                   18838: 
                   18839: Returns:
                   18840: 
                   18841: $switchserver - query string tp append to /adm/switchserver call (if 
                   18842:                 current server's LON-CAPA version is too old. 
                   18843: 
                   18844: $warning - Message is displayed if no suitable server could be found.
                   18845: 
                   18846: =cut
                   18847: 
                   18848: sub check_release_required {
                   18849:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18850:     my ($switchserver,$warning);
                   18851:     if ($required ne '') {
                   18852:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18853:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18854:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18855:             my $otherserver;
                   18856:             if (($major eq '' && $minor eq '') ||
                   18857:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18858:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18859:                 my $switchlcrev =
                   18860:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18861:                                                            $userdomserver);
                   18862:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18863:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18864:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18865:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18866:                     if ($cdom ne $env{'user.domain'}) {
                   18867:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18868:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18869:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18870:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18871:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18872:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18873:                         my $canhost =
                   18874:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18875:                                                               $coursedomserver,
                   18876:                                                               $remoterev,
                   18877:                                                               $udomdefaults{'remotesessions'},
                   18878:                                                               $defdomdefaults{'hostedsessions'});
                   18879: 
                   18880:                         if ($canhost) {
                   18881:                             $otherserver = $coursedomserver;
                   18882:                         } else {
                   18883:                             $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.");
                   18884:                         }
                   18885:                     } else {
                   18886:                         $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).");
                   18887:                     }
                   18888:                 } else {
                   18889:                     $otherserver = $userdomserver;
                   18890:                 }
                   18891:             }
                   18892:             if ($otherserver ne '') {
                   18893:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18894:             }
                   18895:         }
                   18896:     }
                   18897:     return ($switchserver,$warning);
                   18898: }
                   18899: 
                   18900: =pod
                   18901: 
                   18902: =item * &check_release_result()
                   18903: 
                   18904: Inputs:
                   18905: 
                   18906: $switchwarning - Warning message if no suitable server found to host session.
                   18907: 
                   18908: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18909:                 and current role.
                   18910: 
                   18911: Returns: HTML to display with information about requirement to switch server.
                   18912:          Either displaying warning with link to Roles/Courses screen or
                   18913:          display link to switchserver.
                   18914: 
1.1181    raeburn  18915: =cut
                   18916: 
1.1207    raeburn  18917: sub check_release_result {
                   18918:     my ($switchwarning,$switchserver) = @_;
                   18919:     my $output = &start_page('Selected course unavailable on this server').
                   18920:                  '<p class="LC_warning">';
                   18921:     if ($switchwarning) {
                   18922:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18923:         if (&show_course()) {
                   18924:             $output .= &mt('Display courses');
                   18925:         } else {
                   18926:             $output .= &mt('Display roles');
                   18927:         }
                   18928:         $output .= '</a>';
                   18929:     } elsif ($switchserver) {
                   18930:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18931:                    '<br />'.
                   18932:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18933:                    &mt('Switch Server').
                   18934:                    '</a>';
                   18935:     }
                   18936:     $output .= '</p>'.&end_page();
                   18937:     return $output;
                   18938: }
                   18939: 
                   18940: =pod
                   18941: 
                   18942: =item * &needs_coursereinit()
                   18943: 
                   18944: Determine if course contents stored for user's session needs to be
                   18945: refreshed, because content has changed since "Big Hash" last tied.
                   18946: 
                   18947: Check for change is made if time last checked is more than 10 minutes ago
                   18948: (by default).
                   18949: 
                   18950: Inputs:
                   18951: 
                   18952: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18953: 
                   18954: $interval (optional) - Time which may elapse (in s) between last check for content
                   18955:                        change in current course. (default: 600 s).  
                   18956: 
                   18957: Returns: an array; first element is:
                   18958: 
                   18959: =over 4
                   18960: 
                   18961: 'switch' - if content updates mean user's session
                   18962:            needs to be switched to a server running a newer LON-CAPA version
                   18963:  
                   18964: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18965:            on current server hosting user's session                
                   18966: 
                   18967: ''       - if no action required.
                   18968: 
                   18969: =back
                   18970: 
                   18971: If first item element is 'switch':
                   18972: 
                   18973: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18974: 
                   18975: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18976:                               and current role. 
                   18977: 
                   18978: otherwise: no other elements returned.
                   18979: 
                   18980: =back
                   18981: 
                   18982: =cut
                   18983: 
                   18984: sub needs_coursereinit {
                   18985:     my ($loncaparev,$interval) = @_;
                   18986:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18987:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18988:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18989:     my $now = time;
                   18990:     if ($interval eq '') {
                   18991:         $interval = 600;
                   18992:     }
                   18993:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18994:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18995:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18996:         if ($blocked) {
                   18997:             return ();
                   18998:         }
1.1391    raeburn  18999:         my $update;
                   19000:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19001:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   19002:         if ($lastmainchange > $env{'request.course.tied'}) {
                   19003:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19004:             if ($needswitch) {
                   19005:                 return ('switch',$switchwarning,$switchserver);
                   19006:             }
                   19007:             $update = 'main';
                   19008:         }
                   19009:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   19010:             if ($update) {
                   19011:                 $update = 'both';
                   19012:             } else {
                   19013:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   19014:                 if ($needswitch) {
                   19015:                     return ('switch',$switchwarning,$switchserver);
                   19016:                 } else {
                   19017:                     $update = 'supp';
1.1207    raeburn  19018:                 }
                   19019:             }
1.1391    raeburn  19020:             return ($update);
                   19021:         }
                   19022:     }
                   19023:     return ();
                   19024: }
                   19025: 
                   19026: sub switch_for_update {
                   19027:     my ($loncaparev,$cdom,$cnum) = @_;
                   19028:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19029:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   19030:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   19031:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   19032:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   19033:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   19034:             my ($switchserver,$switchwarning) =
                   19035:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   19036:                                         $curr_reqd_hash{'internal.releaserequired'});
                   19037:             if ($switchwarning ne '' || $switchserver ne '') {
                   19038:                 return ('switch',$switchwarning,$switchserver);
                   19039:             }
1.1207    raeburn  19040:         }
                   19041:     }
                   19042:     return ();
                   19043: }
1.1181    raeburn  19044: 
1.1083    raeburn  19045: sub update_content_constraints {
1.1395    raeburn  19046:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  19047:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   19048:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  19049:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  19050:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  19051:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  19052:         if ($item eq 'resourcetag') {
                   19053:             if ($name eq 'responsetype') {
                   19054:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   19055:             }
1.1307    raeburn  19056:         } elsif ($item eq 'course') {
                   19057:             if ($name eq 'courserestype') {
                   19058:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   19059:             }
1.1083    raeburn  19060:         }
                   19061:     }
                   19062:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19063:     if (defined($navmap)) {
1.1307    raeburn  19064:         my (%allresponses,%allcrsrestypes);
                   19065:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   19066:             if ($res->is_tool()) {
                   19067:                 if ($allcrsrestypes{'exttool'}) {
                   19068:                     $allcrsrestypes{'exttool'} ++;
                   19069:                 } else {
                   19070:                     $allcrsrestypes{'exttool'} = 1;
                   19071:                 }
                   19072:                 next;
                   19073:             }
1.1083    raeburn  19074:             my %responses = $res->responseTypes();
                   19075:             foreach my $key (keys(%responses)) {
                   19076:                 next unless(exists($checkresponsetypes{$key}));
                   19077:                 $allresponses{$key} += $responses{$key};
                   19078:             }
                   19079:         }
                   19080:         foreach my $key (keys(%allresponses)) {
                   19081:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   19082:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19083:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19084:             }
                   19085:         }
1.1307    raeburn  19086:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  19087:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  19088:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19089:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   19090:             }
                   19091:         }
1.1083    raeburn  19092:         undef($navmap);
                   19093:     }
1.1391    raeburn  19094:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  19095:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   19096:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   19097:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   19098:         }
                   19099:     }
1.1083    raeburn  19100:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   19101:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   19102:     }
                   19103:     return;
                   19104: }
                   19105: 
1.1110    raeburn  19106: sub allmaps_incourse {
                   19107:     my ($cdom,$cnum,$chome,$cid) = @_;
                   19108:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   19109:         $cid = $env{'request.course.id'};
                   19110:         $cdom = $env{'course.'.$cid.'.domain'};
                   19111:         $cnum = $env{'course.'.$cid.'.num'};
                   19112:         $chome = $env{'course.'.$cid.'.home'};
                   19113:     }
                   19114:     my %allmaps = ();
                   19115:     my $lastchange =
                   19116:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   19117:     if ($lastchange > $env{'request.course.tied'}) {
                   19118:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   19119:         unless ($ferr) {
1.1395    raeburn  19120:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  19121:         }
                   19122:     }
                   19123:     my $navmap = Apache::lonnavmaps::navmap->new();
                   19124:     if (defined($navmap)) {
                   19125:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   19126:             $allmaps{$res->src()} = 1;
                   19127:         }
                   19128:     }
                   19129:     return \%allmaps;
                   19130: }
                   19131: 
1.1083    raeburn  19132: sub parse_supplemental_title {
                   19133:     my ($title) = @_;
                   19134: 
                   19135:     my ($foldertitle,$renametitle);
                   19136:     if ($title =~ /&amp;&amp;&amp;/) {
                   19137:         $title = &HTML::Entites::decode($title);
                   19138:     }
                   19139:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   19140:         $renametitle=$4;
                   19141:         my ($time,$uname,$udom) = ($1,$2,$3);
                   19142:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   19143:         my $name =  &plainname($uname,$udom);
                   19144:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   19145:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  19146:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  19147:         if ($foldertitle ne '') {
1.1401    raeburn  19148:             $title .= ': <br />'.$foldertitle;
                   19149:         }
1.1083    raeburn  19150:     }
                   19151:     if (wantarray) {
                   19152:         return ($title,$foldertitle,$renametitle);
                   19153:     }
                   19154:     return $title;
                   19155: }
                   19156: 
1.1395    raeburn  19157: sub get_supplemental {
                   19158:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   19159:     my $hashid=$cnum.':'.$cdom;
                   19160:     my ($supplemental,$cached,$set_httprefs);
                   19161:     unless ($ignorecache) {
                   19162:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   19163:     }
                   19164:     unless (defined($cached)) {
                   19165:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   19166:         unless ($chome eq 'no_host') {
                   19167:             my @order = @LONCAPA::map::order;
                   19168:             my @resources = @LONCAPA::map::resources;
                   19169:             my @resparms = @LONCAPA::map::resparms;
                   19170:             my @zombies = @LONCAPA::map::zombies;
                   19171:             my ($errors,%ids,%hidden);
                   19172:             $errors =
                   19173:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19174:                                       $errors,$possdel,\%ids,\%hidden);
                   19175:             @LONCAPA::map::order = @order;
                   19176:             @LONCAPA::map::resources = @resources;
                   19177:             @LONCAPA::map::resparms = @resparms;
                   19178:             @LONCAPA::map::zombies = @zombies;
                   19179:             $set_httprefs = 1;
                   19180:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19181:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19182:             }
                   19183:             $supplemental = {
                   19184:                                ids => \%ids,
                   19185:                                hidden => \%hidden,
                   19186:                             };
                   19187:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19188:         }
                   19189:     }
                   19190:     return ($supplemental,$set_httprefs);
                   19191: }
                   19192: 
1.1143    raeburn  19193: sub recurse_supplemental {
1.1391    raeburn  19194:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19195:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19196:         my $mapnum;
                   19197:         if ($suppmap eq 'supplemental.sequence') {
                   19198:             $mapnum = 0;
                   19199:         } else {
                   19200:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19201:         }
1.1143    raeburn  19202:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19203:         if ($fatal) {
                   19204:             $errors ++;
                   19205:         } else {
1.1389    raeburn  19206:             my @order = @LONCAPA::map::order;
                   19207:             if (@order > 0) {
                   19208:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19209:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19210:                 foreach my $idx (@order) {
                   19211:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19212:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19213:                         my $id = $mapnum.':'.$idx;
                   19214:                         push(@{$suppids->{$src}},$id);
                   19215:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19216:                             $hiddensupp->{$id} = 1;
                   19217:                         }
1.1146    raeburn  19218:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19219:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19220:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19221:                         } else {
1.1391    raeburn  19222:                             my $allowed;
                   19223:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19224:                                 $allowed = 1;
                   19225:                             } elsif ($possdel) {
                   19226:                                 foreach my $item (@{$suppids->{$src}}) {
                   19227:                                     next if ($item eq $id);
                   19228:                                     unless ($hiddensupp->{$item}) {
                   19229:                                        $allowed = 1;
                   19230:                                        last;
                   19231:                                     }
                   19232:                                 }
                   19233:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19234:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19235:                                 }
                   19236:                             }
                   19237:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19238:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19239:                             }
1.1143    raeburn  19240:                         }
                   19241:                     }
                   19242:                 }
                   19243:             }
                   19244:         }
                   19245:     }
1.1391    raeburn  19246:     return $errors;
                   19247: }
                   19248: 
                   19249: sub set_supp_httprefs {
                   19250:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19251:     if (ref($supplemental) eq 'HASH') {
                   19252:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19253:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19254:                 next if ($src =~ /\.sequence$/);
                   19255:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19256:                     my $allowed;
                   19257:                     if ($env{'request.role.adv'}) {
                   19258:                         $allowed = 1;
                   19259:                     } else {
                   19260:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19261:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19262:                                 $allowed = 1;
                   19263:                                 last;
                   19264:                             }
                   19265:                         }
                   19266:                     }
                   19267:                     if (exists($env{'httpref.'.$src})) {
                   19268:                         if ($possdel) {
                   19269:                             unless ($allowed) {
                   19270:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19271:                             }
                   19272:                         }
                   19273:                     } elsif ($allowed) {
                   19274:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19275:                     }
                   19276:                 }
                   19277:             }
                   19278:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19279:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19280:             }
                   19281:         }
                   19282:     }
                   19283: }
                   19284: 
                   19285: sub get_supp_parameter {
                   19286:     my ($resparm,$name)=@_;
                   19287:     return if ($resparm eq '');
                   19288:     my $value=undef;
                   19289:     my $ptype=undef;
                   19290:     foreach (split('&&&',$resparm)) {
                   19291:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19292:         if ($thisname eq $name) {
                   19293:             $value=$thisvalue;
                   19294:             $ptype=$thistype;
                   19295:         }
                   19296:     }
                   19297:     return $value;
1.1143    raeburn  19298: }
                   19299: 
1.1101    raeburn  19300: sub symb_to_docspath {
1.1267    raeburn  19301:     my ($symb,$navmapref) = @_;
                   19302:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19303:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19304:     if ($resurl=~/\.(sequence|page)$/) {
                   19305:         $mapurl=$resurl;
                   19306:     } elsif ($resurl eq 'adm/navmaps') {
                   19307:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19308:     }
                   19309:     my $mapresobj;
1.1267    raeburn  19310:     unless (ref($$navmapref)) {
                   19311:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19312:     }
                   19313:     if (ref($$navmapref)) {
                   19314:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19315:     }
                   19316:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19317:     my $type=$2;
                   19318:     my $path;
                   19319:     if (ref($mapresobj)) {
                   19320:         my $pcslist = $mapresobj->map_hierarchy();
                   19321:         if ($pcslist ne '') {
                   19322:             foreach my $pc (split(/,/,$pcslist)) {
                   19323:                 next if ($pc <= 1);
1.1267    raeburn  19324:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19325:                 if (ref($res)) {
                   19326:                     my $thisurl = $res->src();
                   19327:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19328:                     my $thistitle = $res->title();
                   19329:                     $path .= '&'.
                   19330:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19331:                              &escape($thistitle).
1.1101    raeburn  19332:                              ':'.$res->randompick().
                   19333:                              ':'.$res->randomout().
                   19334:                              ':'.$res->encrypted().
                   19335:                              ':'.$res->randomorder().
                   19336:                              ':'.$res->is_page();
                   19337:                 }
                   19338:             }
                   19339:         }
                   19340:         $path =~ s/^\&//;
                   19341:         my $maptitle = $mapresobj->title();
                   19342:         if ($mapurl eq 'default') {
1.1129    raeburn  19343:             $maptitle = 'Main Content';
1.1101    raeburn  19344:         }
                   19345:         $path .= (($path ne '')? '&' : '').
                   19346:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19347:                  &escape($maptitle).
1.1101    raeburn  19348:                  ':'.$mapresobj->randompick().
                   19349:                  ':'.$mapresobj->randomout().
                   19350:                  ':'.$mapresobj->encrypted().
                   19351:                  ':'.$mapresobj->randomorder().
                   19352:                  ':'.$mapresobj->is_page();
                   19353:     } else {
                   19354:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19355:         my $ispage = (($type eq 'page')? 1 : '');
                   19356:         if ($mapurl eq 'default') {
1.1129    raeburn  19357:             $maptitle = 'Main Content';
1.1101    raeburn  19358:         }
                   19359:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19360:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19361:     }
                   19362:     unless ($mapurl eq 'default') {
                   19363:         $path = 'default&'.
1.1146    raeburn  19364:                 &escape('Main Content').
1.1101    raeburn  19365:                 ':::::&'.$path;
                   19366:     }
                   19367:     return $path;
                   19368: }
                   19369: 
1.1393    raeburn  19370: sub validate_folderpath {
                   19371:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19372:     if ($env{'form.folderpath'} ne '') {
                   19373:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19374:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19375:         for (my $i=0; $i<@items; $i++) {
                   19376:             my $odd = $i%2;
                   19377:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19378:                 $badpath = 1;
1.1394    raeburn  19379:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19380:                 my $idx = $i-1;
1.1394    raeburn  19381:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19382:                     my $esc_name = $1;
                   19383:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19384:                         $supppath .= '&'.$esc_name;
                   19385:                         $changed = 1;
                   19386:                     } else {
                   19387:                         $supppath .= '&'.$items[$i];
                   19388:                     }
                   19389:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19390:                     $changed = 1;
1.1393    raeburn  19391:                     my $is_hidden;
                   19392:                     unless ($got_supp) {
1.1395    raeburn  19393:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19394:                         if (ref($supplemental) eq 'HASH') {
                   19395:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19396:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19397:                             }
                   19398:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19399:                                 %suppids = %{$supplemental->{'ids'}};
                   19400:                             }
                   19401:                         }
                   19402:                         $got_supp = 1;
                   19403:                     }
                   19404:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19405:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19406:                         if ($supphidden{$mapid}) {
                   19407:                             $is_hidden = 1;
                   19408:                         }
                   19409:                     }
1.1394    raeburn  19410:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19411:                 } else {
                   19412:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19413:                 }
                   19414:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19415:                 $badpath = 1;
1.1394    raeburn  19416:             } elsif ($supplementalflag) {
1.1393    raeburn  19417:                 $supppath .= '&'.$items[$i];
                   19418:             }
                   19419:             last if ($badpath);
                   19420:         }
                   19421:         if ($badpath) {
                   19422:             delete($env{'form.folderpath'});
1.1394    raeburn  19423:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19424:             $supppath =~ s/^\&//;
                   19425:             $env{'form.folderpath'} = $supppath;
                   19426:         }
                   19427:     }
                   19428:     return;
                   19429: }
                   19430: 
1.1094    raeburn  19431: sub captcha_display {
1.1327    raeburn  19432:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19433:     my ($output,$error);
1.1234    raeburn  19434:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19435:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19436:     if ($captcha eq 'original') {
1.1094    raeburn  19437:         $output = &create_captcha();
                   19438:         unless ($output) {
1.1172    raeburn  19439:             $error = 'captcha';
1.1094    raeburn  19440:         }
                   19441:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19442:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19443:         unless ($output) {
1.1172    raeburn  19444:             $error = 'recaptcha';
1.1094    raeburn  19445:         }
                   19446:     }
1.1234    raeburn  19447:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19448: }
                   19449: 
                   19450: sub captcha_response {
1.1327    raeburn  19451:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19452:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19453:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19454:     if ($captcha eq 'original') {
1.1094    raeburn  19455:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19456:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19457:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19458:     } else {
                   19459:         $captcha_chk = 1;
                   19460:     }
                   19461:     return ($captcha_chk,$captcha_error);
                   19462: }
                   19463: 
                   19464: sub get_captcha_config {
1.1327    raeburn  19465:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19466:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19467:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19468:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19469:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19470:     if ($context eq 'usercreation') {
                   19471:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19472:         if (ref($domconfig{$context}) eq 'HASH') {
                   19473:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19474:             if (ref($hashtocheck) eq 'HASH') {
                   19475:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19476:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19477:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19478:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19479:                     }
                   19480:                     if ($privkey && $pubkey) {
                   19481:                         $captcha = 'recaptcha';
1.1234    raeburn  19482:                         $version = $hashtocheck->{'recaptchaversion'};
                   19483:                         if ($version ne '2') {
                   19484:                             $version = 1;
                   19485:                         }
1.1095    raeburn  19486:                     } else {
                   19487:                         $captcha = 'original';
                   19488:                     }
                   19489:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19490:                     $captcha = 'original';
                   19491:                 }
1.1094    raeburn  19492:             }
1.1095    raeburn  19493:         } else {
                   19494:             $captcha = 'captcha';
                   19495:         }
                   19496:     } elsif ($context eq 'login') {
                   19497:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19498:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19499:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19500:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19501:             if ($privkey && $pubkey) {
                   19502:                 $captcha = 'recaptcha';
1.1234    raeburn  19503:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19504:                 if ($version ne '2') {
                   19505:                     $version = 1; 
                   19506:                 }
1.1095    raeburn  19507:             } else {
                   19508:                 $captcha = 'original';
1.1094    raeburn  19509:             }
1.1095    raeburn  19510:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19511:             $captcha = 'original';
1.1094    raeburn  19512:         }
1.1327    raeburn  19513:     } elsif ($context eq 'passwords') {
                   19514:         if ($dom_in_effect) {
                   19515:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19516:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19517:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19518:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19519:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19520:                 }
                   19521:                 if ($privkey && $pubkey) {
                   19522:                     $captcha = 'recaptcha';
                   19523:                     $version = $passwdconf{'recaptchaversion'};
                   19524:                     if ($version ne '2') {
                   19525:                         $version = 1;
                   19526:                     }
                   19527:                 } else {
                   19528:                     $captcha = 'original';
                   19529:                 }
                   19530:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19531:                 $captcha = 'original';
                   19532:             }
                   19533:         }
                   19534:     } 
1.1234    raeburn  19535:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19536: }
                   19537: 
                   19538: sub create_captcha {
                   19539:     my %captcha_params = &captcha_settings();
                   19540:     my ($output,$maxtries,$tries) = ('',10,0);
                   19541:     while ($tries < $maxtries) {
                   19542:         $tries ++;
                   19543:         my $captcha = Authen::Captcha->new (
                   19544:                                            output_folder => $captcha_params{'output_dir'},
                   19545:                                            data_folder   => $captcha_params{'db_dir'},
                   19546:                                           );
                   19547:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19548: 
                   19549:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19550:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19551:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19552:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19553:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19554:                       '</span><br />'.
1.1176    raeburn  19555:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19556:             last;
                   19557:         }
                   19558:     }
1.1323    raeburn  19559:     if ($output eq '') {
                   19560:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19561:     }
1.1094    raeburn  19562:     return $output;
                   19563: }
                   19564: 
                   19565: sub captcha_settings {
                   19566:     my %captcha_params = (
                   19567:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19568:                            www_output_dir => "/captchaspool",
                   19569:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19570:                            numchars       => '5',
                   19571:                          );
                   19572:     return %captcha_params;
                   19573: }
                   19574: 
                   19575: sub check_captcha {
                   19576:     my ($captcha_chk,$captcha_error);
                   19577:     my $code = $env{'form.code'};
                   19578:     my $md5sum = $env{'form.crypt'};
                   19579:     my %captcha_params = &captcha_settings();
                   19580:     my $captcha = Authen::Captcha->new(
                   19581:                       output_folder => $captcha_params{'output_dir'},
                   19582:                       data_folder   => $captcha_params{'db_dir'},
                   19583:                   );
1.1109    raeburn  19584:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19585:     my %captcha_hash = (
                   19586:                         0       => 'Code not checked (file error)',
                   19587:                        -1      => 'Failed: code expired',
                   19588:                        -2      => 'Failed: invalid code (not in database)',
                   19589:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19590:     );
                   19591:     if ($captcha_chk != 1) {
                   19592:         $captcha_error = $captcha_hash{$captcha_chk}
                   19593:     }
                   19594:     return ($captcha_chk,$captcha_error);
                   19595: }
                   19596: 
                   19597: sub create_recaptcha {
1.1234    raeburn  19598:     my ($pubkey,$version) = @_;
                   19599:     if ($version >= 2) {
1.1367    raeburn  19600:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19601:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19602:     } else {
                   19603:         my $use_ssl;
                   19604:         if ($ENV{'SERVER_PORT'} == 443) {
                   19605:             $use_ssl = 1;
                   19606:         }
                   19607:         my $captcha = Captcha::reCAPTCHA->new;
                   19608:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19609:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19610:                &mt('If the text is hard to read, [_1] will replace them.',
                   19611:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19612:                '<br /><br />';
                   19613:     }
1.1094    raeburn  19614: }
                   19615: 
                   19616: sub check_recaptcha {
1.1234    raeburn  19617:     my ($privkey,$version) = @_;
1.1094    raeburn  19618:     my $captcha_chk;
1.1350    raeburn  19619:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19620:     if ($version >= 2) {
                   19621:         my %info = (
                   19622:                      secret   => $privkey, 
                   19623:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19624:                      remoteip => $ip,
1.1234    raeburn  19625:                    );
1.1280    raeburn  19626:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19627:         $request->content(join('&',map {
                   19628:                          my $name = escape($_);
                   19629:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19630:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19631:                          : &escape($info{$_}) );
                   19632:         } keys(%info)));
                   19633:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19634:         if ($response->is_success)  {
                   19635:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19636:             if (ref($data) eq 'HASH') {
                   19637:                 if ($data->{'success'}) {
                   19638:                     $captcha_chk = 1;
                   19639:                 }
                   19640:             }
                   19641:         }
                   19642:     } else {
                   19643:         my $captcha = Captcha::reCAPTCHA->new;
                   19644:         my $captcha_result =
                   19645:             $captcha->check_answer(
                   19646:                                     $privkey,
1.1350    raeburn  19647:                                     $ip,
1.1234    raeburn  19648:                                     $env{'form.recaptcha_challenge_field'},
                   19649:                                     $env{'form.recaptcha_response_field'},
                   19650:                                   );
                   19651:         if ($captcha_result->{is_valid}) {
                   19652:             $captcha_chk = 1;
                   19653:         }
1.1094    raeburn  19654:     }
                   19655:     return $captcha_chk;
                   19656: }
                   19657: 
1.1174    raeburn  19658: sub emailusername_info {
1.1244    raeburn  19659:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19660:     my %titles = &Apache::lonlocal::texthash (
                   19661:                      lastname      => 'Last Name',
                   19662:                      firstname     => 'First Name',
                   19663:                      institution   => 'School/college/university',
                   19664:                      location      => "School's city, state/province, country",
                   19665:                      web           => "School's web address",
                   19666:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19667:                      id            => 'Student/Employee ID',
1.1174    raeburn  19668:                  );
                   19669:     return (\@fields,\%titles);
                   19670: }
                   19671: 
1.1161    raeburn  19672: sub cleanup_html {
                   19673:     my ($incoming) = @_;
                   19674:     my $outgoing;
                   19675:     if ($incoming ne '') {
                   19676:         $outgoing = $incoming;
                   19677:         $outgoing =~ s/;/&#059;/g;
                   19678:         $outgoing =~ s/\#/&#035;/g;
                   19679:         $outgoing =~ s/\&/&#038;/g;
                   19680:         $outgoing =~ s/</&#060;/g;
                   19681:         $outgoing =~ s/>/&#062;/g;
                   19682:         $outgoing =~ s/\(/&#040/g;
                   19683:         $outgoing =~ s/\)/&#041;/g;
                   19684:         $outgoing =~ s/"/&#034;/g;
                   19685:         $outgoing =~ s/'/&#039;/g;
                   19686:         $outgoing =~ s/\$/&#036;/g;
                   19687:         $outgoing =~ s{/}{&#047;}g;
                   19688:         $outgoing =~ s/=/&#061;/g;
                   19689:         $outgoing =~ s/\\/&#092;/g
                   19690:     }
                   19691:     return $outgoing;
                   19692: }
                   19693: 
1.1190    musolffc 19694: # Checks for critical messages and returns a redirect url if one exists.
                   19695: # $interval indicates how often to check for messages.
1.1282    raeburn  19696: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19697: sub critical_redirect {
1.1282    raeburn  19698:     my ($interval,$context) = @_;
1.1356    raeburn  19699:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19700:         return ();
                   19701:     }
1.1190    musolffc 19702:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19703:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19704:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19705:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19706:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19707:             if ($blocked) {
                   19708:                 my $checkrole = "cm./$cdom/$cnum";
                   19709:                 if ($env{'request.course.sec'} ne '') {
                   19710:                     $checkrole .= "/$env{'request.course.sec'}";
                   19711:                 }
                   19712:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19713:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19714:                     return;
                   19715:                 }
                   19716:             }
                   19717:         }
1.1190    musolffc 19718:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19719:                                         $env{'user.name'});
                   19720:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19721:         my $redirecturl;
1.1190    musolffc 19722:         if ($what[0]) {
1.1356    raeburn  19723: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19724: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19725: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19726:                 return (1, $url);
1.1190    musolffc 19727:             }
1.1191    raeburn  19728:         }
                   19729:     } 
                   19730:     return ();
1.1190    musolffc 19731: }
                   19732: 
1.1174    raeburn  19733: # Use:
                   19734: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19735: #
                   19736: ##################################################
                   19737: #          password associated functions         #
                   19738: ##################################################
                   19739: sub des_keys {
                   19740:     # Make a new key for DES encryption.
                   19741:     # Each key has two parts which are returned separately.
                   19742:     # Please note:  Each key must be passed through the &hex function
                   19743:     # before it is output to the web browser.  The hex versions cannot
                   19744:     # be used to decrypt.
                   19745:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19746:                 '8','9','a','b','c','d','e','f');
                   19747:     my $lkey='';
                   19748:     for (0..7) {
                   19749:         $lkey.=$hexstr[rand(15)];
                   19750:     }
                   19751:     my $ukey='';
                   19752:     for (0..7) {
                   19753:         $ukey.=$hexstr[rand(15)];
                   19754:     }
                   19755:     return ($lkey,$ukey);
                   19756: }
                   19757: 
                   19758: sub des_decrypt {
                   19759:     my ($key,$cyphertext) = @_;
                   19760:     my $keybin=pack("H16",$key);
                   19761:     my $cypher;
                   19762:     if ($Crypt::DES::VERSION>=2.03) {
                   19763:         $cypher=new Crypt::DES $keybin;
                   19764:     } else {
                   19765:         $cypher=new DES $keybin;
                   19766:     }
1.1233    raeburn  19767:     my $plaintext='';
                   19768:     my $cypherlength = length($cyphertext);
                   19769:     my $numchunks = int($cypherlength/32);
                   19770:     for (my $j=0; $j<$numchunks; $j++) {
                   19771:         my $start = $j*32;
                   19772:         my $cypherblock = substr($cyphertext,$start,32);
                   19773:         my $chunk =
                   19774:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19775:         $chunk .=
                   19776:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19777:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19778:         $plaintext .= $chunk;
                   19779:     }
1.1174    raeburn  19780:     return $plaintext;
                   19781: }
                   19782: 
1.1344    raeburn  19783: sub get_requested_shorturls {
1.1309    raeburn  19784:     my ($cdom,$cnum,$navmap) = @_;
                   19785:     return unless (ref($navmap));
1.1344    raeburn  19786:     my ($numnew,$errors);
1.1309    raeburn  19787:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19788:     if (@toshorten) {
                   19789:         my (%maps,%resources,%titles);
                   19790:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19791:                                                                'shorturls',$cdom,$cnum);
                   19792:         if (keys(%resources)) {
1.1344    raeburn  19793:             my %tocreate;
1.1309    raeburn  19794:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19795:                 my $symb = $resources{$item};
                   19796:                 if ($symb) {
                   19797:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19798:                 }
                   19799:             }
1.1344    raeburn  19800:             if (keys(%tocreate)) {
                   19801:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19802:                                                       \%tocreate);
                   19803:             }
1.1309    raeburn  19804:         }
1.1344    raeburn  19805:     }
                   19806:     return ($numnew,$errors);
                   19807: }
                   19808: 
                   19809: sub make_short_symbs {
                   19810:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19811:     my ($numnew,@errors);
                   19812:     if (ref($tocreateref) eq 'HASH') {
                   19813:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19814:         if (keys(%tocreate)) {
                   19815:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19816:             my $su = Short::URL->new(no_vowels => 1);
                   19817:             my $init = '';
                   19818:             my (%newunique,%addcourse,%courseonly,%failed);
                   19819:             # get lock on tiny db
                   19820:             my $now = time;
1.1344    raeburn  19821:             if ($lockuser eq '') {
                   19822:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19823:             }
1.1309    raeburn  19824:             my $lockhash = {
1.1344    raeburn  19825:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19826:                             };
                   19827:             my $tries = 0;
                   19828:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19829:             my ($code,$error);
                   19830:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19831:                 $tries ++;
                   19832:                 sleep 1;
1.1319    raeburn  19833:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19834:             }
                   19835:             if ($gotlock eq 'ok') {
                   19836:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19837:                                        \%addcourse,\%courseonly,\%failed);
                   19838:                 if (keys(%failed)) {
                   19839:                     my $numfailed = scalar(keys(%failed));
                   19840:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19841:                 }
                   19842:                 if (keys(%newunique)) {
                   19843:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19844:                     if ($putres eq 'ok') {
                   19845:                         $numnew = scalar(keys(%newunique));
                   19846:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19847:                         unless ($newputres eq 'ok') {
                   19848:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19849:                         }
                   19850:                     } else {
                   19851:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19852:                     }
                   19853:                 }
                   19854:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19855:                 unless ($dellockres eq 'ok') {
                   19856:                     push(@errors,&mt('error: could not release lockfile'));
                   19857:                 }
                   19858:             } else {
                   19859:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19860:             }
                   19861:             if (keys(%courseonly)) {
                   19862:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19863:                 if ($result ne 'ok') {
                   19864:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19865:                 }
                   19866:             }
                   19867:         }
                   19868:     }
                   19869:     return ($numnew,\@errors);
                   19870: }
                   19871: 
                   19872: sub shorten_symbs {
                   19873:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19874:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19875:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19876:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19877:     my (%possibles,%collisions);
                   19878:     foreach my $key (keys(%{$tocreate})) {
                   19879:         my $num = String::CRC32::crc32($key);
                   19880:         my $tiny = $su->encode($num,$init);
                   19881:         if ($tiny) {
                   19882:             $possibles{$tiny} = $key;
                   19883:         }
                   19884:     }
                   19885:     if (!$init) {
                   19886:         $init = 1;
                   19887:     } else {
                   19888:         $init ++;
                   19889:     }
                   19890:     if (keys(%possibles)) {
                   19891:         my @posstiny = keys(%possibles);
                   19892:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19893:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19894:         if (keys(%currtiny)) {
                   19895:             foreach my $key (keys(%currtiny)) {
                   19896:                 next if ($currtiny{$key} eq '');
                   19897:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19898:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19899:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19900:                         $courseonly->{$tsymb} = $key;
                   19901:                     }
                   19902:                 } else {
                   19903:                     $collisions{$possibles{$key}} = 1;
                   19904:                 }
                   19905:                 delete($possibles{$key});
                   19906:             }
                   19907:         }
                   19908:         foreach my $key (keys(%possibles)) {
                   19909:             $newunique->{$key} = $possibles{$key};
                   19910:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19911:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19912:                 $addcourse->{$tsymb} = $key;
                   19913:             }
                   19914:         }
                   19915:     }
                   19916:     if (keys(%collisions)) {
                   19917:         if ($init <5) {
                   19918:             if (!$init) {
                   19919:                 $init = 1;
                   19920:             } else {
                   19921:                 $init ++;
                   19922:             }
                   19923:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19924:                                    $newunique,$addcourse,$courseonly,$failed);
                   19925:         } else {
                   19926:             foreach my $key (keys(%collisions)) {
                   19927:                 $failed->{$key} = 1;
                   19928:             }
                   19929:         }
                   19930:     }
                   19931:     return $init;
                   19932: }
                   19933: 
1.1328    raeburn  19934: sub is_nonframeable {
1.1329    raeburn  19935:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19936:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19937:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19938: 
                   19939:     $remprotocol = lc($remprotocol);
                   19940:     $remhost = lc($remhost);
                   19941:     my $remport = 80;
                   19942:     if ($remprotocol eq 'https') {
                   19943:         $remport = 443;
                   19944:     }
1.1330    raeburn  19945:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19946:     if ($cached) {
                   19947:         unless ($nocache) {
                   19948:             if ($result) {
                   19949:                 return 1;
                   19950:             } else {
                   19951:                 return 0;
                   19952:             }
                   19953:         }
                   19954:     }
1.1328    raeburn  19955:     my $uselink;
                   19956:     my $request = new HTTP::Request('HEAD',$url);
                   19957:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19958:     if ($response->is_success()) {
                   19959:         my $secpolicy = lc($response->header('content-security-policy'));
                   19960:         my $xframeop = lc($response->header('x-frame-options'));
                   19961:         $secpolicy =~ s/^\s+|\s+$//g;
                   19962:         $xframeop =~ s/^\s+|\s+$//g;
                   19963:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19964:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19965:             my ($origin,$protocol,$port);
                   19966:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19967:                 $port = $ENV{'SERVER_PORT'};
                   19968:             } else {
                   19969:                 $port = 80;
                   19970:             }
                   19971:             if ($absolute eq '') {
                   19972:                 $protocol = 'http:';
                   19973:                 if ($port == 443) {
                   19974:                     $protocol = 'https:';
                   19975:                 }
                   19976:                 $origin = $protocol.'//'.lc($hostname);
                   19977:             } else {
                   19978:                 $origin = lc($absolute);
                   19979:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19980:             }
                   19981:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19982:                 my $framepolicy = $1;
                   19983:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19984:                 my @policies = split(/\s+/,$framepolicy);
                   19985:                 if (@policies) {
                   19986:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19987:                         $uselink = 1;
                   19988:                     } else {
                   19989:                         $uselink = 1;
                   19990:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19991:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19992:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19993:                             undef($uselink);
                   19994:                         }
                   19995:                         if ($uselink) {
                   19996:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19997:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19998:                                     undef($uselink);
                   19999:                                 }
                   20000:                             }
                   20001:                         }
                   20002:                         if ($uselink) {
                   20003:                             my @possok;
                   20004:                             if ($ip ne '') {
                   20005:                                 push(@possok,$ip);
                   20006:                             }
                   20007:                             my $hoststr = '';
                   20008:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   20009:                                 if ($hoststr eq '') {
                   20010:                                     $hoststr = $part;
                   20011:                                 } else {
                   20012:                                     $hoststr = "$part.$hoststr";
                   20013:                                 }
                   20014:                                 if ($hoststr eq $hostname) {
                   20015:                                     push(@possok,$hostname);
                   20016:                                 } else {
                   20017:                                     push(@possok,"*.$hoststr");
                   20018:                                 }
                   20019:                             }
                   20020:                             if (@possok) {
                   20021:                                 foreach my $poss (@possok) {
                   20022:                                     last if (!$uselink);
                   20023:                                     foreach my $policy (@policies) {
                   20024:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   20025:                                             undef($uselink);
                   20026:                                             last;
                   20027:                                         }
                   20028:                                     }
                   20029:                                 }
                   20030:                             }
                   20031:                         }
                   20032:                     }
                   20033:                 }
                   20034:             } elsif ($xframeop ne '') {
                   20035:                 $uselink = 1;
                   20036:                 my @policies = split(/\s*,\s*/,$xframeop);
                   20037:                 if (@policies) {
                   20038:                     unless (grep(/^deny$/,@policies)) {
                   20039:                         if ($origin ne '') {
                   20040:                             if (grep(/^sameorigin$/,@policies)) {
                   20041:                                 if ($remotehost eq $origin) {
                   20042:                                     undef($uselink);
                   20043:                                 }
                   20044:                             }
                   20045:                             if ($uselink) {
                   20046:                                 foreach my $policy (@policies) {
                   20047:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   20048:                                         my $allowfrom = $1;
                   20049:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   20050:                                             undef($uselink);
                   20051:                                             last;
                   20052:                                         }
                   20053:                                     }
                   20054:                                 }
                   20055:                             }
                   20056:                         }
                   20057:                     }
                   20058:                 }
                   20059:             }
                   20060:         }
                   20061:     }
1.1329    raeburn  20062:     if ($nocache) {
                   20063:         if ($cached) {
                   20064:             my $devalidate;
                   20065:             if ($uselink && !$result) {
                   20066:                 $devalidate = 1;
                   20067:             } elsif (!$uselink && $result) {
                   20068:                 $devalidate = 1;
                   20069:             }
                   20070:             if ($devalidate) {
                   20071:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   20072:             }
                   20073:         }
                   20074:     } else {
                   20075:         if ($uselink) {
                   20076:             $result = 1;
                   20077:         } else {
                   20078:             $result = 0;
                   20079:         }
                   20080:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   20081:     }
1.1328    raeburn  20082:     return $uselink;
                   20083: }
                   20084: 
1.1359    raeburn  20085: sub page_menu {
                   20086:     my ($menucolls,$menunum) = @_;
                   20087:     my %menu;
                   20088:     foreach my $item (split(/;/,$menucolls)) {
                   20089:         my ($num,$value) = split(/\%/,$item);
                   20090:         if ($num eq $menunum) {
                   20091:             my @entries = split(/\&/,$value);
                   20092:             foreach my $entry (@entries) {
                   20093:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  20094:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  20095:                     $menu{$name} = $fields;
                   20096:                 } else {
                   20097:                     my @shown;
                   20098:                     if ($fields =~ /,/) {
                   20099:                         @shown = split(/,/,$fields);
                   20100:                     } else {
                   20101:                         @shown = ($fields);
                   20102:                     }
                   20103:                     if (@shown) {
                   20104:                         foreach my $field (@shown) {
                   20105:                             next if ($field eq '');
                   20106:                             $menu{$field} = 1;
                   20107:                         }
                   20108:                     }
                   20109:                 }
                   20110:             }
                   20111:         }
                   20112:     }
                   20113:     return %menu;
                   20114: }
                   20115: 
1.112     bowersj2 20116: 1;
                   20117: __END__;
1.41      ng       20118: 

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