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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1424  ! raeburn     4: # $Id: loncommon.pm,v 1.1423 2023/11/27 23:24:05 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: 
1.648     raeburn  1767: =back
1.565     albertel 1768: 
                   1769: =cut
                   1770: 
                   1771: sub resize_textarea_js {
1.590     raeburn  1772:     my $geometry = &viewport_geometry_js();
1.565     albertel 1773:     return <<"RESIZE";
                   1774:     <script type="text/javascript">
1.824     bisitz   1775: // <![CDATA[
1.590     raeburn  1776: $geometry
1.565     albertel 1777: 
1.588     albertel 1778: function getX(element) {
                   1779:     var x = 0;
                   1780:     while (element) {
                   1781: 	x += element.offsetLeft;
                   1782: 	element = element.offsetParent;
                   1783:     }
                   1784:     return x;
                   1785: }
                   1786: function getY(element) {
                   1787:     var y = 0;
                   1788:     while (element) {
                   1789: 	y += element.offsetTop;
                   1790: 	element = element.offsetParent;
                   1791:     }
                   1792:     return y;
                   1793: }
                   1794: 
                   1795: 
1.565     albertel 1796: function resize_textarea(textarea_id,bottom_id) {
                   1797:     init_geometry();
                   1798:     var textarea        = document.getElementById(textarea_id);
                   1799:     //alert(textarea);
                   1800: 
1.588     albertel 1801:     var textarea_top    = getY(textarea);
1.565     albertel 1802:     var textarea_height = textarea.offsetHeight;
                   1803:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1804:     var bottom_top      = getY(bottom);
1.565     albertel 1805:     var bottom_height   = bottom.offsetHeight;
                   1806:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1807:     var fudge           = 23;
1.565     albertel 1808:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1809:     if (new_height < 300) {
                   1810: 	new_height = 300;
                   1811:     }
                   1812:     textarea.style.height=new_height+'px';
                   1813: }
1.824     bisitz   1814: // ]]>
1.565     albertel 1815: </script>
                   1816: RESIZE
                   1817: 
                   1818: }
                   1819: 
1.1205    golterma 1820: sub colorfuleditor_js {
1.1248    raeburn  1821:     my $browse_or_search;
                   1822:     my $respath;
                   1823:     my ($cnum,$cdom) = &crsauthor_url();
                   1824:     if ($cnum) {
                   1825:         $respath = "/res/$cdom/$cnum/";
                   1826:         my %js_lt = &Apache::lonlocal::texthash(
                   1827:             sunm => 'Sub-directory name',
                   1828:             save => 'Save page to make this permanent',
                   1829:         );
                   1830:         &js_escape(\%js_lt);
1.1400    raeburn  1831:         my $showfile_js = &show_crsfiles_js();
1.1248    raeburn  1832:         $browse_or_search = <<"END";
                   1833: 
1.1400    raeburn  1834:     $showfile_js
                   1835: 
1.1248    raeburn  1836:     function toggleChooser(form,element,titleid,only,search) {
                   1837:         var disp = 'none';
                   1838:         if (document.getElementById('chooser_'+element)) {
                   1839:             var curr = document.getElementById('chooser_'+element).style.display;
                   1840:             if (curr == 'none') {
                   1841:                 disp='inline';
                   1842:                 if (form.elements['chooser_'+element].length) {
                   1843:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
                   1844:                         form.elements['chooser_'+element][i].checked = false;
                   1845:                     }
                   1846:                 }
                   1847:                 toggleResImport(form,element);
                   1848:             }
                   1849:             document.getElementById('chooser_'+element).style.display = disp;
1.1400    raeburn  1850:             var dirsel = '';
                   1851:             var filesel = '';
                   1852:             if (document.getElementById('chooser_'+element+'_crsres')) {
                   1853:                 var currcrsres = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1854:                 if (currcrsres == 'none') {
                   1855:                     dirsel = 'coursepath_'+element;
                   1856:                     var filesel = 'coursefile_'+element;
                   1857:                     var include;
                   1858:                     if (document.getElementById('crsres_include_'+element)) {
                   1859:                         include = document.getElementById('crsres_include_'+element).value;
                   1860:                     }
1.1402    raeburn  1861:                     populateCrsSelects(form,dirsel,filesel,1,include,1,0,1,1,0);
1.1400    raeburn  1862:                 }
                   1863:             }
                   1864:             if (document.getElementById('chooser_'+element+'_upload')) {
                   1865:                 var currcrsupload = document.getElementById('chooser_'+element+'_upload').style.display;
                   1866:                 if (currcrsupload == 'none') {
                   1867:                     dirsel = 'crsauthorpath_'+element;
                   1868:                     filesel = '';
1.1402    raeburn  1869:                     populateCrsSelects(form,dirsel,filesel,0,'',1,0,1,0,1);
1.1400    raeburn  1870:                 }
                   1871:             }
1.1248    raeburn  1872:         }
                   1873:     }
                   1874: 
1.1400    raeburn  1875:     function toggleCrsFile(form,element) {
1.1248    raeburn  1876:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1877:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
                   1878:             if (curr == 'none') {
1.1400    raeburn  1879:                 if (document.getElementById('coursepath_'+element)) {
                   1880:                     var numdirs;
                   1881:                     if (document.getElementById('coursepath_'+element).length) {
                   1882:                         numdirs = document.getElementById('coursepath_'+element).length;
                   1883:                     }
1.1402    raeburn  1884:                     if ((document.getElementById('hascrsres_'+element)) &&
                   1885:                         (document.getElementById('nocrsres_'+element))) {
                   1886:                         if (numdirs) {
                   1887:                             document.getElementById('hascrsres_'+element).style.display='inline-block';
                   1888:                             document.getElementById('nocrsres_'+element).style.display='none';
                   1889:                         } else {
                   1890:                             document.getElementById('hascrsres_'+element).style.display='none';
                   1891:                             document.getElementById('nocrsres_'+element).style.display='inline-block';
                   1892:                         }
                   1893:                     }
1.1248    raeburn  1894:                     form.elements['coursepath_'+element].selectedIndex = 0;
                   1895:                     if (numdirs > 1) {
1.1400    raeburn  1896:                         var selelem = form.elements['coursefile_'+element];
                   1897:                         var i, len = selelem.options.length -1;
                   1898:                         if (len >=0) {
                   1899:                             for (i = len; i >= 0; i--) {
                   1900:                                 selelem.remove(i);
                   1901:                             }
                   1902:                             selelem.options[0] = new Option('','');
                   1903:                         }
1.1248    raeburn  1904:                     }
                   1905:                 }
1.1400    raeburn  1906:             }
1.1248    raeburn  1907:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
                   1908:         }
                   1909:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1910:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
                   1911:             if (document.getElementById('uploadcrsres_'+element)) {
                   1912:                 document.getElementById('uploadcrsres_'+element).value = '';
                   1913:             }
                   1914:         }
                   1915:         return;
                   1916:     }
                   1917: 
1.1400    raeburn  1918:     function toggleCrsUpload(form,element) {
1.1248    raeburn  1919:         if (document.getElementById('chooser_'+element+'_crsres')) {
                   1920:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
                   1921:         }
                   1922:         if (document.getElementById('chooser_'+element+'_upload')) {
                   1923:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
                   1924:             if (curr == 'none') {
1.1400    raeburn  1925:                 form.elements['newsubdir_'+element][0].checked = true;
                   1926:                 toggleNewsubdir(form,element);
                   1927:                 document.getElementById('chooser_'+element+'_upload').style.display = 'block';
                   1928:                 if (document.getElementById('uploadcrsres_'+element)) {
                   1929:                     document.getElementById('uploadcrsres_'+element).value = '';
1.1248    raeburn  1930:                 }
                   1931:             }
                   1932:         }
                   1933:         return;
                   1934:     }
                   1935: 
                   1936:     function toggleResImport(form,element) {
                   1937:         var choices = new Array('crsres','upload');
                   1938:         for (var i=0; i<choices.length; i++) {
                   1939:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
                   1940:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
                   1941:             }
                   1942:         }
                   1943:     }
                   1944: 
                   1945:     function toggleNewsubdir(form,element) {
                   1946:         var newsub = form.elements['newsubdir_'+element];
                   1947:         if (newsub) {
                   1948:             if (newsub.length) {
                   1949:                 for (var j=0; j<newsub.length; j++) {
                   1950:                     if (newsub[j].checked) {
                   1951:                         if (document.getElementById('newsubdirname_'+element)) {
                   1952:                             if (newsub[j].value == '1') {
                   1953:                                 document.getElementById('newsubdirname_'+element).type = "text";
                   1954:                                 if (document.getElementById('newsubdir_'+element)) {
                   1955:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
                   1956:                                 }
                   1957:                             } else {
                   1958:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
                   1959:                                 document.getElementById('newsubdirname_'+element).value = "";
                   1960:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
                   1961:                             }
                   1962:                         }
                   1963:                         break; 
                   1964:                     }
                   1965:                 }
                   1966:             }
                   1967:         }
                   1968:     }
                   1969: 
                   1970:     function updateCrsFile(form,element) {
                   1971:         var directory = form.elements['coursepath_'+element];
                   1972:         var filename = form.elements['coursefile_'+element];
                   1973:         var path = directory.options[directory.selectedIndex].value;
                   1974:         var file = filename.options[filename.selectedIndex].value;
1.1400    raeburn  1975:         if (file != '') {
                   1976:             form.elements[element].value = '$respath';
                   1977:             if (path == '/') {
                   1978:                 form.elements[element].value += file;
                   1979:             } else {
                   1980:                 form.elements[element].value += path+'/'+file;
                   1981:             }
                   1982:             unClean();
                   1983:             if (document.getElementById('previewimg_'+element)) {
                   1984:                 document.getElementById('previewimg_'+element).src = form.elements[element].value;
                   1985:                 var newsrc = document.getElementById('previewimg_'+element).src; 
                   1986:             }
                   1987:             if (document.getElementById('showimg_'+element)) {
                   1988:                 document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
                   1989:             }
1.1248    raeburn  1990:         }
                   1991:         toggleChooser(form,element);
                   1992:         return;
                   1993:     }
                   1994: 
                   1995:     function uploadDone(suffix,name) {
                   1996:         if (name) {
                   1997: 	    document.forms["lonhomework"].elements[suffix].value = name;
                   1998:             unClean();
                   1999:             toggleChooser(document.forms["lonhomework"],suffix);
                   2000:         }
                   2001:     }
                   2002: 
                   2003: \$(document).ready(function(){
                   2004: 
                   2005:     \$(document).delegate('form :submit', 'click', function( event ) {
                   2006:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
                   2007:             var buttonId = this.id;
                   2008:             var suffix = buttonId.toString();
                   2009:             suffix = suffix.replace(/^crsupload_/,'');
                   2010:             event.preventDefault();
                   2011:             document.lonhomework.target = 'crsupload_target_'+suffix;
                   2012:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
                   2013:             \$(this.form).submit();
                   2014:             document.lonhomework.target = '';
                   2015:             if (document.getElementById('crsuploadto_'+suffix)) {
                   2016:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
                   2017:             }
                   2018:             return false;
                   2019:         }
                   2020:     });
                   2021: });
                   2022: END
                   2023:     }
1.1205    golterma 2024:     return <<"COLORFULEDIT"
                   2025: <script type="text/javascript">
                   2026: // <![CDATA[>
                   2027:     function fold_box(curDepth, lastresource){
                   2028: 
                   2029:     // we need a list because there can be several blocks you need to fold in one tag
                   2030:         var block = document.getElementsByName('foldblock_'+curDepth);
                   2031:     // but there is only one folding button per tag
                   2032:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   2033: 
                   2034:         if(block.item(0).style.display == 'none'){
                   2035: 
                   2036:             foldbutton.value = '@{[&mt("Hide")]}';
                   2037:             for (i = 0; i < block.length; i++){
                   2038:                 block.item(i).style.display = '';
                   2039:             }
                   2040:         }else{
                   2041: 
                   2042:             foldbutton.value = '@{[&mt("Show")]}';
                   2043:             for (i = 0; i < block.length; i++){
                   2044:                 // block.item(i).style.visibility = 'collapse';
                   2045:                 block.item(i).style.display = 'none';
                   2046:             }
                   2047:         };
                   2048:         saveState(lastresource);
                   2049:     }
                   2050: 
                   2051:     function saveState (lastresource) {
                   2052: 
                   2053:         var tag_list = getTagList();
                   2054:         if(tag_list != null){
                   2055:             var timestamp = new Date().getTime();
                   2056:             var key = lastresource;
                   2057: 
                   2058:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   2059:             // starting with timestamp
                   2060:             var value = timestamp+';';
                   2061: 
                   2062:             // building the list of key-value pairs
                   2063:             for(var i = 0; i < tag_list.length; i++){
                   2064:                 value += tag_list[i]+',';
                   2065:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   2066:             }
                   2067: 
                   2068:             // only iterate whole storage if nothing to override
                   2069:             if(localStorage.getItem(key) == null){        
                   2070: 
                   2071:                 // prevent storage from growing large
                   2072:                 if(localStorage.length > 50){
                   2073:                     var regex_getTimestamp = /^(?:\d)+;/;
                   2074:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   2075:                     var oldest_key;
                   2076:                     
                   2077:                     for(var i = 1; i < localStorage.length; i++){
                   2078:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   2079:                             oldest_key = localStorage.key(i);
                   2080:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   2081:                         }
                   2082:                     }
                   2083:                     localStorage.removeItem(oldest_key);
                   2084:                 }
                   2085:             }
                   2086:             localStorage.setItem(key,value);
                   2087:         }
                   2088:     }
                   2089: 
                   2090:     // restore folding status of blocks (on page load)
                   2091:     function restoreState (lastresource) {
                   2092:         if(localStorage.getItem(lastresource) != null){
                   2093:             var key = lastresource;
                   2094:             var value = localStorage.getItem(key);
                   2095:             var regex_delTimestamp = /^\d+;/;
                   2096: 
                   2097:             value.replace(regex_delTimestamp, '');
                   2098: 
                   2099:             var valueArr = value.split(';');
                   2100:             var pairs;
                   2101:             var elements;
                   2102:             for (var i = 0; i < valueArr.length; i++){
                   2103:                 pairs = valueArr[i].split(',');
                   2104:                 elements = document.getElementsByName(pairs[0]);
                   2105: 
                   2106:                 for (var j = 0; j < elements.length; j++){  
                   2107:                     elements[j].style.display = pairs[1];
                   2108:                     if (pairs[1] == "none"){
                   2109:                         var regex_id = /([_\\d]+)\$/;
                   2110:                         regex_id.exec(pairs[0]);
                   2111:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   2112:                     }
                   2113:                 }
                   2114:             }
                   2115:         }
                   2116:     }
                   2117: 
                   2118:     function getTagList () {
                   2119:         
                   2120:         var stringToSearch = document.lonhomework.innerHTML;
                   2121: 
                   2122:         var ret = new Array();
                   2123:         var regex_findBlock = /(foldblock_.*?)"/g;
                   2124:         var tag_list = stringToSearch.match(regex_findBlock);
                   2125: 
                   2126:         if(tag_list != null){
                   2127:             for(var i = 0; i < tag_list.length; i++){            
                   2128:                 ret.push(tag_list[i].replace(/"/, ''));
                   2129:             }
                   2130:         }
                   2131:         return ret;
                   2132:     }
                   2133: 
                   2134:     function saveScrollPosition (resource) {
                   2135:         var tag_list = getTagList();
                   2136: 
                   2137:         // we dont always want to jump to the first block
                   2138:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   2139:         if(\$(window).scrollTop() > 170){
                   2140:             if(tag_list != null){
                   2141:                 var result;
                   2142:                 for(var i = 0; i < tag_list.length; i++){
                   2143:                     if(isElementInViewport(tag_list[i])){
                   2144:                         result += tag_list[i]+';';
                   2145:                     }
                   2146:                 }
                   2147:                 sessionStorage.setItem('anchor_'+resource, result);
                   2148:             }
                   2149:         } else {
                   2150:             // we dont need to save zero, just delete the item to leave everything tidy
                   2151:             sessionStorage.removeItem('anchor_'+resource);
                   2152:         }
                   2153:     }
                   2154: 
                   2155:     function restoreScrollPosition(resource){
                   2156: 
                   2157:         var elem = sessionStorage.getItem('anchor_'+resource);
                   2158:         if(elem != null){
                   2159:             var tag_list = elem.split(';');
                   2160:             var elem_list;
                   2161: 
                   2162:             for(var i = 0; i < tag_list.length; i++){
                   2163:                 elem_list = document.getElementsByName(tag_list[i]);
                   2164:                 
                   2165:                 if(elem_list.length > 0){
                   2166:                     elem = elem_list[0];
                   2167:                     break;
                   2168:                 }
                   2169:             }
                   2170:             elem.scrollIntoView();
                   2171:         }
                   2172:     }
                   2173: 
                   2174:     function isElementInViewport(el) {
                   2175: 
                   2176:         // change to last element instead of first
                   2177:         var elem = document.getElementsByName(el);
                   2178:         var rect = elem[0].getBoundingClientRect();
                   2179: 
                   2180:         return (
                   2181:             rect.top >= 0 &&
                   2182:             rect.left >= 0 &&
                   2183:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   2184:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   2185:         );
                   2186:     }
                   2187:     
                   2188:     function autosize(depth){
                   2189:         var cmInst = window['cm'+depth];
                   2190:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   2191: 
                   2192:         // is fixed size, switching to dynamic
                   2193:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   2194:             cmInst.setSize("","auto");
                   2195:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   2196:             sessionStorage.setItem("autosized_"+depth, "yes");
                   2197: 
                   2198:         // is dynamic size, switching to fixed
                   2199:         } else {
                   2200:             cmInst.setSize("","300px");
                   2201:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   2202:             sessionStorage.removeItem("autosized_"+depth);
                   2203:         }
                   2204:     }
                   2205: 
1.1248    raeburn  2206: $browse_or_search
1.1205    golterma 2207: 
                   2208: // ]]>
                   2209: </script>
                   2210: COLORFULEDIT
                   2211: }
                   2212: 
                   2213: sub xmleditor_js {
                   2214:     return <<XMLEDIT
                   2215: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   2216: <script type="text/javascript">
                   2217: // <![CDATA[>
                   2218: 
                   2219:     function saveScrollPosition (resource) {
                   2220: 
                   2221:         var scrollPos = \$(window).scrollTop();
                   2222:         sessionStorage.setItem(resource,scrollPos);
                   2223:     }
                   2224: 
                   2225:     function restoreScrollPosition(resource){
                   2226: 
                   2227:         var scrollPos = sessionStorage.getItem(resource);
                   2228:         \$(window).scrollTop(scrollPos);
                   2229:     }
                   2230: 
                   2231:     // unless internet explorer
                   2232:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   2233: 
                   2234:         \$(document).ready(function() {
                   2235:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   2236:         });
                   2237:     }
                   2238: 
                   2239:     // inserts text at cursor position into codemirror (xml editor only)
                   2240:     function insertText(text){
                   2241:         cm.focus();
                   2242:         var curPos = cm.getCursor();
                   2243:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   2244:     }
                   2245: // ]]>
                   2246: </script>
                   2247: XMLEDIT
                   2248: }
                   2249: 
                   2250: sub insert_folding_button {
                   2251:     my $curDepth = $Apache::lonxml::curdepth;
                   2252:     my $lastresource = $env{'request.ambiguous'};
                   2253: 
                   2254:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   2255:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   2256: }
                   2257: 
1.1248    raeburn  2258: sub crsauthor_url {
                   2259:     my ($url) = @_;
                   2260:     if ($url eq '') {
                   2261:         $url = $ENV{'REQUEST_URI'};
                   2262:     }
                   2263:     my ($cnum,$cdom);
                   2264:     if ($env{'request.course.id'}) {
                   2265:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
                   2266:         if ($audom ne '' && $auname ne '') {
                   2267:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
                   2268:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
                   2269:                 $cnum = $auname;
                   2270:                 $cdom = $audom;
                   2271:             }
                   2272:         }
                   2273:     }
                   2274:     return ($cnum,$cdom);
                   2275: }
                   2276: 
                   2277: sub import_crsauthor_form {
1.1400    raeburn  2278:     my ($firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
1.1248    raeburn  2279:     return (0) unless ($env{'request.course.id'});
                   2280:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2281:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2282:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   2283:     return (0) unless (($cnum ne '') && ($cdom ne ''));
                   2284:     my @ids=&Apache::lonnet::current_machine_ids();
1.1400    raeburn  2285:     my ($output,$is_home,$toppath,%subdirs,%files,%selimport_menus,$include,$exclude);
1.1402    raeburn  2286: 
1.1248    raeburn  2287:     if (grep(/^\Q$crshome\E$/,@ids)) {
                   2288:         $is_home = 1;
                   2289:     }
1.1400    raeburn  2290:     $toppath = "/priv/$cdom/$cnum";
                   2291:     my $nonemptydir = 1;
                   2292:     my $js_only;
                   2293:     if ($only) {
                   2294:         map { $include->{$_} = 1; } split(/\s*,\s*/,$only);
                   2295:         $js_only = join(',',map { &js_escape($_); } sort(keys(%{$include})));
                   2296:     }
                   2297:     $exclude = &Apache::lonnet::priv_exclude();
1.1402    raeburn  2298:     &Apache::lonnet::recursedirs($is_home,1,$include,$exclude,1,0,$toppath,'',\%subdirs,\%files);
1.1400    raeburn  2299:     my $numdirs = scalar(keys(%files));
1.1248    raeburn  2300:     my %lt = &Apache::lonlocal::texthash (
                   2301:         fnam => 'Filename',
                   2302:         dire => 'Directory',
1.1400    raeburn  2303:         se   => 'Select',
1.1248    raeburn  2304:     );
1.1402    raeburn  2305:     $output = $lt{'dire'}.':&nbsp;'.
1.1400    raeburn  2306:               '<select id="'.$firstselectname.'" name="'.$firstselectname.'" '.
1.1402    raeburn  2307:               'onchange="populateCrsSelects(this.form,'."'$firstselectname','$secondselectname',1,'$js_only',0,1,0,0,0".');">'.
1.1400    raeburn  2308:               '<option value="" selected="selected">'.$lt{'se'}.'</option>';
1.1402    raeburn  2309:     if ($files{'/'}) {
                   2310:         $output .= '<option value="/">/</option>'."\n";
                   2311:     }
1.1400    raeburn  2312:     foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
1.1402    raeburn  2313:         next if ($key eq '/');
1.1400    raeburn  2314:         $output .= '<option value="'.$key.'">'.$key.'</option>'."\n";
                   2315:     }
                   2316:     $output .= '</select><br />'."\n".
1.1402    raeburn  2317:                $lt{'fnam'}.':&nbsp;<select id="'.$secondselectname.'" name="'.$secondselectname.'">'."\n".
1.1400    raeburn  2318:                '<option value="" selected="selected"></option>'."\n".
1.1402    raeburn  2319:                '</select>'."\n".
                   2320:                '<input type="hidden" id="crsres_include_'.$suffix.'" value="'.$only.'" />';
1.1400    raeburn  2321:     return ($numdirs,$output);
                   2322: }
                   2323: 
                   2324: sub show_crsfiles_js {
                   2325:     my $excluderef = &Apache::lonnet::priv_exclude();
                   2326:     my $se = &js_escape(&mt('Select'));
                   2327:     my $exclude;
                   2328:     if (ref($excluderef) eq 'HASH') {
                   2329:         $exclude = join(',', map { &js_escape($_); } sort(keys(%{$excluderef})));
                   2330:     }
                   2331:     my $js = <<"END";
                   2332: 
                   2333: 
1.1402    raeburn  2334:     function populateCrsSelects (form,dirsel,filesel,exc,include,setdir,setfile,recurse,nonemptydir,addtopdir) {
1.1400    raeburn  2335:         var relpath = '';
                   2336:         if ((setfile) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2337:             var currdir = form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value;
                   2338:             if (currdir == '') {
                   2339:                 if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2340:                     selelem = form.elements[filesel];
                   2341:                     var j, numfiles = selelem.options.length -1;
                   2342:                     if (numfiles >=0) {
                   2343:                         for (j = numfiles; j >= 0; j--) {
                   2344:                             selelem.remove(j);
                   2345:                         }
                   2346:                     }
                   2347:                     if (selelem.options.length == 0) {
                   2348:                         selelem.options[selelem.options.length] = new Option('','');
                   2349:                         selelem.selectedIndex = 0;
1.1248    raeburn  2350:                     }
                   2351:                 }
1.1400    raeburn  2352:                 return;
                   2353:             } else {
                   2354:                 relpath = encodeURIComponent(form.elements[dirsel].options[form.elements[dirsel].selectedIndex].value);
1.1248    raeburn  2355:             }
                   2356:         }
1.1400    raeburn  2357:         var http = new XMLHttpRequest();
                   2358:         var url = "/adm/courseauthor";
                   2359:         var crsrole = "$env{'request.role'}";
                   2360:         var exclude = '';
                   2361:         if (exc) {
                   2362:             exclude = '$exclude';
                   2363:         }
1.1402    raeburn  2364:         var params = "role=course&files=1&rec="+recurse+"&nonempty="+nonemptydir+"&exc="+exclude+"&inc="+include+"&addtop="+addtopdir+"&path="+relpath;
1.1400    raeburn  2365:         http.open("POST", url, true);
                   2366:         http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   2367:         http.onreadystatechange = function() {
                   2368:             if (http.readyState == 4 && http.status == 200) {
                   2369:                 var data = JSON.parse(http.responseText);
                   2370:                 var selelem;
                   2371:                 if ((setdir) && (dirsel != null) && (dirsel != 'undefined') && (dirsel != '')) {
                   2372:                     if (Array.isArray(data.dirs)) {
                   2373:                         selelem = form.elements[dirsel];
                   2374:                         var i, numdirs = selelem.options.length -1;
                   2375:                         if (numdirs >=0) {
                   2376:                             for (i = numdirs; i >= 0; i--) {
                   2377:                                 selelem.remove(i);
                   2378:                             }
                   2379:                         }
                   2380:                         var len = data.dirs.length;
                   2381:                         if (len) {
1.1402    raeburn  2382:                             selelem.options[selelem.options.length] = new Option('$se','');
1.1400    raeburn  2383:                             var j;
                   2384:                             for (j = 0; j < len; j++) {
                   2385:                                 selelem.options[selelem.options.length] = new Option(data.dirs[j],data.dirs[j]);
                   2386:                             }
                   2387:                             selelem.selectedIndex = 0;
                   2388:                         }
                   2389:                         if (!setfile) {
                   2390:                             if ((filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2391:                                 selelem = form.elements[filesel];
                   2392:                                 var j, numfiles = selelem.options.length -1;
                   2393:                                 if (numfiles >=0) {
                   2394:                                     for (j = numfiles; j >= 0; j--) {
                   2395:                                         selelem.remove(j);
                   2396:                                     }
                   2397:                                 }
                   2398:                                 if (selelem.options.length == 0) {
                   2399:                                     selelem.options[selelem.options.length] = new Option('','');
                   2400:                                     selelem.selectedIndex = 0;
                   2401:                                 }
                   2402:                             }
                   2403:                         }
                   2404:                     }
                   2405:                 }
                   2406:                 if ((setfile) && (filesel != null) && (filesel != 'undefined') && (filesel != '')) {
                   2407:                     selelem = form.elements[filesel];
                   2408:                     var i, numfiles = selelem.options.length -1;
                   2409:                     if (numfiles >=0) {
                   2410:                         for (i = numfiles; i >= 0; i--) {
                   2411:                             selelem.remove(i);
                   2412:                         }
                   2413:                     }
                   2414:                     var x;
                   2415:                     for (x in data.files) {
                   2416:                         if (Array.isArray(data.files[x])) {
                   2417:                             if (data.files[x].length > 1) {
                   2418:                                 selelem.options[selelem.options.length] = new Option('$se','');
                   2419:                             }
                   2420:                             var len = data.files[x].length;
                   2421:                             if (len) {
                   2422:                                 var k;
                   2423:                                 for (k = 0; k < len; k++) {
                   2424:                                     selelem.options[selelem.options.length] = new Option(data.files[x][k],data.files[x][k]);
                   2425:                                 }
                   2426:                                 selelem.selectedIndex = 0;
                   2427:                             }
                   2428:                         }
                   2429:                     }
                   2430:                     if (selelem.options.length == 0) {
                   2431:                         selelem.options[selelem.options.length] = new Option('','');
                   2432:                         selelem.selectedIndex = 0;
                   2433:                     }
1.1248    raeburn  2434:                 }
                   2435:             }
                   2436:         }
1.1400    raeburn  2437:         http.send(params);
1.1248    raeburn  2438:     }
1.1400    raeburn  2439: END
1.1248    raeburn  2440: }
                   2441: 
1.565     albertel 2442: =pod
                   2443: 
1.1420    raeburn  2444: =item * &iframe_wrapper_headjs()
                   2445: 
                   2446: #
                   2447: # Where iframe is in use, if window.onload() executes before the custom resize function
                   2448: # has been defined (jQuery), two global javascript vars (LCnotready and LCresizedef)
                   2449: # are used to ensure document.ready() triggers a call to resize, so the iframe contents
                   2450: # do not obscure the Functions menu.
                   2451: #
                   2452: 
                   2453: =back
                   2454: 
                   2455: =cut
                   2456: 
                   2457: 
                   2458: sub iframe_wrapper_headjs {
                   2459:     return <<"ENDJS";
                   2460: <script type="text/javascript">
                   2461: // <![CDATA[
                   2462: var LCnotready = 0;
                   2463: var LCresizedef = 0;
                   2464: // ]]>
                   2465: </script>
                   2466: 
                   2467: ENDJS
                   2468: 
                   2469: }
                   2470: 
                   2471: =pod
                   2472: 
                   2473: =item * &iframe_wrapper_resizejs()
                   2474: 
                   2475: #
                   2476: # jQuery to use when iframe is in use and a page resize occurs.
                   2477: # This script will ensure that the iframe does not obscure any
                   2478: # standard LON-CAPA inline menus (primary, secondary, and/or
                   2479: # breadcrumbs and Functions menus. Expects javascript from
                   2480: # &iframe_wrapper_headjs() to be in head portion of the web page,
                   2481: # e.g., by inclusion in second arg passed to &start_page().
                   2482: #
                   2483: 
                   2484: =back
                   2485: 
                   2486: =cut
                   2487: 
                   2488: sub iframe_wrapper_resizejs {
                   2489:     my $offset = 5;
                   2490:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['inhibitmenu']);
                   2491:     if (($env{'form.inhibitmenu'} eq 'yes') || ($env{'form.only_body'})) {
                   2492:         $offset = 0;
                   2493:     }
                   2494:     return &Apache::lonhtmlcommon::scripttag(<<SCRIPT);
                   2495:     \$(document).ready( function() {
                   2496:         \$(window).unbind('resize').resize(function(){
                   2497:             var header = null;
                   2498:             var offset = $offset;
                   2499:             var height = 0;
                   2500:             var hdrtop = 0;
1.1421    raeburn  2501:             if (\$('div.LC_menus_content:first').length) {
                   2502:                 if (\$('div.LC_menus_content:first').hasClass ("shown")) {
                   2503:                     header = \$('div.LC_menus_content:first');
1.1423    raeburn  2504:                     offset = 12;
1.1421    raeburn  2505:                 }
                   2506:             } else if (\$('div.LC_head_subbox:first').length) {
1.1420    raeburn  2507:                 header = \$('div.LC_head_subbox:first');
                   2508:                 offset = 9;
                   2509:             } else {
                   2510:                 if (\$('#LC_breadcrumbs').length) {
                   2511:                     header = \$('#LC_breadcrumbs');
                   2512:                 }
                   2513:             }
                   2514:             if (header != null && header.length) {
                   2515:                 height = header.height();
                   2516:                 hdrtop = header.position().top;
                   2517:             }
                   2518:             var pos = height + hdrtop + offset;
                   2519:             \$('.LC_iframecontainer').css('top', pos);
                   2520:         });
                   2521:         LCresizedef = 1;
                   2522:         if (LCnotready == 1) {
                   2523:             LCnotready = 0;
                   2524:             \$(window).trigger('resize');
                   2525:         }
                   2526:     });
                   2527:     window.onload = function(){
                   2528:          if (LCresizedef) {
                   2529:              LCnotready = 0;
                   2530:              \$(window).trigger('resize');
                   2531:          } else {
                   2532:              LCnotready = 1;
                   2533:          }
                   2534:     };
                   2535: SCRIPT
                   2536: 
                   2537: }
                   2538: 
                   2539: =pod
                   2540: 
1.256     matthew  2541: =head1 Excel and CSV file utility routines
                   2542: 
                   2543: =cut
                   2544: 
                   2545: ###############################################################
                   2546: ###############################################################
                   2547: 
                   2548: =pod
                   2549: 
1.1162    raeburn  2550: =over 4
                   2551: 
1.648     raeburn  2552: =item * &csv_translate($text) 
1.37      matthew  2553: 
1.185     www      2554: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2555: format.
                   2556: 
                   2557: =cut
                   2558: 
1.180     matthew  2559: ###############################################################
                   2560: ###############################################################
1.37      matthew  2561: sub csv_translate {
                   2562:     my $text = shift;
                   2563:     $text =~ s/\"/\"\"/g;
1.209     albertel 2564:     $text =~ s/\n/ /g;
1.37      matthew  2565:     return $text;
                   2566: }
1.180     matthew  2567: 
                   2568: ###############################################################
                   2569: ###############################################################
                   2570: 
                   2571: =pod
                   2572: 
1.648     raeburn  2573: =item * &define_excel_formats()
1.180     matthew  2574: 
                   2575: Define some commonly used Excel cell formats.
                   2576: 
                   2577: Currently supported formats:
                   2578: 
                   2579: =over 4
                   2580: 
                   2581: =item header
                   2582: 
                   2583: =item bold
                   2584: 
                   2585: =item h1
                   2586: 
                   2587: =item h2
                   2588: 
                   2589: =item h3
                   2590: 
1.256     matthew  2591: =item h4
                   2592: 
                   2593: =item i
                   2594: 
1.180     matthew  2595: =item date
                   2596: 
                   2597: =back
                   2598: 
                   2599: Inputs: $workbook
                   2600: 
                   2601: Returns: $format, a hash reference.
                   2602: 
1.1057    foxr     2603: 
1.180     matthew  2604: =cut
                   2605: 
                   2606: ###############################################################
                   2607: ###############################################################
                   2608: sub define_excel_formats {
                   2609:     my ($workbook) = @_;
                   2610:     my $format;
                   2611:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2612:                                                 bottom    => 1,
                   2613:                                                 align     => 'center');
                   2614:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2615:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2616:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2617:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2618:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2619:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2620:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2621:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2622:     return $format;
                   2623: }
                   2624: 
                   2625: ###############################################################
                   2626: ###############################################################
1.113     bowersj2 2627: 
                   2628: =pod
                   2629: 
1.648     raeburn  2630: =item * &create_workbook()
1.255     matthew  2631: 
                   2632: Create an Excel worksheet.  If it fails, output message on the
                   2633: request object and return undefs.
                   2634: 
                   2635: Inputs: Apache request object
                   2636: 
                   2637: Returns (undef) on failure, 
                   2638:     Excel worksheet object, scalar with filename, and formats 
                   2639:     from &Apache::loncommon::define_excel_formats on success
                   2640: 
                   2641: =cut
                   2642: 
                   2643: ###############################################################
                   2644: ###############################################################
                   2645: sub create_workbook {
                   2646:     my ($r) = @_;
                   2647:         #
                   2648:     # Create the excel spreadsheet
                   2649:     my $filename = '/prtspool/'.
1.258     albertel 2650:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2651:         time.'_'.rand(1000000000).'.xls';
                   2652:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2653:     if (! defined($workbook)) {
                   2654:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2655:         $r->print(
                   2656:             '<p class="LC_error">'
                   2657:            .&mt('Problems occurred in creating the new Excel file.')
                   2658:            .' '.&mt('This error has been logged.')
                   2659:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2660:            .'</p>'
                   2661:         );
1.255     matthew  2662:         return (undef);
                   2663:     }
                   2664:     #
1.1014    foxr     2665:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2666:     #
                   2667:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2668:     return ($workbook,$filename,$format);
                   2669: }
                   2670: 
                   2671: ###############################################################
                   2672: ###############################################################
                   2673: 
                   2674: =pod
                   2675: 
1.648     raeburn  2676: =item * &create_text_file()
1.113     bowersj2 2677: 
1.542     raeburn  2678: Create a file to write to and eventually make available to the user.
1.256     matthew  2679: If file creation fails, outputs an error message on the request object and 
                   2680: return undefs.
1.113     bowersj2 2681: 
1.256     matthew  2682: Inputs: Apache request object, and file suffix
1.113     bowersj2 2683: 
1.256     matthew  2684: Returns (undef) on failure, 
                   2685:     Filehandle and filename on success.
1.113     bowersj2 2686: 
                   2687: =cut
                   2688: 
1.256     matthew  2689: ###############################################################
                   2690: ###############################################################
                   2691: sub create_text_file {
                   2692:     my ($r,$suffix) = @_;
                   2693:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2694:     my $fh;
                   2695:     my $filename = '/prtspool/'.
1.258     albertel 2696:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2697:         time.'_'.rand(1000000000).'.'.$suffix;
                   2698:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2699:     if (! defined($fh)) {
                   2700:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2701:         $r->print(
                   2702:             '<p class="LC_error">'
                   2703:            .&mt('Problems occurred in creating the output file.')
                   2704:            .' '.&mt('This error has been logged.')
                   2705:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2706:            .'</p>'
                   2707:         );
1.113     bowersj2 2708:     }
1.256     matthew  2709:     return ($fh,$filename)
1.113     bowersj2 2710: }
                   2711: 
                   2712: 
1.256     matthew  2713: =pod 
1.113     bowersj2 2714: 
                   2715: =back
                   2716: 
                   2717: =cut
1.37      matthew  2718: 
                   2719: ###############################################################
1.33      matthew  2720: ##        Home server <option> list generating code          ##
                   2721: ###############################################################
1.35      matthew  2722: 
1.169     www      2723: # ------------------------------------------
                   2724: 
                   2725: sub domain_select {
1.1289    raeburn  2726:     my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
                   2727:     my @possdoms;
                   2728:     if (ref($incdoms) eq 'ARRAY') {
                   2729:         @possdoms = @{$incdoms};
                   2730:     } else {
                   2731:         @possdoms = &Apache::lonnet::all_domains();
                   2732:     }
                   2733: 
1.169     www      2734:     my %domains=map { 
1.514     albertel 2735: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.1289    raeburn  2736:     } @possdoms;
                   2737: 
                   2738:     if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
                   2739:         foreach my $dom (@{$excdoms}) {
                   2740:             delete($domains{$dom});
                   2741:         }
                   2742:     }
                   2743: 
1.169     www      2744:     if ($multiple) {
                   2745: 	$domains{''}=&mt('Any domain');
1.550     albertel 2746: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2747: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2748:     } else {
1.550     albertel 2749: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2750: 	return &select_form($name,$value,\%domains);
1.169     www      2751:     }
                   2752: }
                   2753: 
1.282     albertel 2754: #-------------------------------------------
                   2755: 
                   2756: =pod
                   2757: 
1.519     raeburn  2758: =head1 Routines for form select boxes
                   2759: 
                   2760: =over 4
                   2761: 
1.648     raeburn  2762: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2763: 
                   2764: Returns a string containing a <select> element int multiple mode
                   2765: 
                   2766: 
                   2767: Args:
                   2768:   $name - name of the <select> element
1.506     raeburn  2769:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2770:   $size - number of rows long the select element is
1.283     albertel 2771:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2772:           (shown text should already have been &mt())
1.506     raeburn  2773:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2774: 
1.282     albertel 2775: =cut
                   2776: 
                   2777: #-------------------------------------------
1.169     www      2778: sub multiple_select_form {
1.284     albertel 2779:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2780:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2781:     my $output='';
1.191     matthew  2782:     if (! defined($size)) {
                   2783:         $size = 4;
1.283     albertel 2784:         if (scalar(keys(%$hash))<4) {
                   2785:             $size = scalar(keys(%$hash));
1.191     matthew  2786:         }
                   2787:     }
1.734     bisitz   2788:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2789:     my @order;
1.506     raeburn  2790:     if (ref($order) eq 'ARRAY')  {
                   2791:         @order = @{$order};
                   2792:     } else {
                   2793:         @order = sort(keys(%$hash));
1.501     banghart 2794:     }
                   2795:     if (exists($$hash{'select_form_order'})) {
                   2796:         @order = @{$$hash{'select_form_order'}};
                   2797:     }
                   2798:         
1.284     albertel 2799:     foreach my $key (@order) {
1.356     albertel 2800:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2801:         $output.='selected="selected" ' if ($selected{$key});
                   2802:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2803:     }
                   2804:     $output.="</select>\n";
                   2805:     return $output;
                   2806: }
                   2807: 
1.88      www      2808: #-------------------------------------------
                   2809: 
                   2810: =pod
                   2811: 
1.1254    raeburn  2812: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2813: 
                   2814: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2815: allow a user to select options from a ref to a hash containing:
                   2816: option_name => displayed text. An optional $onchange can include
1.1254    raeburn  2817: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2818: An optional arg -- $readonly -- if true will cause the select form
                   2819: to be disabled, e.g., for the case where an instructor has a section-
                   2820: specific role, and is viewing/modifying parameters. 
1.970     raeburn  2821: 
1.88      www      2822: See lonrights.pm for an example invocation and use.
                   2823: 
                   2824: =cut
                   2825: 
                   2826: #-------------------------------------------
                   2827: sub select_form {
1.1228    raeburn  2828:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2829:     return unless (ref($hashref) eq 'HASH');
                   2830:     if ($onchange) {
                   2831:         $onchange = ' onchange="'.$onchange.'"';
                   2832:     }
1.1228    raeburn  2833:     my $disabled;
                   2834:     if ($readonly) {
                   2835:         $disabled = ' disabled="disabled"';
                   2836:     }
                   2837:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2838:     my @keys;
1.970     raeburn  2839:     if (exists($hashref->{'select_form_order'})) {
                   2840: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2841:     } else {
1.970     raeburn  2842: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2843:     }
1.356     albertel 2844:     foreach my $key (@keys) {
                   2845:         $selectform.=
                   2846: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2847:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2848:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2849:     }
                   2850:     $selectform.="</select>";
                   2851:     return $selectform;
                   2852: }
                   2853: 
1.475     www      2854: # For display filters
                   2855: 
                   2856: sub display_filter {
1.1074    raeburn  2857:     my ($context) = @_;
1.475     www      2858:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2859:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2860:     my $phraseinput = 'hidden';
                   2861:     my $includeinput = 'hidden';
                   2862:     my ($checked,$includetypestext);
                   2863:     if ($env{'form.displayfilter'} eq 'containing') {
                   2864:         $phraseinput = 'text'; 
                   2865:         if ($context eq 'parmslog') {
                   2866:             $includeinput = 'checkbox';
                   2867:             if ($env{'form.includetypes'}) {
                   2868:                 $checked = ' checked="checked"';
                   2869:             }
                   2870:             $includetypestext = &mt('Include parameter types');
                   2871:         }
                   2872:     } else {
                   2873:         $includetypestext = '&nbsp;';
                   2874:     }
                   2875:     my ($additional,$secondid,$thirdid);
                   2876:     if ($context eq 'parmslog') {
                   2877:         $additional = 
                   2878:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2879:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2880:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2881:             '</label>';
                   2882:         $secondid = 'includetypes';
                   2883:         $thirdid = 'includetypestext';
                   2884:     }
                   2885:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2886:                                                     '$secondid','$thirdid')";
                   2887:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.1403    raeburn  2888: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},'',undef,
1.475     www      2889: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2890: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2891:            &mt('Filter: [_1]',
1.477     www      2892: 	   &select_form($env{'form.displayfilter'},
                   2893: 			'displayfilter',
1.970     raeburn  2894: 			{'currentfolder' => 'Current folder/page',
1.477     www      2895: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2896: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2897: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2898:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2899:                          '" />'.$additional;
                   2900: }
                   2901: 
                   2902: sub display_filter_js {
                   2903:     my $includetext = &mt('Include parameter types');
                   2904:     return <<"ENDJS";
                   2905:   
                   2906: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2907:     var firstType = 'hidden';
                   2908:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2909:         firstType = 'text';
                   2910:     }
                   2911:     firstObject = document.getElementById(firstid);
                   2912:     if (typeof(firstObject) == 'object') {
                   2913:         if (firstObject.type != firstType) {
                   2914:             changeInputType(firstObject,firstType);
                   2915:         }
                   2916:     }
                   2917:     if (context == 'parmslog') {
                   2918:         var secondType = 'hidden';
                   2919:         if (firstType == 'text') {
                   2920:             secondType = 'checkbox';
                   2921:         }
                   2922:         secondObject = document.getElementById(secondid);  
                   2923:         if (typeof(secondObject) == 'object') {
                   2924:             if (secondObject.type != secondType) {
                   2925:                 changeInputType(secondObject,secondType);
                   2926:             }
                   2927:         }
                   2928:         var textItem = document.getElementById(thirdid);
                   2929:         var currtext = textItem.innerHTML;
                   2930:         var newtext;
                   2931:         if (firstType == 'text') {
                   2932:             newtext = '$includetext';
                   2933:         } else {
                   2934:             newtext = '&nbsp;';
                   2935:         }
                   2936:         if (currtext != newtext) {
                   2937:             textItem.innerHTML = newtext;
                   2938:         }
                   2939:     }
                   2940:     return;
                   2941: }
                   2942: 
                   2943: function changeInputType(oldObject,newType) {
                   2944:     var newObject = document.createElement('input');
                   2945:     newObject.type = newType;
                   2946:     if (oldObject.size) {
                   2947:         newObject.size = oldObject.size;
                   2948:     }
                   2949:     if (oldObject.value) {
                   2950:         newObject.value = oldObject.value;
                   2951:     }
                   2952:     if (oldObject.name) {
                   2953:         newObject.name = oldObject.name;
                   2954:     }
                   2955:     if (oldObject.id) {
                   2956:         newObject.id = oldObject.id;
                   2957:     }
                   2958:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2959:     return;
                   2960: }
                   2961: 
                   2962: ENDJS
1.475     www      2963: }
                   2964: 
1.167     www      2965: sub gradeleveldescription {
                   2966:     my $gradelevel=shift;
                   2967:     my %gradelevels=(0 => 'Not specified',
                   2968: 		     1 => 'Grade 1',
                   2969: 		     2 => 'Grade 2',
                   2970: 		     3 => 'Grade 3',
                   2971: 		     4 => 'Grade 4',
                   2972: 		     5 => 'Grade 5',
                   2973: 		     6 => 'Grade 6',
                   2974: 		     7 => 'Grade 7',
                   2975: 		     8 => 'Grade 8',
                   2976: 		     9 => 'Grade 9',
                   2977: 		     10 => 'Grade 10',
                   2978: 		     11 => 'Grade 11',
                   2979: 		     12 => 'Grade 12',
                   2980: 		     13 => 'Grade 13',
                   2981: 		     14 => '100 Level',
                   2982: 		     15 => '200 Level',
                   2983: 		     16 => '300 Level',
                   2984: 		     17 => '400 Level',
                   2985: 		     18 => 'Graduate Level');
                   2986:     return &mt($gradelevels{$gradelevel});
                   2987: }
                   2988: 
1.163     www      2989: sub select_level_form {
                   2990:     my ($deflevel,$name)=@_;
                   2991:     unless ($deflevel) { $deflevel=0; }
1.167     www      2992:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2993:     for (my $i=0; $i<=18; $i++) {
                   2994:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2995:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2996:                 ">".&gradeleveldescription($i)."</option>\n";
                   2997:     }
                   2998:     $selectform.="</select>";
                   2999:     return $selectform;
1.163     www      3000: }
1.167     www      3001: 
1.35      matthew  3002: #-------------------------------------------
                   3003: 
1.45      matthew  3004: =pod
                   3005: 
1.1256    raeburn  3006: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  3007: 
                   3008: Returns a string containing a <select name='$name' size='1'> form to 
                   3009: allow a user to select the domain to preform an operation in.  
                   3010: See loncreateuser.pm for an example invocation and use.
                   3011: 
1.90      www      3012: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   3013: selected");
                   3014: 
1.743     raeburn  3015: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   3016: 
1.910     raeburn  3017: 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.
                   3018: 
1.1121    raeburn  3019: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   3020: 
                   3021: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  3022: 
1.1256    raeburn  3023: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
                   3024: 
1.35      matthew  3025: =cut
                   3026: 
                   3027: #-------------------------------------------
1.34      matthew  3028: sub select_dom_form {
1.1256    raeburn  3029:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  3030:     if ($onchange) {
1.874     raeburn  3031:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  3032:     }
1.1256    raeburn  3033:     if ($disabled) {
                   3034:         $disabled = ' disabled="disabled"';
                   3035:     }
1.1121    raeburn  3036:     my (@domains,%exclude);
1.910     raeburn  3037:     if (ref($incdoms) eq 'ARRAY') {
                   3038:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   3039:     } else {
                   3040:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   3041:     }
1.90      www      3042:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  3043:     if (ref($excdoms) eq 'ARRAY') {
                   3044:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   3045:     }
1.1256    raeburn  3046:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 3047:     foreach my $dom (@domains) {
1.1121    raeburn  3048:         next if ($exclude{$dom});
1.356     albertel 3049:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  3050:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   3051:         if ($showdomdesc) {
                   3052:             if ($dom ne '') {
                   3053:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3054:                 if ($domdesc ne '') {
                   3055:                     $selectdomain .= ' ('.$domdesc.')';
                   3056:                 }
                   3057:             } 
                   3058:         }
                   3059:         $selectdomain .= "</option>\n";
1.34      matthew  3060:     }
                   3061:     $selectdomain.="</select>";
                   3062:     return $selectdomain;
                   3063: }
                   3064: 
1.35      matthew  3065: #-------------------------------------------
                   3066: 
1.45      matthew  3067: =pod
                   3068: 
1.648     raeburn  3069: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  3070: 
1.586     raeburn  3071: input: 4 arguments (two required, two optional) - 
                   3072:     $domain - domain of new user
                   3073:     $name - name of form element
                   3074:     $default - Value of 'default' causes a default item to be first 
                   3075:                             option, and selected by default. 
                   3076:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   3077:                             if 1 server found, or default, if 0 found.
1.594     raeburn  3078: output: returns 2 items: 
1.586     raeburn  3079: (a) form element which contains either:
                   3080:    (i) <select name="$name">
                   3081:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   3082:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   3083:        </select>
                   3084:        form item if there are multiple library servers in $domain, or
                   3085:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   3086:        if there is only one library server in $domain.
                   3087: 
                   3088: (b) number of library servers found.
                   3089: 
                   3090: See loncreateuser.pm for example of use.
1.35      matthew  3091: 
                   3092: =cut
                   3093: 
                   3094: #-------------------------------------------
1.586     raeburn  3095: sub home_server_form_item {
                   3096:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 3097:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  3098:     my $result;
                   3099:     my $numlib = keys(%servers);
                   3100:     if ($numlib > 1) {
                   3101:         $result .= '<select name="'.$name.'" />'."\n";
                   3102:         if ($default) {
1.804     bisitz   3103:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  3104:                        '</option>'."\n";
                   3105:         }
                   3106:         foreach my $hostid (sort(keys(%servers))) {
                   3107:             $result.= '<option value="'.$hostid.'">'.
                   3108: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   3109:         }
                   3110:         $result .= '</select>'."\n";
                   3111:     } elsif ($numlib == 1) {
                   3112:         my $hostid;
                   3113:         foreach my $item (keys(%servers)) {
                   3114:             $hostid = $item;
                   3115:         }
                   3116:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   3117:                    $hostid.'" />';
                   3118:                    if (!$hide) {
                   3119:                        $result .= $hostid.' '.$servers{$hostid};
                   3120:                    }
                   3121:                    $result .= "\n";
                   3122:     } elsif ($default) {
                   3123:         $result .= '<input type="hidden" name="'.$name.
                   3124:                    '" value="default" />';
                   3125:                    if (!$hide) {
                   3126:                        $result .= &mt('default');
                   3127:                    }
                   3128:                    $result .= "\n";
1.33      matthew  3129:     }
1.586     raeburn  3130:     return ($result,$numlib);
1.33      matthew  3131: }
1.112     bowersj2 3132: 
                   3133: =pod
                   3134: 
1.534     albertel 3135: =back 
                   3136: 
1.112     bowersj2 3137: =cut
1.87      matthew  3138: 
                   3139: ###############################################################
1.112     bowersj2 3140: ##                  Decoding User Agent                      ##
1.87      matthew  3141: ###############################################################
                   3142: 
                   3143: =pod
                   3144: 
1.112     bowersj2 3145: =head1 Decoding the User Agent
                   3146: 
                   3147: =over 4
                   3148: 
                   3149: =item * &decode_user_agent()
1.87      matthew  3150: 
                   3151: Inputs: $r
                   3152: 
                   3153: Outputs:
                   3154: 
                   3155: =over 4
                   3156: 
1.112     bowersj2 3157: =item * $httpbrowser
1.87      matthew  3158: 
1.112     bowersj2 3159: =item * $clientbrowser
1.87      matthew  3160: 
1.112     bowersj2 3161: =item * $clientversion
1.87      matthew  3162: 
1.112     bowersj2 3163: =item * $clientmathml
1.87      matthew  3164: 
1.112     bowersj2 3165: =item * $clientunicode
1.87      matthew  3166: 
1.112     bowersj2 3167: =item * $clientos
1.87      matthew  3168: 
1.1137    raeburn  3169: =item * $clientmobile
                   3170: 
1.1141    raeburn  3171: =item * $clientinfo
                   3172: 
1.1194    raeburn  3173: =item * $clientosversion
                   3174: 
1.87      matthew  3175: =back
                   3176: 
1.157     matthew  3177: =back 
                   3178: 
1.87      matthew  3179: =cut
                   3180: 
                   3181: ###############################################################
                   3182: ###############################################################
                   3183: sub decode_user_agent {
1.247     albertel 3184:     my ($r)=@_;
1.87      matthew  3185:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   3186:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   3187:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 3188:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  3189:     my $clientbrowser='unknown';
                   3190:     my $clientversion='0';
                   3191:     my $clientmathml='';
                   3192:     my $clientunicode='0';
1.1137    raeburn  3193:     my $clientmobile=0;
1.1194    raeburn  3194:     my $clientosversion='';
1.87      matthew  3195:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  3196:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  3197: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   3198: 	    $clientbrowser=$bname;
                   3199:             $httpbrowser=~/$vreg/i;
                   3200: 	    $clientversion=$1;
                   3201:             $clientmathml=($clientversion>=$minv);
                   3202:             $clientunicode=($clientversion>=$univ);
                   3203: 	}
                   3204:     }
                   3205:     my $clientos='unknown';
1.1141    raeburn  3206:     my $clientinfo;
1.87      matthew  3207:     if (($httpbrowser=~/linux/i) ||
                   3208:         ($httpbrowser=~/unix/i) ||
                   3209:         ($httpbrowser=~/ux/i) ||
                   3210:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   3211:     if (($httpbrowser=~/vax/i) ||
                   3212:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   3213:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   3214:     if (($httpbrowser=~/mac/i) ||
                   3215:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  3216:     if ($httpbrowser=~/win/i) {
                   3217:         $clientos='win';
                   3218:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   3219:             $clientosversion = $1;
                   3220:         }
                   3221:     }
1.87      matthew  3222:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  3223:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   3224:         $clientmobile=lc($1);
                   3225:     }
1.1141    raeburn  3226:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   3227:         $clientinfo = 'firefox-'.$1;
                   3228:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   3229:         $clientinfo = 'chromeframe-'.$1;
                   3230:     }
1.87      matthew  3231:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  3232:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   3233:             $clientosversion);
1.87      matthew  3234: }
                   3235: 
1.32      matthew  3236: ###############################################################
                   3237: ##    Authentication changing form generation subroutines    ##
                   3238: ###############################################################
                   3239: ##
                   3240: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   3241: ## hash, and have reasonable default values.
                   3242: ##
                   3243: ##    formname = the name given in the <form> tag.
1.35      matthew  3244: #-------------------------------------------
                   3245: 
1.45      matthew  3246: =pod
                   3247: 
1.112     bowersj2 3248: =head1 Authentication Routines
                   3249: 
                   3250: =over 4
                   3251: 
1.648     raeburn  3252: =item * &authform_xxxxxx()
1.35      matthew  3253: 
                   3254: The authform_xxxxxx subroutines provide javascript and html forms which 
                   3255: handle some of the conveniences required for authentication forms.  
                   3256: This is not an optimal method, but it works.  
                   3257: 
                   3258: =over 4
                   3259: 
1.112     bowersj2 3260: =item * authform_header
1.35      matthew  3261: 
1.112     bowersj2 3262: =item * authform_authorwarning
1.35      matthew  3263: 
1.112     bowersj2 3264: =item * authform_nochange
1.35      matthew  3265: 
1.112     bowersj2 3266: =item * authform_kerberos
1.35      matthew  3267: 
1.112     bowersj2 3268: =item * authform_internal
1.35      matthew  3269: 
1.112     bowersj2 3270: =item * authform_filesystem
1.35      matthew  3271: 
1.1310    raeburn  3272: =item * authform_lti
                   3273: 
1.35      matthew  3274: =back
                   3275: 
1.648     raeburn  3276: See loncreateuser.pm for invocation and use examples.
1.157     matthew  3277: 
1.35      matthew  3278: =cut
                   3279: 
                   3280: #-------------------------------------------
1.32      matthew  3281: sub authform_header{  
                   3282:     my %in = (
                   3283:         formname => 'cu',
1.80      albertel 3284:         kerb_def_dom => '',
1.32      matthew  3285:         @_,
                   3286:     );
                   3287:     $in{'formname'} = 'document.' . $in{'formname'};
                   3288:     my $result='';
1.80      albertel 3289: 
                   3290: #---------------------------------------------- Code for upper case translation
                   3291:     my $Javascript_toUpperCase;
                   3292:     unless ($in{kerb_def_dom}) {
                   3293:         $Javascript_toUpperCase =<<"END";
                   3294:         switch (choice) {
                   3295:            case 'krb': currentform.elements[choicearg].value =
                   3296:                currentform.elements[choicearg].value.toUpperCase();
                   3297:                break;
                   3298:            default:
                   3299:         }
                   3300: END
                   3301:     } else {
                   3302:         $Javascript_toUpperCase = "";
                   3303:     }
                   3304: 
1.165     raeburn  3305:     my $radioval = "'nochange'";
1.591     raeburn  3306:     if (defined($in{'curr_authtype'})) {
                   3307:         if ($in{'curr_authtype'} ne '') {
                   3308:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   3309:         }
1.174     matthew  3310:     }
1.165     raeburn  3311:     my $argfield = 'null';
1.591     raeburn  3312:     if (defined($in{'mode'})) {
1.165     raeburn  3313:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  3314:             if (defined($in{'curr_autharg'})) {
                   3315:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  3316:                     $argfield = "'$in{'curr_autharg'}'";
                   3317:                 }
                   3318:             }
                   3319:         }
                   3320:     }
                   3321: 
1.32      matthew  3322:     $result.=<<"END";
                   3323: var current = new Object();
1.165     raeburn  3324: current.radiovalue = $radioval;
                   3325: current.argfield = $argfield;
1.32      matthew  3326: 
                   3327: function changed_radio(choice,currentform) {
                   3328:     var choicearg = choice + 'arg';
                   3329:     // If a radio button in changed, we need to change the argfield
                   3330:     if (current.radiovalue != choice) {
                   3331:         current.radiovalue = choice;
                   3332:         if (current.argfield != null) {
                   3333:             currentform.elements[current.argfield].value = '';
                   3334:         }
                   3335:         if (choice == 'nochange') {
                   3336:             current.argfield = null;
                   3337:         } else {
                   3338:             current.argfield = choicearg;
                   3339:             switch(choice) {
                   3340:                 case 'krb': 
                   3341:                     currentform.elements[current.argfield].value = 
                   3342:                         "$in{'kerb_def_dom'}";
                   3343:                 break;
                   3344:               default:
                   3345:                 break;
                   3346:             }
                   3347:         }
                   3348:     }
                   3349:     return;
                   3350: }
1.22      www      3351: 
1.32      matthew  3352: function changed_text(choice,currentform) {
                   3353:     var choicearg = choice + 'arg';
                   3354:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 3355:         $Javascript_toUpperCase
1.32      matthew  3356:         // clear old field
                   3357:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   3358:             currentform.elements[current.argfield].value = '';
                   3359:         }
                   3360:         current.argfield = choicearg;
                   3361:     }
                   3362:     set_auth_radio_buttons(choice,currentform);
                   3363:     return;
1.20      www      3364: }
1.32      matthew  3365: 
                   3366: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  3367:     var numauthchoices = currentform.login.length;
                   3368:     if (typeof numauthchoices  == "undefined") {
                   3369:         return;
                   3370:     } 
1.32      matthew  3371:     var i=0;
1.986     raeburn  3372:     while (i < numauthchoices) {
1.32      matthew  3373:         if (currentform.login[i].value == newvalue) { break; }
                   3374:         i++;
                   3375:     }
1.986     raeburn  3376:     if (i == numauthchoices) {
1.32      matthew  3377:         return;
                   3378:     }
                   3379:     current.radiovalue = newvalue;
                   3380:     currentform.login[i].checked = true;
                   3381:     return;
                   3382: }
                   3383: END
                   3384:     return $result;
                   3385: }
                   3386: 
1.1106    raeburn  3387: sub authform_authorwarning {
1.32      matthew  3388:     my $result='';
1.144     matthew  3389:     $result='<i>'.
                   3390:         &mt('As a general rule, only authors or co-authors should be '.
                   3391:             'filesystem authenticated '.
                   3392:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  3393:     return $result;
                   3394: }
                   3395: 
1.1106    raeburn  3396: sub authform_nochange {
1.32      matthew  3397:     my %in = (
                   3398:               formname => 'document.cu',
                   3399:               kerb_def_dom => 'MSU.EDU',
                   3400:               @_,
                   3401:           );
1.1106    raeburn  3402:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  3403:     my $result;
1.1104    raeburn  3404:     if (!$authnum) {
1.1105    raeburn  3405:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  3406:     } else {
                   3407:         $result = '<label>'.&mt('[_1] Do not change login data',
                   3408:                   '<input type="radio" name="login" value="nochange" '.
                   3409:                   'checked="checked" onclick="'.
1.281     albertel 3410:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   3411: 	    '</label>';
1.586     raeburn  3412:     }
1.32      matthew  3413:     return $result;
                   3414: }
                   3415: 
1.591     raeburn  3416: sub authform_kerberos {
1.32      matthew  3417:     my %in = (
                   3418:               formname => 'document.cu',
                   3419:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 3420:               kerb_def_auth => 'krb4',
1.32      matthew  3421:               @_,
                   3422:               );
1.586     raeburn  3423:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1259    raeburn  3424:         $autharg,$jscall,$disabled);
1.1106    raeburn  3425:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 3426:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   3427:        $check5 = ' checked="checked"';
1.80      albertel 3428:     } else {
1.772     bisitz   3429:        $check4 = ' checked="checked"';
1.80      albertel 3430:     }
1.1259    raeburn  3431:     if ($in{'readonly'}) {
                   3432:         $disabled = ' disabled="disabled"';
                   3433:     }
1.165     raeburn  3434:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  3435:     if (defined($in{'curr_authtype'})) {
                   3436:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   3437:             $krbcheck = ' checked="checked"';
1.623     raeburn  3438:             if (defined($in{'mode'})) {
                   3439:                 if ($in{'mode'} eq 'modifyuser') {
                   3440:                     $krbcheck = '';
                   3441:                 }
                   3442:             }
1.591     raeburn  3443:             if (defined($in{'curr_kerb_ver'})) {
                   3444:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   3445:                     $check5 = ' checked="checked"';
1.591     raeburn  3446:                     $check4 = '';
                   3447:                 } else {
1.772     bisitz   3448:                     $check4 = ' checked="checked"';
1.591     raeburn  3449:                     $check5 = '';
                   3450:                 }
1.586     raeburn  3451:             }
1.591     raeburn  3452:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  3453:                 $krbarg = $in{'curr_autharg'};
                   3454:             }
1.586     raeburn  3455:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  3456:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3457:                     $result = 
                   3458:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   3459:         $in{'curr_autharg'},$krbver);
                   3460:                 } else {
                   3461:                     $result =
                   3462:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   3463:                 }
                   3464:                 return $result; 
                   3465:             }
                   3466:         }
                   3467:     } else {
                   3468:         if ($authnum == 1) {
1.784     bisitz   3469:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  3470:         }
                   3471:     }
1.586     raeburn  3472:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   3473:         return;
1.587     raeburn  3474:     } elsif ($authtype eq '') {
1.591     raeburn  3475:         if (defined($in{'mode'})) {
1.587     raeburn  3476:             if ($in{'mode'} eq 'modifycourse') {
                   3477:                 if ($authnum == 1) {
1.1259    raeburn  3478:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  3479:                 }
                   3480:             }
                   3481:         }
1.586     raeburn  3482:     }
                   3483:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   3484:     if ($authtype eq '') {
                   3485:         $authtype = '<input type="radio" name="login" value="krb" '.
                   3486:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1259    raeburn  3487:                     $krbcheck.$disabled.' />';
1.586     raeburn  3488:     }
                   3489:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  3490:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  3491:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  3492:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  3493:          $in{'curr_authtype'} eq 'krb4')) {
                   3494:         $result .= &mt
1.144     matthew  3495:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 3496:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  3497:          '<label>'.$authtype,
1.281     albertel 3498:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  3499:              'value="'.$krbarg.'" '.
1.1259    raeburn  3500:              'onchange="'.$jscall.'"'.$disabled.' />',
                   3501:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   3502:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 3503: 	 '</label>');
1.586     raeburn  3504:     } elsif ($can_assign{'krb4'}) {
                   3505:         $result .= &mt
                   3506:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3507:          '[_3] Version 4 [_4]',
                   3508:          '<label>'.$authtype,
                   3509:          '</label><input type="text" size="10" name="krbarg" '.
                   3510:              'value="'.$krbarg.'" '.
1.1259    raeburn  3511:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3512:          '<label><input type="hidden" name="krbver" value="4" />',
                   3513:          '</label>');
                   3514:     } elsif ($can_assign{'krb5'}) {
                   3515:         $result .= &mt
                   3516:         ('[_1] Kerberos authenticated with domain [_2] '.
                   3517:          '[_3] Version 5 [_4]',
                   3518:          '<label>'.$authtype,
                   3519:          '</label><input type="text" size="10" name="krbarg" '.
                   3520:              'value="'.$krbarg.'" '.
1.1259    raeburn  3521:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  3522:          '<label><input type="hidden" name="krbver" value="5" />',
                   3523:          '</label>');
                   3524:     }
1.32      matthew  3525:     return $result;
                   3526: }
                   3527: 
1.1106    raeburn  3528: sub authform_internal {
1.586     raeburn  3529:     my %in = (
1.32      matthew  3530:                 formname => 'document.cu',
                   3531:                 kerb_def_dom => 'MSU.EDU',
                   3532:                 @_,
                   3533:                 );
1.1259    raeburn  3534:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3535:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3536:     if ($in{'readonly'}) {
                   3537:         $disabled = ' disabled="disabled"';
                   3538:     }
1.591     raeburn  3539:     if (defined($in{'curr_authtype'})) {
                   3540:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  3541:             if ($can_assign{'int'}) {
1.772     bisitz   3542:                 $intcheck = 'checked="checked" ';
1.623     raeburn  3543:                 if (defined($in{'mode'})) {
                   3544:                     if ($in{'mode'} eq 'modifyuser') {
                   3545:                         $intcheck = '';
                   3546:                     }
                   3547:                 }
1.591     raeburn  3548:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3549:                     $intarg = $in{'curr_autharg'};
                   3550:                 }
                   3551:             } else {
                   3552:                 $result = &mt('Currently internally authenticated.');
                   3553:                 return $result;
1.165     raeburn  3554:             }
                   3555:         }
1.586     raeburn  3556:     } else {
                   3557:         if ($authnum == 1) {
1.784     bisitz   3558:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  3559:         }
                   3560:     }
                   3561:     if (!$can_assign{'int'}) {
                   3562:         return;
1.587     raeburn  3563:     } elsif ($authtype eq '') {
1.591     raeburn  3564:         if (defined($in{'mode'})) {
1.587     raeburn  3565:             if ($in{'mode'} eq 'modifycourse') {
                   3566:                 if ($authnum == 1) {
1.1259    raeburn  3567:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  3568:                 }
                   3569:             }
                   3570:         }
1.165     raeburn  3571:     }
1.586     raeburn  3572:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3573:     if ($authtype eq '') {
                   3574:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1259    raeburn  3575:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3576:     }
1.605     bisitz   3577:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1259    raeburn  3578:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3579:     $result = &mt
1.144     matthew  3580:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3581:          '<label>'.$authtype,'</label>'.$autharg);
1.1259    raeburn  3582:     $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  3583:     return $result;
                   3584: }
                   3585: 
1.1104    raeburn  3586: sub authform_local {
1.32      matthew  3587:     my %in = (
                   3588:               formname => 'document.cu',
                   3589:               kerb_def_dom => 'MSU.EDU',
                   3590:               @_,
                   3591:               );
1.1259    raeburn  3592:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3593:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3594:     if ($in{'readonly'}) {
                   3595:         $disabled = ' disabled="disabled"';
                   3596:     } 
1.591     raeburn  3597:     if (defined($in{'curr_authtype'})) {
                   3598:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3599:             if ($can_assign{'loc'}) {
1.772     bisitz   3600:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3601:                 if (defined($in{'mode'})) {
                   3602:                     if ($in{'mode'} eq 'modifyuser') {
                   3603:                         $loccheck = '';
                   3604:                     }
                   3605:                 }
1.591     raeburn  3606:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3607:                     $locarg = $in{'curr_autharg'};
                   3608:                 }
                   3609:             } else {
                   3610:                 $result = &mt('Currently using local (institutional) authentication.');
                   3611:                 return $result;
1.165     raeburn  3612:             }
                   3613:         }
1.586     raeburn  3614:     } else {
                   3615:         if ($authnum == 1) {
1.784     bisitz   3616:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3617:         }
                   3618:     }
                   3619:     if (!$can_assign{'loc'}) {
                   3620:         return;
1.587     raeburn  3621:     } elsif ($authtype eq '') {
1.591     raeburn  3622:         if (defined($in{'mode'})) {
1.587     raeburn  3623:             if ($in{'mode'} eq 'modifycourse') {
                   3624:                 if ($authnum == 1) {
1.1259    raeburn  3625:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3626:                 }
                   3627:             }
                   3628:         }
1.165     raeburn  3629:     }
1.586     raeburn  3630:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3631:     if ($authtype eq '') {
                   3632:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3633:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3634:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3635:     }
                   3636:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1259    raeburn  3637:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3638:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3639:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3640:     return $result;
                   3641: }
                   3642: 
1.1106    raeburn  3643: sub authform_filesystem {
1.32      matthew  3644:     my %in = (
                   3645:               formname => 'document.cu',
                   3646:               kerb_def_dom => 'MSU.EDU',
                   3647:               @_,
                   3648:               );
1.1259    raeburn  3649:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1106    raeburn  3650:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1259    raeburn  3651:     if ($in{'readonly'}) {
                   3652:         $disabled = ' disabled="disabled"';
                   3653:     }
1.591     raeburn  3654:     if (defined($in{'curr_authtype'})) {
                   3655:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3656:             if ($can_assign{'fsys'}) {
1.772     bisitz   3657:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3658:                 if (defined($in{'mode'})) {
                   3659:                     if ($in{'mode'} eq 'modifyuser') {
                   3660:                         $fsyscheck = '';
                   3661:                     }
                   3662:                 }
1.586     raeburn  3663:             } else {
                   3664:                 $result = &mt('Currently Filesystem Authenticated.');
                   3665:                 return $result;
1.1259    raeburn  3666:             }
1.586     raeburn  3667:         }
                   3668:     } else {
                   3669:         if ($authnum == 1) {
1.784     bisitz   3670:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3671:         }
                   3672:     }
                   3673:     if (!$can_assign{'fsys'}) {
                   3674:         return;
1.587     raeburn  3675:     } elsif ($authtype eq '') {
1.591     raeburn  3676:         if (defined($in{'mode'})) {
1.587     raeburn  3677:             if ($in{'mode'} eq 'modifycourse') {
                   3678:                 if ($authnum == 1) {
1.1259    raeburn  3679:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3680:                 }
                   3681:             }
                   3682:         }
1.586     raeburn  3683:     }
                   3684:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3685:     if ($authtype eq '') {
                   3686:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3687:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1259    raeburn  3688:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3689:     }
1.1310    raeburn  3690:     $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
1.1259    raeburn  3691:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3692:     $result = &mt
1.144     matthew  3693:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.1310    raeburn  3694:          '<label>'.$authtype,'</label>'.$autharg);
                   3695:     return $result;
                   3696: }
                   3697: 
                   3698: sub authform_lti {
                   3699:     my %in = (
                   3700:               formname => 'document.cu',
                   3701:               kerb_def_dom => 'MSU.EDU',
                   3702:               @_,
                   3703:               );
                   3704:     my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
                   3705:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
                   3706:     if ($in{'readonly'}) {
                   3707:         $disabled = ' disabled="disabled"';
                   3708:     }
                   3709:     if (defined($in{'curr_authtype'})) {
                   3710:         if ($in{'curr_authtype'} eq 'lti') {
                   3711:             if ($can_assign{'lti'}) {
                   3712:                 $lticheck = 'checked="checked" ';
                   3713:                 if (defined($in{'mode'})) {
                   3714:                     if ($in{'mode'} eq 'modifyuser') {
                   3715:                         $lticheck = '';
                   3716:                     }
                   3717:                 }
                   3718:             } else {
                   3719:                 $result = &mt('Currently LTI Authenticated.');
                   3720:                 return $result;
                   3721:             }
                   3722:         }
                   3723:     } else {
                   3724:         if ($authnum == 1) {
                   3725:             $authtype = '<input type="hidden" name="login" value="lti" />';
                   3726:         }
                   3727:     }
                   3728:     if (!$can_assign{'lti'}) {
                   3729:         return;
                   3730:     } elsif ($authtype eq '') {
                   3731:         if (defined($in{'mode'})) {
                   3732:             if ($in{'mode'} eq 'modifycourse') {
                   3733:                 if ($authnum == 1) {
                   3734:                     $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
                   3735:                 }
                   3736:             }
                   3737:         }
                   3738:     }
                   3739:     $jscall = "javascript:changed_radio('lti',$in{'formname'});";
                   3740:     if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
                   3741:         $authtype = '<input type="radio" name="login" value="lti" '.
                   3742:                     $lticheck.' onchange="'.$jscall.'" onclick="'.
                   3743:                     $jscall.'"'.$disabled.' />';
                   3744:     }
                   3745:     $autharg = '<input type="hidden" name="ltiarg" value="" />';
                   3746:     if ($authtype) {
                   3747:         $result = &mt('[_1] LTI Authenticated',
                   3748:                       '<label>'.$authtype.'</label>'.$autharg);
                   3749:     } else {
                   3750:         $result = '<b>'.&mt('LTI Authenticated').'</b>'.
                   3751:                   $autharg;
                   3752:     }
1.32      matthew  3753:     return $result;
                   3754: }
                   3755: 
1.586     raeburn  3756: sub get_assignable_auth {
                   3757:     my ($dom) = @_;
                   3758:     if ($dom eq '') {
                   3759:         $dom = $env{'request.role.domain'};
                   3760:     }
                   3761:     my %can_assign = (
                   3762:                           krb4 => 1,
                   3763:                           krb5 => 1,
                   3764:                           int  => 1,
                   3765:                           loc  => 1,
1.1310    raeburn  3766:                           lti  => 1,
1.586     raeburn  3767:                      );
                   3768:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3769:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3770:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3771:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3772:             my $context;
                   3773:             if ($env{'request.role'} =~ /^au/) {
                   3774:                 $context = 'author';
1.1259    raeburn  3775:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3776:                 $context = 'domain';
                   3777:             } elsif ($env{'request.course.id'}) {
                   3778:                 $context = 'course';
                   3779:             }
                   3780:             if ($context) {
                   3781:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3782:                    %can_assign = %{$authhash->{$context}}; 
                   3783:                 }
                   3784:             }
                   3785:         }
                   3786:     }
                   3787:     my $authnum = 0;
                   3788:     foreach my $key (keys(%can_assign)) {
                   3789:         if ($can_assign{$key}) {
                   3790:             $authnum ++;
                   3791:         }
                   3792:     }
                   3793:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3794:         $authnum --;
                   3795:     }
                   3796:     return ($authnum,%can_assign);
                   3797: }
                   3798: 
1.1331    raeburn  3799: sub check_passwd_rules {
                   3800:     my ($domain,$plainpass) = @_;
                   3801:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3802:     my ($min,$max,@chars,@brokerule,$warning);
1.1333    raeburn  3803:     $min = $Apache::lonnet::passwdmin;
1.1331    raeburn  3804:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3805:         if ($passwdconf{'min'} =~ /^\d+$/) {
1.1333    raeburn  3806:             if ($passwdconf{'min'} > $min) {
                   3807:                 $min = $passwdconf{'min'};
                   3808:             }
1.1331    raeburn  3809:         }
                   3810:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3811:             $max = $passwdconf{'max'};
                   3812:         }
                   3813:         @chars = @{$passwdconf{'chars'}};
                   3814:     }
                   3815:     if (($min) && (length($plainpass) < $min)) {
                   3816:         push(@brokerule,'min');
                   3817:     }
                   3818:     if (($max) && (length($plainpass) > $max)) {
                   3819:         push(@brokerule,'max');
                   3820:     }
                   3821:     if (@chars) {
                   3822:         my %rules;
                   3823:         map { $rules{$_} = 1; } @chars;
                   3824:         if ($rules{'uc'}) {
                   3825:             unless ($plainpass =~ /[A-Z]/) {
                   3826:                 push(@brokerule,'uc');
                   3827:             }
                   3828:         }
                   3829:         if ($rules{'lc'}) {
1.1332    raeburn  3830:             unless ($plainpass =~ /[a-z]/) {
1.1331    raeburn  3831:                 push(@brokerule,'lc');
                   3832:             }
                   3833:         }
                   3834:         if ($rules{'num'}) {
                   3835:             unless ($plainpass =~ /\d/) {
                   3836:                 push(@brokerule,'num');
                   3837:             }
                   3838:         }
                   3839:         if ($rules{'spec'}) {
                   3840:             unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
                   3841:                 push(@brokerule,'spec');
                   3842:             }
                   3843:         }
                   3844:     }
                   3845:     if (@brokerule) {
                   3846:         my %rulenames = &Apache::lonlocal::texthash(
                   3847:             uc   => 'At least one upper case letter',
                   3848:             lc   => 'At least one lower case letter',
                   3849:             num  => 'At least one number',
                   3850:             spec => 'At least one non-alphanumeric',
                   3851:         );
                   3852:         $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                   3853:         $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
                   3854:         $rulenames{'num'} .= ': 0123456789';
                   3855:         $rulenames{'spec'} .= ': !&quot;\#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\]^_\`{|}~';
                   3856:         $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
                   3857:         $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
                   3858:         $warning = &mt('Password did not satisfy the following:').'<ul>';
1.1336    raeburn  3859:         foreach my $rule ('min','max','uc','lc','num','spec') {
1.1331    raeburn  3860:             if (grep(/^$rule$/,@brokerule)) {
                   3861:                 $warning .= '<li>'.$rulenames{$rule}.'</li>';
                   3862:             }
                   3863:         }
                   3864:         $warning .= '</ul>';
                   3865:     }
1.1332    raeburn  3866:     if (wantarray) {
                   3867:         return @brokerule;
                   3868:     }
1.1331    raeburn  3869:     return $warning;
                   3870: }
                   3871: 
1.1376    raeburn  3872: sub passwd_validation_js {
1.1377    raeburn  3873:     my ($currpasswdval,$domain,$context,$id) = @_;
                   3874:     my (%passwdconf,$alertmsg);
                   3875:     if ($context eq 'linkprot') {
                   3876:         my %domconfig = &Apache::lonnet::get_dom('configuration',['ltisec'],$domain);
                   3877:         if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   3878:             if (ref($domconfig{'ltisec'}{'rules'}) eq 'HASH') {
                   3879:                 %passwdconf = %{$domconfig{'ltisec'}{'rules'}};
                   3880:             }
                   3881:         }
                   3882:         if ($id eq 'add') {
                   3883:             $alertmsg = &mt('Secret for added launcher did not satisfy requirement(s):').'\n\n';
                   3884:         } elsif ($id =~ /^\d+$/) {
                   3885:             my $pos = $id+1;
                   3886:             $alertmsg = &mt('Secret for launcher [_1] did not satisfy requirement(s):','#'.$pos).'\n\n';
                   3887:         } else {
                   3888:             $alertmsg = &mt('A secret did not satisfy requirement(s):').'\n\n';
                   3889:         }
                   3890:     } else {
                   3891:         %passwdconf = &Apache::lonnet::get_passwdconf($domain);
                   3892:         $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
                   3893:     }
1.1376    raeburn  3894:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
                   3895:     $numrules = 0;
                   3896:     $min = $Apache::lonnet::passwdmin;
                   3897:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
                   3898:         if ($passwdconf{'min'} =~ /^\d+$/) {
                   3899:             if ($passwdconf{'min'} > $min) {
                   3900:                 $min = $passwdconf{'min'};
                   3901:             }
                   3902:         }
                   3903:         if ($passwdconf{'max'} =~ /^\d+$/) {
                   3904:             $max = $passwdconf{'max'};
                   3905:             $numrules ++;
                   3906:         }
                   3907:         @chars = @{$passwdconf{'chars'}};
                   3908:         if (@chars) {
                   3909:             $numrules ++;
                   3910:         }
                   3911:     }
                   3912:     if ($min > 0) {
                   3913:         $numrules ++;
                   3914:     }
                   3915:     if (($min > 0) || ($max ne '') || (@chars > 0)) {
                   3916:         if ($min) {
                   3917:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
                   3918:         }
                   3919:         if ($max) {
                   3920:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
                   3921:         }
                   3922:         my (@charalerts,@charrules);
                   3923:         if (@chars) {
                   3924:             if (grep(/^uc$/,@chars)) {
                   3925:                 push(@charalerts,&mt('contain at least one upper case letter'));
                   3926:                 push(@charrules,'uc');
                   3927:             }
                   3928:             if (grep(/^lc$/,@chars)) {
                   3929:                 push(@charalerts,&mt('contain at least one lower case letter'));
                   3930:                 push(@charrules,'lc');
                   3931:             }
                   3932:             if (grep(/^num$/,@chars)) {
                   3933:                 push(@charalerts,&mt('contain at least one number'));
                   3934:                 push(@charrules,'num');
                   3935:             }
                   3936:             if (grep(/^spec$/,@chars)) {
                   3937:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
                   3938:                 push(@charrules,'spec');
                   3939:             }
                   3940:         }
                   3941:         $intargjs = qq|            var rulesmsg = '';\n|.
                   3942:                     qq|            var currpwval = $currpasswdval;\n|;
                   3943:             if ($min) {
                   3944:                 $intargjs .= qq|
                   3945:             if (currpwval.length < $min) {
                   3946:                 rulesmsg += ' - $alert{min}';
                   3947:             }
                   3948: |;
                   3949:             }
                   3950:             if ($max) {
                   3951:                 $intargjs .= qq|
                   3952:             if (currpwval.length > $max) {
                   3953:                 rulesmsg += ' - $alert{max}';
                   3954:             }
                   3955: |;
                   3956:             }
                   3957:             if (@chars > 0) {
                   3958:                 my $charrulestr = '"'.join('","',@charrules).'"';
                   3959:                 my $charalertstr = '"'.join('","',@charalerts).'"';
                   3960:                 $intargjs .= qq|            var brokerules = new Array();\n|.
                   3961:                              qq|            var charrules = new Array($charrulestr);\n|.
                   3962:                              qq|            var charalerts = new Array($charalertstr);\n|;
                   3963:                 my %rules;
                   3964:                 map { $rules{$_} = 1; } @chars;
                   3965:                 if ($rules{'uc'}) {
                   3966:                     $intargjs .= qq|
                   3967:             var ucRegExp = /[A-Z]/;
                   3968:             if (!ucRegExp.test(currpwval)) {
                   3969:                 brokerules.push('uc');
                   3970:             }
                   3971: |;
                   3972:                 }
                   3973:                 if ($rules{'lc'}) {
                   3974:                     $intargjs .= qq|
                   3975:             var lcRegExp = /[a-z]/;
                   3976:             if (!lcRegExp.test(currpwval)) {
                   3977:                 brokerules.push('lc');
                   3978:             }
                   3979: |;
                   3980:                 }
                   3981:                 if ($rules{'num'}) {
                   3982:                      $intargjs .= qq|
                   3983:             var numRegExp = /[0-9]/;
                   3984:             if (!numRegExp.test(currpwval)) {
                   3985:                 brokerules.push('num');
                   3986:             }
                   3987: |;
                   3988:                 }
                   3989:                 if ($rules{'spec'}) {
                   3990:                      $intargjs .= q|
                   3991:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
                   3992:             if (!specRegExp.test(currpwval)) {
                   3993:                 brokerules.push('spec');
                   3994:             }
                   3995: |;
                   3996:                 }
                   3997:                 $intargjs .= qq|
                   3998:             if (brokerules.length > 0) {
                   3999:                 for (var i=0; i<brokerules.length; i++) {
                   4000:                     for (var j=0; j<charrules.length; j++) {
                   4001:                         if (brokerules[i] == charrules[j]) {
                   4002:                             rulesmsg += ' - '+charalerts[j]+'\\n';
                   4003:                             break;
                   4004:                         }
                   4005:                     }
                   4006:                 }
                   4007:             }
                   4008: |;
                   4009:             }
                   4010:             $intargjs .= qq|
                   4011:             if (rulesmsg != '') {
                   4012:                 rulesmsg = '$alertmsg'+rulesmsg;
                   4013:                 alert(rulesmsg);
                   4014:                 return false;
                   4015:             }
                   4016: |;
                   4017:     }
                   4018:     return ($numrules,$intargjs);
                   4019: }
                   4020: 
1.80      albertel 4021: ###############################################################
                   4022: ##    Get Kerberos Defaults for Domain                 ##
                   4023: ###############################################################
                   4024: ##
                   4025: ## Returns default kerberos version and an associated argument
                   4026: ## as listed in file domain.tab. If not listed, provides
                   4027: ## appropriate default domain and kerberos version.
                   4028: ##
                   4029: #-------------------------------------------
                   4030: 
                   4031: =pod
                   4032: 
1.648     raeburn  4033: =item * &get_kerberos_defaults()
1.80      albertel 4034: 
                   4035: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  4036: version and domain. If not found, it defaults to version 4 and the 
                   4037: domain of the server.
1.80      albertel 4038: 
1.648     raeburn  4039: =over 4
                   4040: 
1.80      albertel 4041: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   4042: 
1.648     raeburn  4043: =back
                   4044: 
                   4045: =back
                   4046: 
1.80      albertel 4047: =cut
                   4048: 
                   4049: #-------------------------------------------
                   4050: sub get_kerberos_defaults {
                   4051:     my $domain=shift;
1.641     raeburn  4052:     my ($krbdef,$krbdefdom);
                   4053:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   4054:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   4055:         $krbdef = $domdefaults{'auth_def'};
                   4056:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   4057:     } else {
1.80      albertel 4058:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   4059:         my $krbdefdom=$1;
                   4060:         $krbdefdom=~tr/a-z/A-Z/;
                   4061:         $krbdef = "krb4";
                   4062:     }
                   4063:     return ($krbdef,$krbdefdom);
                   4064: }
1.112     bowersj2 4065: 
1.32      matthew  4066: 
1.46      matthew  4067: ###############################################################
                   4068: ##                Thesaurus Functions                        ##
                   4069: ###############################################################
1.20      www      4070: 
1.46      matthew  4071: =pod
1.20      www      4072: 
1.112     bowersj2 4073: =head1 Thesaurus Functions
                   4074: 
                   4075: =over 4
                   4076: 
1.648     raeburn  4077: =item * &initialize_keywords()
1.46      matthew  4078: 
                   4079: Initializes the package variable %Keywords if it is empty.  Uses the
                   4080: package variable $thesaurus_db_file.
                   4081: 
                   4082: =cut
                   4083: 
                   4084: ###################################################
                   4085: 
                   4086: sub initialize_keywords {
                   4087:     return 1 if (scalar keys(%Keywords));
                   4088:     # If we are here, %Keywords is empty, so fill it up
                   4089:     #   Make sure the file we need exists...
                   4090:     if (! -e $thesaurus_db_file) {
                   4091:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   4092:                                  " failed because it does not exist");
                   4093:         return 0;
                   4094:     }
                   4095:     #   Set up the hash as a database
                   4096:     my %thesaurus_db;
                   4097:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4098:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4099:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   4100:                                  $thesaurus_db_file);
                   4101:         return 0;
                   4102:     } 
                   4103:     #  Get the average number of appearances of a word.
                   4104:     my $avecount = $thesaurus_db{'average.count'};
                   4105:     #  Put keywords (those that appear > average) into %Keywords
                   4106:     while (my ($word,$data)=each (%thesaurus_db)) {
                   4107:         my ($count,undef) = split /:/,$data;
                   4108:         $Keywords{$word}++ if ($count > $avecount);
                   4109:     }
                   4110:     untie %thesaurus_db;
                   4111:     # Remove special values from %Keywords.
1.356     albertel 4112:     foreach my $value ('total.count','average.count') {
                   4113:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  4114:   }
1.46      matthew  4115:     return 1;
                   4116: }
                   4117: 
                   4118: ###################################################
                   4119: 
                   4120: =pod
                   4121: 
1.648     raeburn  4122: =item * &keyword($word)
1.46      matthew  4123: 
                   4124: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   4125: than the average number of times in the thesaurus database.  Calls 
                   4126: &initialize_keywords
                   4127: 
                   4128: =cut
                   4129: 
                   4130: ###################################################
1.20      www      4131: 
                   4132: sub keyword {
1.46      matthew  4133:     return if (!&initialize_keywords());
                   4134:     my $word=lc(shift());
                   4135:     $word=~s/\W//g;
                   4136:     return exists($Keywords{$word});
1.20      www      4137: }
1.46      matthew  4138: 
                   4139: ###############################################################
                   4140: 
                   4141: =pod 
1.20      www      4142: 
1.648     raeburn  4143: =item * &get_related_words()
1.46      matthew  4144: 
1.160     matthew  4145: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  4146: an array of words.  If the keyword is not in the thesaurus, an empty array
                   4147: will be returned.  The order of the words returned is determined by the
                   4148: database which holds them.
                   4149: 
                   4150: Uses global $thesaurus_db_file.
                   4151: 
1.1057    foxr     4152: 
1.46      matthew  4153: =cut
                   4154: 
                   4155: ###############################################################
                   4156: sub get_related_words {
                   4157:     my $keyword = shift;
                   4158:     my %thesaurus_db;
                   4159:     if (! -e $thesaurus_db_file) {
                   4160:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   4161:                                  "failed because the file does not exist");
                   4162:         return ();
                   4163:     }
                   4164:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 4165:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  4166:         return ();
                   4167:     } 
                   4168:     my @Words=();
1.429     www      4169:     my $count=0;
1.46      matthew  4170:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 4171: 	# The first element is the number of times
                   4172: 	# the word appears.  We do not need it now.
1.429     www      4173: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   4174: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   4175: 	my $threshold=$mostfrequentcount/10;
                   4176:         foreach my $possibleword (@RelatedWords) {
                   4177:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   4178:             if ($wordcount>$threshold) {
                   4179: 		push(@Words,$word);
                   4180:                 $count++;
                   4181:                 if ($count>10) { last; }
                   4182: 	    }
1.20      www      4183:         }
                   4184:     }
1.46      matthew  4185:     untie %thesaurus_db;
                   4186:     return @Words;
1.14      harris41 4187: }
1.1090    foxr     4188: ###############################################################
                   4189: #
                   4190: #  Spell checking
                   4191: #
                   4192: 
                   4193: =pod
                   4194: 
1.1142    raeburn  4195: =back
                   4196: 
1.1090    foxr     4197: =head1 Spell checking
                   4198: 
                   4199: =over 4
                   4200: 
                   4201: =item * &check_spelling($wordlist $language)
                   4202: 
                   4203: Takes a string containing words and feeds it to an external
                   4204: spellcheck program via a pipeline. Returns a string containing
                   4205: them mis-spelled words.
                   4206: 
                   4207: Parameters:
                   4208: 
                   4209: =over 4
                   4210: 
                   4211: =item - $wordlist
                   4212: 
                   4213: String that will be fed into the spellcheck program.
                   4214: 
                   4215: =item - $language
                   4216: 
                   4217: Language string that specifies the language for which the spell
                   4218: check will be performed.
                   4219: 
                   4220: =back
                   4221: 
                   4222: =back
                   4223: 
                   4224: Note: This sub assumes that aspell is installed.
                   4225: 
                   4226: 
                   4227: =cut
                   4228: 
1.46      matthew  4229: 
1.1090    foxr     4230: sub check_spelling {
                   4231:     my ($wordlist, $language) = @_;
1.1091    foxr     4232:     my @misspellings;
                   4233:     
                   4234:     # Generate the speller and set the langauge.
                   4235:     # if explicitly selected:
1.1090    foxr     4236: 
1.1091    foxr     4237:     my $speller = Text::Aspell->new;
1.1090    foxr     4238:     if ($language) {
1.1091    foxr     4239: 	$speller->set_option('lang', $language);
1.1090    foxr     4240:     }
                   4241: 
1.1091    foxr     4242:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     4243: 
1.1091    foxr     4244:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     4245: 
1.1091    foxr     4246:     foreach my $word (@words) {
                   4247: 	if(! $speller->check($word)) {
                   4248: 	    push(@misspellings, $word);
1.1090    foxr     4249: 	}
                   4250:     }
1.1091    foxr     4251:     return join(' ', @misspellings);
                   4252:     
1.1090    foxr     4253: }
                   4254: 
1.61      www      4255: # -------------------------------------------------------------- Plaintext name
1.81      albertel 4256: =pod
                   4257: 
1.112     bowersj2 4258: =head1 User Name Functions
                   4259: 
                   4260: =over 4
                   4261: 
1.648     raeburn  4262: =item * &plainname($uname,$udom,$first)
1.81      albertel 4263: 
1.112     bowersj2 4264: Takes a users logon name and returns it as a string in
1.226     albertel 4265: "first middle last generation" form 
                   4266: if $first is set to 'lastname' then it returns it as
                   4267: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 4268: 
                   4269: =cut
1.61      www      4270: 
1.295     www      4271: 
1.81      albertel 4272: ###############################################################
1.61      www      4273: sub plainname {
1.226     albertel 4274:     my ($uname,$udom,$first)=@_;
1.537     albertel 4275:     return if (!defined($uname) || !defined($udom));
1.295     www      4276:     my %names=&getnames($uname,$udom);
1.226     albertel 4277:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   4278: 					  $names{'middlename'},
                   4279: 					  $names{'lastname'},
                   4280: 					  $names{'generation'},$first);
                   4281:     $name=~s/^\s+//;
1.62      www      4282:     $name=~s/\s+$//;
                   4283:     $name=~s/\s+/ /g;
1.353     albertel 4284:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      4285:     return $name;
1.61      www      4286: }
1.66      www      4287: 
                   4288: # -------------------------------------------------------------------- Nickname
1.81      albertel 4289: =pod
                   4290: 
1.648     raeburn  4291: =item * &nickname($uname,$udom)
1.81      albertel 4292: 
                   4293: Gets a users name and returns it as a string as
                   4294: 
                   4295: "&quot;nickname&quot;"
1.66      www      4296: 
1.81      albertel 4297: if the user has a nickname or
                   4298: 
                   4299: "first middle last generation"
                   4300: 
                   4301: if the user does not
                   4302: 
                   4303: =cut
1.66      www      4304: 
                   4305: sub nickname {
                   4306:     my ($uname,$udom)=@_;
1.537     albertel 4307:     return if (!defined($uname) || !defined($udom));
1.295     www      4308:     my %names=&getnames($uname,$udom);
1.68      albertel 4309:     my $name=$names{'nickname'};
1.66      www      4310:     if ($name) {
                   4311:        $name='&quot;'.$name.'&quot;'; 
                   4312:     } else {
                   4313:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   4314: 	     $names{'lastname'}.' '.$names{'generation'};
                   4315:        $name=~s/\s+$//;
                   4316:        $name=~s/\s+/ /g;
                   4317:     }
                   4318:     return $name;
                   4319: }
                   4320: 
1.295     www      4321: sub getnames {
                   4322:     my ($uname,$udom)=@_;
1.537     albertel 4323:     return if (!defined($uname) || !defined($udom));
1.433     albertel 4324:     if ($udom eq 'public' && $uname eq 'public') {
                   4325: 	return ('lastname' => &mt('Public'));
                   4326:     }
1.295     www      4327:     my $id=$uname.':'.$udom;
                   4328:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   4329:     if ($cached) {
                   4330: 	return %{$names};
                   4331:     } else {
                   4332: 	my %loadnames=&Apache::lonnet::get('environment',
                   4333:                     ['firstname','middlename','lastname','generation','nickname'],
                   4334: 					 $udom,$uname);
                   4335: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   4336: 	return %loadnames;
                   4337:     }
                   4338: }
1.61      www      4339: 
1.542     raeburn  4340: # -------------------------------------------------------------------- getemails
1.648     raeburn  4341: 
1.542     raeburn  4342: =pod
                   4343: 
1.648     raeburn  4344: =item * &getemails($uname,$udom)
1.542     raeburn  4345: 
                   4346: Gets a user's email information and returns it as a hash with keys:
                   4347: notification, critnotification, permanentemail
                   4348: 
                   4349: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  4350: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  4351:  
1.648     raeburn  4352: 
1.542     raeburn  4353: =cut
                   4354: 
1.648     raeburn  4355: 
1.466     albertel 4356: sub getemails {
                   4357:     my ($uname,$udom)=@_;
                   4358:     if ($udom eq 'public' && $uname eq 'public') {
                   4359: 	return;
                   4360:     }
1.467     www      4361:     if (!$udom) { $udom=$env{'user.domain'}; }
                   4362:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 4363:     my $id=$uname.':'.$udom;
                   4364:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   4365:     if ($cached) {
                   4366: 	return %{$names};
                   4367:     } else {
                   4368: 	my %loadnames=&Apache::lonnet::get('environment',
                   4369:                     			   ['notification','critnotification',
                   4370: 					    'permanentemail'],
                   4371: 					   $udom,$uname);
                   4372: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   4373: 	return %loadnames;
                   4374:     }
                   4375: }
                   4376: 
1.551     albertel 4377: sub flush_email_cache {
                   4378:     my ($uname,$udom)=@_;
                   4379:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4380:     if (!$uname) { $uname=$env{'user.name'};   }
                   4381:     return if ($udom eq 'public' && $uname eq 'public');
                   4382:     my $id=$uname.':'.$udom;
                   4383:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   4384: }
                   4385: 
1.728     raeburn  4386: # -------------------------------------------------------------------- getlangs
                   4387: 
                   4388: =pod
                   4389: 
                   4390: =item * &getlangs($uname,$udom)
                   4391: 
                   4392: Gets a user's language preference and returns it as a hash with key:
                   4393: language.
                   4394: 
                   4395: =cut
                   4396: 
                   4397: 
                   4398: sub getlangs {
                   4399:     my ($uname,$udom) = @_;
                   4400:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4401:     if (!$uname) { $uname=$env{'user.name'};   }
                   4402:     my $id=$uname.':'.$udom;
                   4403:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   4404:     if ($cached) {
                   4405:         return %{$langs};
                   4406:     } else {
                   4407:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   4408:                                            $udom,$uname);
                   4409:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   4410:         return %loadlangs;
                   4411:     }
                   4412: }
                   4413: 
                   4414: sub flush_langs_cache {
                   4415:     my ($uname,$udom)=@_;
                   4416:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4417:     if (!$uname) { $uname=$env{'user.name'};   }
                   4418:     return if ($udom eq 'public' && $uname eq 'public');
                   4419:     my $id=$uname.':'.$udom;
                   4420:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   4421: }
                   4422: 
1.61      www      4423: # ------------------------------------------------------------------ Screenname
1.81      albertel 4424: 
                   4425: =pod
                   4426: 
1.648     raeburn  4427: =item * &screenname($uname,$udom)
1.81      albertel 4428: 
                   4429: Gets a users screenname and returns it as a string
                   4430: 
                   4431: =cut
1.61      www      4432: 
                   4433: sub screenname {
                   4434:     my ($uname,$udom)=@_;
1.258     albertel 4435:     if ($uname eq $env{'user.name'} &&
                   4436: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 4437:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 4438:     return $names{'screenname'};
1.62      www      4439: }
                   4440: 
1.212     albertel 4441: 
1.802     bisitz   4442: # ------------------------------------------------------------- Confirm Wrapper
                   4443: =pod
                   4444: 
1.1142    raeburn  4445: =item * &confirmwrapper($message)
1.802     bisitz   4446: 
                   4447: Wrap messages about completion of operation in box
                   4448: 
                   4449: =cut
                   4450: 
                   4451: sub confirmwrapper {
                   4452:     my ($message)=@_;
                   4453:     if ($message) {
                   4454:         return "\n".'<div class="LC_confirm_box">'."\n"
                   4455:                .$message."\n"
                   4456:                .'</div>'."\n";
                   4457:     } else {
                   4458:         return $message;
                   4459:     }
                   4460: }
                   4461: 
1.62      www      4462: # ------------------------------------------------------------- Message Wrapper
                   4463: 
                   4464: sub messagewrapper {
1.369     www      4465:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      4466:     return 
1.441     albertel 4467:         '<a href="/adm/email?compose=individual&amp;'.
                   4468:         'recname='.$username.'&amp;recdom='.$domain.
                   4469: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  4470:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      4471: }
1.802     bisitz   4472: 
1.74      www      4473: # --------------------------------------------------------------- Notes Wrapper
                   4474: 
                   4475: sub noteswrapper {
                   4476:     my ($link,$un,$do)=@_;
                   4477:     return 
1.896     amueller 4478: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      4479: }
1.802     bisitz   4480: 
1.62      www      4481: # ------------------------------------------------------------- Aboutme Wrapper
                   4482: 
                   4483: sub aboutmewrapper {
1.1070    raeburn  4484:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  4485:     if (!defined($username)  && !defined($domain)) {
                   4486:         return;
                   4487:     }
1.1096    raeburn  4488:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  4489: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      4490: }
                   4491: 
                   4492: # ------------------------------------------------------------ Syllabus Wrapper
                   4493: 
                   4494: sub syllabuswrapper {
1.707     bisitz   4495:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  4496:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      4497: }
1.14      harris41 4498: 
1.1397    raeburn  4499: # -----------------------------------------------------------------------------
                   4500: 
1.1396    raeburn  4501: sub aboutme_on {
                   4502:     my ($uname,$udom)=@_;
                   4503:     unless ($uname) { $uname=$env{'user.name'}; }
                   4504:     unless ($udom)  { $udom=$env{'user.domain'}; }
                   4505:     return if ($udom eq 'public' && $uname eq 'public');
                   4506:     my $hashkey=$uname.':'.$udom;
                   4507:     my ($aboutme,$cached)=&Apache::lonnet::is_cached_new('aboutme',$hashkey);
                   4508:     if ($cached) {
                   4509:         return $aboutme;
                   4510:     }
                   4511:     $aboutme = &Apache::lonnet::usertools_access($uname,$udom,'aboutme');
                   4512:     &Apache::lonnet::do_cache_new('aboutme',$hashkey,$aboutme,3600);
                   4513:     return $aboutme;
                   4514: }
                   4515: 
                   4516: sub devalidate_aboutme_cache {
                   4517:     my ($uname,$udom)=@_;
                   4518:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   4519:     if (!$uname) { $uname=$env{'user.name'};   }
                   4520:     return if ($udom eq 'public' && $uname eq 'public');
                   4521:     my $id=$uname.':'.$udom;
                   4522:     &Apache::lonnet::devalidate_cache_new('aboutme',$id);
                   4523: }
                   4524: 
1.208     matthew  4525: sub track_student_link {
1.887     raeburn  4526:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 4527:     my $link ="/adm/trackstudent?";
1.208     matthew  4528:     my $title = 'View recent activity';
                   4529:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4530:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 4531:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  4532:         $title .= ' of this student';
1.268     albertel 4533:     } 
1.208     matthew  4534:     if (defined($target) && $target !~ /^\s*$/) {
                   4535:         $target = qq{target="$target"};
                   4536:     } else {
                   4537:         $target = '';
                   4538:     }
1.268     albertel 4539:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  4540:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 4541:     $title = &mt($title);
                   4542:     $linktext = &mt($linktext);
1.448     albertel 4543:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   4544: 	&help_open_topic('View_recent_activity');
1.208     matthew  4545: }
                   4546: 
1.781     raeburn  4547: sub slot_reservations_link {
                   4548:     my ($linktext,$sname,$sdom,$target) = @_;
                   4549:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   4550:     my $title = 'View slot reservation history';
                   4551:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   4552:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   4553:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   4554:         $title .= ' of this student';
                   4555:     }
                   4556:     if (defined($target) && $target !~ /^\s*$/) {
                   4557:         $target = qq{target="$target"};
                   4558:     } else {
                   4559:         $target = '';
                   4560:     }
                   4561:     $title = &mt($title);
                   4562:     $linktext = &mt($linktext);
                   4563:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   4564: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   4565: 
                   4566: }
                   4567: 
1.508     www      4568: # ===================================================== Display a student photo
                   4569: 
                   4570: 
1.509     albertel 4571: sub student_image_tag {
1.508     www      4572:     my ($domain,$user)=@_;
                   4573:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   4574:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   4575: 	return '<img src="'.$imgsrc.'" align="right" />';
                   4576:     } else {
                   4577: 	return '';
                   4578:     }
                   4579: }
                   4580: 
1.112     bowersj2 4581: =pod
                   4582: 
                   4583: =back
                   4584: 
                   4585: =head1 Access .tab File Data
                   4586: 
                   4587: =over 4
                   4588: 
1.648     raeburn  4589: =item * &languageids() 
1.112     bowersj2 4590: 
                   4591: returns list of all language ids
                   4592: 
                   4593: =cut
                   4594: 
1.14      harris41 4595: sub languageids {
1.16      harris41 4596:     return sort(keys(%language));
1.14      harris41 4597: }
                   4598: 
1.112     bowersj2 4599: =pod
                   4600: 
1.648     raeburn  4601: =item * &languagedescription() 
1.112     bowersj2 4602: 
                   4603: returns description of a specified language id
                   4604: 
                   4605: =cut
                   4606: 
1.14      harris41 4607: sub languagedescription {
1.125     www      4608:     my $code=shift;
                   4609:     return  ($supported_language{$code}?'* ':'').
                   4610:             $language{$code}.
1.126     www      4611: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      4612: }
                   4613: 
1.1048    foxr     4614: =pod
                   4615: 
                   4616: =item * &plainlanguagedescription
                   4617: 
                   4618: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   4619: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   4620: 
                   4621: =cut
                   4622: 
1.145     www      4623: sub plainlanguagedescription {
                   4624:     my $code=shift;
                   4625:     return $language{$code};
                   4626: }
                   4627: 
1.1048    foxr     4628: =pod
                   4629: 
                   4630: =item * &supportedlanguagecode
                   4631: 
                   4632: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   4633: code.
                   4634: 
                   4635: =cut
                   4636: 
1.145     www      4637: sub supportedlanguagecode {
                   4638:     my $code=shift;
                   4639:     return $supported_language{$code};
1.97      www      4640: }
                   4641: 
1.112     bowersj2 4642: =pod
                   4643: 
1.1048    foxr     4644: =item * &latexlanguage()
                   4645: 
                   4646: Given a language key code returns the correspondnig language to use
                   4647: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   4648: is no supported hyphenation for the language code.
                   4649: 
                   4650: =cut
                   4651: 
                   4652: sub latexlanguage {
                   4653:     my $code = shift;
                   4654:     return $latex_language{$code};
                   4655: }
                   4656: 
                   4657: =pod
                   4658: 
                   4659: =item * &latexhyphenation()
                   4660: 
                   4661: Same as above but what's supplied is the language as it might be stored
                   4662: in the metadata.
                   4663: 
                   4664: =cut
                   4665: 
                   4666: sub latexhyphenation {
                   4667:     my $key = shift;
                   4668:     return $latex_language_bykey{$key};
                   4669: }
                   4670: 
                   4671: =pod
                   4672: 
1.648     raeburn  4673: =item * &copyrightids() 
1.112     bowersj2 4674: 
                   4675: returns list of all copyrights
                   4676: 
                   4677: =cut
                   4678: 
                   4679: sub copyrightids {
                   4680:     return sort(keys(%cprtag));
                   4681: }
                   4682: 
                   4683: =pod
                   4684: 
1.648     raeburn  4685: =item * &copyrightdescription() 
1.112     bowersj2 4686: 
                   4687: returns description of a specified copyright id
                   4688: 
                   4689: =cut
                   4690: 
                   4691: sub copyrightdescription {
1.166     www      4692:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 4693: }
1.197     matthew  4694: 
                   4695: =pod
                   4696: 
1.648     raeburn  4697: =item * &source_copyrightids() 
1.192     taceyjo1 4698: 
                   4699: returns list of all source copyrights
                   4700: 
                   4701: =cut
                   4702: 
                   4703: sub source_copyrightids {
                   4704:     return sort(keys(%scprtag));
                   4705: }
                   4706: 
                   4707: =pod
                   4708: 
1.648     raeburn  4709: =item * &source_copyrightdescription() 
1.192     taceyjo1 4710: 
                   4711: returns description of a specified source copyright id
                   4712: 
                   4713: =cut
                   4714: 
                   4715: sub source_copyrightdescription {
                   4716:     return &mt($scprtag{shift(@_)});
                   4717: }
1.112     bowersj2 4718: 
                   4719: =pod
                   4720: 
1.648     raeburn  4721: =item * &filecategories() 
1.112     bowersj2 4722: 
                   4723: returns list of all file categories
                   4724: 
                   4725: =cut
                   4726: 
                   4727: sub filecategories {
                   4728:     return sort(keys(%category_extensions));
                   4729: }
                   4730: 
                   4731: =pod
                   4732: 
1.648     raeburn  4733: =item * &filecategorytypes() 
1.112     bowersj2 4734: 
                   4735: returns list of file types belonging to a given file
                   4736: category
                   4737: 
                   4738: =cut
                   4739: 
                   4740: sub filecategorytypes {
1.356     albertel 4741:     my ($cat) = @_;
1.1248    raeburn  4742:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
                   4743:         return @{$category_extensions{lc($cat)}};
                   4744:     } else {
                   4745:         return ();
                   4746:     }
1.112     bowersj2 4747: }
                   4748: 
                   4749: =pod
                   4750: 
1.648     raeburn  4751: =item * &fileembstyle() 
1.112     bowersj2 4752: 
                   4753: returns embedding style for a specified file type
                   4754: 
                   4755: =cut
                   4756: 
                   4757: sub fileembstyle {
                   4758:     return $fe{lc(shift(@_))};
1.169     www      4759: }
                   4760: 
1.351     www      4761: sub filemimetype {
                   4762:     return $fm{lc(shift(@_))};
                   4763: }
                   4764: 
1.169     www      4765: 
                   4766: sub filecategoryselect {
                   4767:     my ($name,$value)=@_;
1.189     matthew  4768:     return &select_form($value,$name,
1.970     raeburn  4769:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 4770: }
                   4771: 
                   4772: =pod
                   4773: 
1.648     raeburn  4774: =item * &filedescription() 
1.112     bowersj2 4775: 
                   4776: returns description for a specified file type
                   4777: 
                   4778: =cut
                   4779: 
                   4780: sub filedescription {
1.188     matthew  4781:     my $file_description = $fd{lc(shift())};
                   4782:     $file_description =~ s:([\[\]]):~$1:g;
                   4783:     return &mt($file_description);
1.112     bowersj2 4784: }
                   4785: 
                   4786: =pod
                   4787: 
1.648     raeburn  4788: =item * &filedescriptionex() 
1.112     bowersj2 4789: 
                   4790: returns description for a specified file type with
                   4791: extra formatting
                   4792: 
                   4793: =cut
                   4794: 
                   4795: sub filedescriptionex {
                   4796:     my $ex=shift;
1.188     matthew  4797:     my $file_description = $fd{lc($ex)};
                   4798:     $file_description =~ s:([\[\]]):~$1:g;
                   4799:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 4800: }
                   4801: 
                   4802: # End of .tab access
                   4803: =pod
                   4804: 
                   4805: =back
                   4806: 
                   4807: =cut
                   4808: 
                   4809: # ------------------------------------------------------------------ File Types
                   4810: sub fileextensions {
                   4811:     return sort(keys(%fe));
                   4812: }
                   4813: 
1.97      www      4814: # ----------------------------------------------------------- Display Languages
                   4815: # returns a hash with all desired display languages
                   4816: #
                   4817: 
                   4818: sub display_languages {
                   4819:     my %languages=();
1.695     raeburn  4820:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 4821: 	$languages{$lang}=1;
1.97      www      4822:     }
                   4823:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 4824:     if ($env{'form.displaylanguage'}) {
1.356     albertel 4825: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   4826: 	    $languages{$lang}=1;
1.97      www      4827:         }
                   4828:     }
                   4829:     return %languages;
1.14      harris41 4830: }
                   4831: 
1.582     albertel 4832: sub languages {
                   4833:     my ($possible_langs) = @_;
1.695     raeburn  4834:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 4835:     if (!ref($possible_langs)) {
                   4836: 	if( wantarray ) {
                   4837: 	    return @preferred_langs;
                   4838: 	} else {
                   4839: 	    return $preferred_langs[0];
                   4840: 	}
                   4841:     }
                   4842:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   4843:     my @preferred_possibilities;
                   4844:     foreach my $preferred_lang (@preferred_langs) {
                   4845: 	if (exists($possibilities{$preferred_lang})) {
                   4846: 	    push(@preferred_possibilities, $preferred_lang);
                   4847: 	}
                   4848:     }
                   4849:     if( wantarray ) {
                   4850: 	return @preferred_possibilities;
                   4851:     }
                   4852:     return $preferred_possibilities[0];
                   4853: }
                   4854: 
1.742     raeburn  4855: sub user_lang {
                   4856:     my ($touname,$toudom,$fromcid) = @_;
                   4857:     my @userlangs;
                   4858:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   4859:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   4860:                     $env{'course.'.$fromcid.'.languages'}));
                   4861:     } else {
                   4862:         my %langhash = &getlangs($touname,$toudom);
                   4863:         if ($langhash{'languages'} ne '') {
                   4864:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   4865:         } else {
                   4866:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   4867:             if ($domdefs{'lang_def'} ne '') {
                   4868:                 @userlangs = ($domdefs{'lang_def'});
                   4869:             }
                   4870:         }
                   4871:     }
                   4872:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   4873:     my $user_lh = Apache::localize->get_handle(@languages);
                   4874:     return $user_lh;
                   4875: }
                   4876: 
                   4877: 
1.112     bowersj2 4878: ###############################################################
                   4879: ##               Student Answer Attempts                     ##
                   4880: ###############################################################
                   4881: 
                   4882: =pod
                   4883: 
                   4884: =head1 Alternate Problem Views
                   4885: 
                   4886: =over 4
                   4887: 
1.648     raeburn  4888: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  4889:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4890: 
                   4891: Return string with previous attempt on problem. Arguments:
                   4892: 
                   4893: =over 4
                   4894: 
                   4895: =item * $symb: Problem, including path
                   4896: 
                   4897: =item * $username: username of the desired student
                   4898: 
                   4899: =item * $domain: domain of the desired student
1.14      harris41 4900: 
1.112     bowersj2 4901: =item * $course: Course ID
1.14      harris41 4902: 
1.112     bowersj2 4903: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4904:     something
1.14      harris41 4905: 
1.112     bowersj2 4906: =item * $regexp: if string matches this regexp, the string will be
                   4907:     sent to $gradesub
1.14      harris41 4908: 
1.112     bowersj2 4909: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4910: 
1.1199    raeburn  4911: =item * $usec: section of the desired student
                   4912: 
                   4913: =item * $identifier: counter for student (multiple students one problem) or 
                   4914:     problem (one student; whole sequence).
                   4915: 
1.112     bowersj2 4916: =back
1.14      harris41 4917: 
1.112     bowersj2 4918: The output string is a table containing all desired attempts, if any.
1.16      harris41 4919: 
1.112     bowersj2 4920: =cut
1.1       albertel 4921: 
                   4922: sub get_previous_attempt {
1.1199    raeburn  4923:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4924:   my $prevattempts='';
1.43      ng       4925:   no strict 'refs';
1.1       albertel 4926:   if ($symb) {
1.3       albertel 4927:     my (%returnhash)=
                   4928:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4929:     if ($returnhash{'version'}) {
                   4930:       my %lasthash=();
                   4931:       my $version;
                   4932:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4933:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4934:             if ($key =~ /\.rawrndseed$/) {
                   4935:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4936:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4937:             } else {
                   4938:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4939:             }
1.19      harris41 4940:         }
1.1       albertel 4941:       }
1.596     albertel 4942:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4943:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4944:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4945:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4946:       foreach my $key (sort(keys(%lasthash))) {
                   4947: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4948: 	if ($#parts > 0) {
1.31      albertel 4949: 	  my $data=$parts[-1];
1.989     raeburn  4950:           next if ($data eq 'foilorder');
1.31      albertel 4951: 	  pop(@parts);
1.1010    www      4952:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4953:           if ($data eq 'type') {
                   4954:               unless ($showsurv) {
                   4955:                   my $id = join(',',@parts);
                   4956:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4957:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4958:                       $lasthidden{$ign.'.'.$id} = 1;
                   4959:                   }
1.945     raeburn  4960:               }
1.1199    raeburn  4961:               if ($identifier ne '') {
                   4962:                   my $id = join(',',@parts);
                   4963:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4964:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4965:                       $hidestatus{$ign.'.'.$id} = 1;
                   4966:                   }
                   4967:               }
                   4968:           } elsif ($data eq 'regrader') {
                   4969:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4970:                   my $id = join(',',@parts);
                   4971:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4972:               }
1.1010    www      4973:           } 
1.31      albertel 4974: 	} else {
1.41      ng       4975: 	  if ($#parts == 0) {
                   4976: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4977: 	  } else {
                   4978: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4979: 	  }
1.31      albertel 4980: 	}
1.16      harris41 4981:       }
1.596     albertel 4982:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4983:       if ($getattempt eq '') {
1.1199    raeburn  4984:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4985:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4986:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4987:                 foreach my $id (keys(%regraded)) {
                   4988:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4989:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4990:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4991:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4992:                     }
                   4993:                 }
                   4994:             }
1.1200    raeburn  4995:         }
                   4996: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4997:             my (@hidden,@unsolved);
1.945     raeburn  4998:             if (%typeparts) {
                   4999:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  5000:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   5001:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  5002:                         push(@hidden,$id);
1.1199    raeburn  5003:                     } elsif ($identifier ne '') {
                   5004:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   5005:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   5006:                                 ($hidestatus{$id})) {
1.1200    raeburn  5007:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  5008:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   5009:                                 push(@{$solved{$id}},$version);
                   5010:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   5011:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   5012:                                 my $skip;
                   5013:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   5014:                                     foreach my $reset (@{$resets{$id}}) {
                   5015:                                         if ($reset > $solved{$id}[-1]) {
                   5016:                                             $skip=1;
                   5017:                                             last;
                   5018:                                         }
                   5019:                                     }
                   5020:                                 }
                   5021:                                 unless ($skip) {
                   5022:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   5023:                                     push(@unsolved,$partslist);
                   5024:                                 }
                   5025:                             }
                   5026:                         }
1.945     raeburn  5027:                     }
                   5028:                 }
                   5029:             }
                   5030:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  5031:                            '<td>'.&mt('Transaction [_1]',$version);
                   5032:             if (@unsolved) {
                   5033:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   5034:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   5035:                                  &mt('Hide').'</label></span>';
                   5036:             }
                   5037:             $prevattempts .= '</td>';
1.945     raeburn  5038:             if (@hidden) {
                   5039:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5040:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  5041:                     my $hide;
                   5042:                     foreach my $id (@hidden) {
                   5043:                         if ($key =~ /^\Q$id\E/) {
                   5044:                             $hide = 1;
                   5045:                             last;
                   5046:                         }
                   5047:                     }
                   5048:                     if ($hide) {
                   5049:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5050:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5051:                             my $value = &format_previous_attempt_value($key,
                   5052:                                              $returnhash{$version.':'.$key});
1.1173    kruse    5053:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5054:                         } else {
                   5055:                             $prevattempts.='<td>&nbsp;</td>';
                   5056:                         }
                   5057:                     } else {
                   5058:                         if ($key =~ /\./) {
1.1212    raeburn  5059:                             my $value = $returnhash{$version.':'.$key};
                   5060:                             if ($key =~ /\.rndseed$/) {
                   5061:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5062:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5063:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5064:                                 }
                   5065:                             }
                   5066:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5067:                                            '&nbsp;</td>';
1.945     raeburn  5068:                         } else {
                   5069:                             $prevattempts.='<td>&nbsp;</td>';
                   5070:                         }
                   5071:                     }
                   5072:                 }
                   5073:             } else {
                   5074: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5075:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  5076:                     my $value = $returnhash{$version.':'.$key};
                   5077:                     if ($key =~ /\.rndseed$/) {
                   5078:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   5079:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   5080:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   5081:                         }
                   5082:                     }
                   5083:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   5084:                                    '&nbsp;</td>';
1.945     raeburn  5085: 	        }
                   5086:             }
                   5087: 	    $prevattempts.=&end_data_table_row();
1.40      ng       5088: 	 }
1.1       albertel 5089:       }
1.945     raeburn  5090:       my @currhidden = keys(%lasthidden);
1.596     albertel 5091:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 5092:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  5093:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  5094:           if (%typeparts) {
                   5095:               my $hidden;
                   5096:               foreach my $id (@currhidden) {
                   5097:                   if ($key =~ /^\Q$id\E/) {
                   5098:                       $hidden = 1;
                   5099:                       last;
                   5100:                   }
                   5101:               }
                   5102:               if ($hidden) {
                   5103:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   5104:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   5105:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5106:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5107:                           $value = &$gradesub($value);
                   5108:                       }
1.1173    kruse    5109:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  5110:                   } else {
                   5111:                       $prevattempts.='<td>&nbsp;</td>';
                   5112:                   }
                   5113:               } else {
                   5114:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5115:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5116:                       $value = &$gradesub($value);
                   5117:                   }
1.1173    kruse    5118:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5119:               }
                   5120:           } else {
                   5121: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   5122: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   5123:                   $value = &$gradesub($value);
                   5124:               }
1.1173    kruse    5125: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  5126:           }
1.16      harris41 5127:       }
1.596     albertel 5128:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 5129:     } else {
1.1305    raeburn  5130:       my $msg;
                   5131:       if ($symb =~ /ext\.tool$/) {
                   5132:           $msg = &mt('No grade passed back.');
                   5133:       } else {
                   5134:           $msg = &mt('Nothing submitted - no attempts.');
                   5135:       }
1.596     albertel 5136:       $prevattempts=
                   5137: 	  &start_data_table().&start_data_table_row().
1.1305    raeburn  5138: 	  '<td>'.$msg.'</td>'.
1.596     albertel 5139: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5140:     }
                   5141:   } else {
1.596     albertel 5142:     $prevattempts=
                   5143: 	  &start_data_table().&start_data_table_row().
                   5144: 	  '<td>'.&mt('No data.').'</td>'.
                   5145: 	  &end_data_table_row().&end_data_table();
1.1       albertel 5146:   }
1.10      albertel 5147: }
                   5148: 
1.581     albertel 5149: sub format_previous_attempt_value {
                   5150:     my ($key,$value) = @_;
1.1011    www      5151:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    5152:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 5153:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    5154:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  5155:     } elsif ($key =~ /answerstring$/) {
                   5156:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    5157:         my @answer = %answers;
                   5158:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  5159:         my @anskeys = sort(keys(%answers));
                   5160:         if (@anskeys == 1) {
                   5161:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  5162:             if ($answer =~ m{\0}) {
                   5163:                 $answer =~ s{\0}{,}g;
1.988     raeburn  5164:             }
                   5165:             my $tag_internal_answer_name = 'INTERNAL';
                   5166:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   5167:                 $value = $answer; 
                   5168:             } else {
                   5169:                 $value = $anskeys[0].'='.$answer;
                   5170:             }
                   5171:         } else {
                   5172:             foreach my $ans (@anskeys) {
                   5173:                 my $answer = $answers{$ans};
1.1001    raeburn  5174:                 if ($answer =~ m{\0}) {
                   5175:                     $answer =~ s{\0}{,}g;
1.988     raeburn  5176:                 }
                   5177:                 $value .=  $ans.'='.$answer.'<br />';;
                   5178:             } 
                   5179:         }
1.581     albertel 5180:     } else {
1.1173    kruse    5181:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 5182:     }
                   5183:     return $value;
                   5184: }
                   5185: 
                   5186: 
1.107     albertel 5187: sub relative_to_absolute {
                   5188:     my ($url,$output)=@_;
                   5189:     my $parser=HTML::TokeParser->new(\$output);
                   5190:     my $token;
                   5191:     my $thisdir=$url;
                   5192:     my @rlinks=();
                   5193:     while ($token=$parser->get_token) {
                   5194: 	if ($token->[0] eq 'S') {
                   5195: 	    if ($token->[1] eq 'a') {
                   5196: 		if ($token->[2]->{'href'}) {
                   5197: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   5198: 		}
                   5199: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   5200: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   5201: 	    } elsif ($token->[1] eq 'base') {
                   5202: 		$thisdir=$token->[2]->{'href'};
                   5203: 	    }
                   5204: 	}
                   5205:     }
                   5206:     $thisdir=~s-/[^/]*$--;
1.356     albertel 5207:     foreach my $link (@rlinks) {
1.726     raeburn  5208: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 5209: 		($link=~/^\//) ||
                   5210: 		($link=~/^javascript:/i) ||
                   5211: 		($link=~/^mailto:/i) ||
                   5212: 		($link=~/^\#/)) {
                   5213: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   5214: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 5215: 	}
                   5216:     }
                   5217: # -------------------------------------------------- Deal with Applet codebases
                   5218:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   5219:     return $output;
                   5220: }
                   5221: 
1.112     bowersj2 5222: =pod
                   5223: 
1.648     raeburn  5224: =item * &get_student_view()
1.112     bowersj2 5225: 
                   5226: show a snapshot of what student was looking at
                   5227: 
                   5228: =cut
                   5229: 
1.10      albertel 5230: sub get_student_view {
1.186     albertel 5231:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      5232:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5233:   my (%form);
1.10      albertel 5234:   my @elements=('symb','courseid','domain','username');
                   5235:   foreach my $element (@elements) {
1.186     albertel 5236:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5237:   }
1.186     albertel 5238:   if (defined($moreenv)) {
                   5239:       %form=(%form,%{$moreenv});
                   5240:   }
1.236     albertel 5241:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 5242:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.1306    raeburn  5243:   if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
                   5244:       $feedurl =~ s{^/adm/wrapper}{};
                   5245:   }
1.650     www      5246:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 5247:   $userview=~s/\<body[^\>]*\>//gi;
                   5248:   $userview=~s/\<\/body\>//gi;
                   5249:   $userview=~s/\<html\>//gi;
                   5250:   $userview=~s/\<\/html\>//gi;
                   5251:   $userview=~s/\<head\>//gi;
                   5252:   $userview=~s/\<\/head\>//gi;
                   5253:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 5254:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      5255:   if (wantarray) {
                   5256:      return ($userview,$response);
                   5257:   } else {
                   5258:      return $userview;
                   5259:   }
                   5260: }
                   5261: 
                   5262: sub get_student_view_with_retries {
                   5263:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   5264: 
                   5265:     my $ok = 0;                 # True if we got a good response.
                   5266:     my $content;
                   5267:     my $response;
                   5268: 
                   5269:     # Try to get the student_view done. within the retries count:
                   5270:     
                   5271:     do {
                   5272:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   5273:          $ok      = $response->is_success;
                   5274:          if (!$ok) {
                   5275:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   5276:          }
                   5277:          $retries--;
                   5278:     } while (!$ok && ($retries > 0));
                   5279:     
                   5280:     if (!$ok) {
                   5281:        $content = '';          # On error return an empty content.
                   5282:     }
1.651     www      5283:     if (wantarray) {
                   5284:        return ($content, $response);
                   5285:     } else {
                   5286:        return $content;
                   5287:     }
1.11      albertel 5288: }
                   5289: 
1.1349    raeburn  5290: sub css_links {
                   5291:     my ($currsymb,$level) = @_;
                   5292:     my ($links,@symbs,%cssrefs,%httpref);
                   5293:     if ($level eq 'map') {
                   5294:         my $navmap = Apache::lonnavmaps::navmap->new();
                   5295:         if (ref($navmap)) {
                   5296:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
                   5297:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
                   5298:             foreach my $res (@resources) {
                   5299:                 if (ref($res) && $res->symb()) {
                   5300:                     push(@symbs,$res->symb());
                   5301:                 }
                   5302:             }
                   5303:         }
                   5304:     } else {
                   5305:         @symbs = ($currsymb);
                   5306:     }
                   5307:     foreach my $symb (@symbs) {
                   5308:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
                   5309:         if ($css_href =~ /\S/) {
                   5310:             unless ($css_href =~ m{https?://}) {
                   5311:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
                   5312:                 my $proburl =  &Apache::lonnet::clutter($url);
                   5313:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
                   5314:                 unless ($css_href =~ m{^/}) {
                   5315:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
                   5316:                 }
                   5317:                 if ($css_href =~ m{^/(res|uploaded)/}) {
                   5318:                     unless (($httpref{'httpref.'.$css_href}) ||
                   5319:                             (&Apache::lonnet::is_on_map($css_href))) {
                   5320:                         my $thisurl = $proburl;
                   5321:                         if ($env{'httpref.'.$proburl}) {
                   5322:                             $thisurl = $env{'httpref.'.$proburl};
                   5323:                         }
                   5324:                         $httpref{'httpref.'.$css_href} = $thisurl;
                   5325:                     }
                   5326:                 }
                   5327:             }
                   5328:             $cssrefs{$css_href} = 1;
                   5329:         }
                   5330:     }
                   5331:     if (keys(%httpref)) {
                   5332:         &Apache::lonnet::appenv(\%httpref);
                   5333:     }
                   5334:     if (keys(%cssrefs)) {
                   5335:         foreach my $css_href (keys(%cssrefs)) {
                   5336:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
                   5337:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
                   5338:         }
                   5339:     }
                   5340:     return $links;
                   5341: }
                   5342: 
1.112     bowersj2 5343: =pod
                   5344: 
1.648     raeburn  5345: =item * &get_student_answers() 
1.112     bowersj2 5346: 
                   5347: show a snapshot of how student was answering problem
                   5348: 
                   5349: =cut
                   5350: 
1.11      albertel 5351: sub get_student_answers {
1.100     sakharuk 5352:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      5353:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 5354:   my (%moreenv);
1.11      albertel 5355:   my @elements=('symb','courseid','domain','username');
                   5356:   foreach my $element (@elements) {
1.186     albertel 5357:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 5358:   }
1.186     albertel 5359:   $moreenv{'grade_target'}='answer';
                   5360:   %moreenv=(%form,%moreenv);
1.497     raeburn  5361:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   5362:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 5363:   return $userview;
1.1       albertel 5364: }
1.116     albertel 5365: 
                   5366: =pod
                   5367: 
                   5368: =item * &submlink()
                   5369: 
1.242     albertel 5370: Inputs: $text $uname $udom $symb $target
1.116     albertel 5371: 
                   5372: Returns: A link to grades.pm such as to see the SUBM view of a student
                   5373: 
                   5374: =cut
                   5375: 
                   5376: ###############################################
                   5377: sub submlink {
1.242     albertel 5378:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 5379:     if (!($uname && $udom)) {
                   5380: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5381: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 5382: 	if (!$symb) { $symb=$cursymb; }
                   5383:     }
1.254     matthew  5384:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5385:     $symb=&escape($symb);
1.960     bisitz   5386:     if ($target) { $target=" target=\"$target\""; }
                   5387:     return
                   5388:         '<a href="/adm/grades?command=submission'.
                   5389:         '&amp;symb='.$symb.
                   5390:         '&amp;student='.$uname.
                   5391:         '&amp;userdom='.$udom.'"'.
                   5392:         $target.'>'.$text.'</a>';
1.242     albertel 5393: }
                   5394: ##############################################
                   5395: 
                   5396: =pod
                   5397: 
                   5398: =item * &pgrdlink()
                   5399: 
                   5400: Inputs: $text $uname $udom $symb $target
                   5401: 
                   5402: Returns: A link to grades.pm such as to see the PGRD view of a student
                   5403: 
                   5404: =cut
                   5405: 
                   5406: ###############################################
                   5407: sub pgrdlink {
                   5408:     my $link=&submlink(@_);
                   5409:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   5410:     return $link;
                   5411: }
                   5412: ##############################################
                   5413: 
                   5414: =pod
                   5415: 
                   5416: =item * &pprmlink()
                   5417: 
                   5418: Inputs: $text $uname $udom $symb $target
                   5419: 
                   5420: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 5421: student and a specific resource
1.242     albertel 5422: 
                   5423: =cut
                   5424: 
                   5425: ###############################################
                   5426: sub pprmlink {
                   5427:     my ($text,$uname,$udom,$symb,$target)=@_;
                   5428:     if (!($uname && $udom)) {
                   5429: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 5430: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 5431: 	if (!$symb) { $symb=$cursymb; }
                   5432:     }
1.254     matthew  5433:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      5434:     $symb=&escape($symb);
1.242     albertel 5435:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 5436:     return '<a href="/adm/parmset?command=set&amp;'.
                   5437: 	'symb='.$symb.'&amp;uname='.$uname.
                   5438: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 5439: }
                   5440: ##############################################
1.37      matthew  5441: 
1.112     bowersj2 5442: =pod
                   5443: 
                   5444: =back
                   5445: 
                   5446: =cut
                   5447: 
1.37      matthew  5448: ###############################################
1.51      www      5449: 
                   5450: 
                   5451: sub timehash {
1.687     raeburn  5452:     my ($thistime) = @_;
                   5453:     my $timezone = &Apache::lonlocal::gettimezone();
                   5454:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   5455:                      ->set_time_zone($timezone);
                   5456:     my $wday = $dt->day_of_week();
                   5457:     if ($wday == 7) { $wday = 0; }
                   5458:     return ( 'second' => $dt->second(),
                   5459:              'minute' => $dt->minute(),
                   5460:              'hour'   => $dt->hour(),
                   5461:              'day'     => $dt->day_of_month(),
                   5462:              'month'   => $dt->month(),
                   5463:              'year'    => $dt->year(),
                   5464:              'weekday' => $wday,
                   5465:              'dayyear' => $dt->day_of_year(),
                   5466:              'dlsav'   => $dt->is_dst() );
1.51      www      5467: }
                   5468: 
1.370     www      5469: sub utc_string {
                   5470:     my ($date)=@_;
1.371     www      5471:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      5472: }
                   5473: 
1.51      www      5474: sub maketime {
                   5475:     my %th=@_;
1.687     raeburn  5476:     my ($epoch_time,$timezone,$dt);
                   5477:     $timezone = &Apache::lonlocal::gettimezone();
                   5478:     eval {
                   5479:         $dt = DateTime->new( year   => $th{'year'},
                   5480:                              month  => $th{'month'},
                   5481:                              day    => $th{'day'},
                   5482:                              hour   => $th{'hour'},
                   5483:                              minute => $th{'minute'},
                   5484:                              second => $th{'second'},
                   5485:                              time_zone => $timezone,
                   5486:                          );
                   5487:     };
                   5488:     if (!$@) {
                   5489:         $epoch_time = $dt->epoch;
                   5490:         if ($epoch_time) {
                   5491:             return $epoch_time;
                   5492:         }
                   5493:     }
1.51      www      5494:     return POSIX::mktime(
                   5495:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      5496:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      5497: }
                   5498: 
                   5499: #########################################
1.51      www      5500: 
                   5501: sub findallcourses {
1.482     raeburn  5502:     my ($roles,$uname,$udom) = @_;
1.355     albertel 5503:     my %roles;
                   5504:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 5505:     my %courses;
1.51      www      5506:     my $now=time;
1.482     raeburn  5507:     if (!defined($uname)) {
                   5508:         $uname = $env{'user.name'};
                   5509:     }
                   5510:     if (!defined($udom)) {
                   5511:         $udom = $env{'user.domain'};
                   5512:     }
                   5513:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  5514:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  5515:         if (!%roles) {
                   5516:             %roles = (
                   5517:                        cc => 1,
1.907     raeburn  5518:                        co => 1,
1.482     raeburn  5519:                        in => 1,
                   5520:                        ep => 1,
                   5521:                        ta => 1,
                   5522:                        cr => 1,
                   5523:                        st => 1,
                   5524:              );
                   5525:         }
                   5526:         foreach my $entry (keys(%roleshash)) {
                   5527:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   5528:             if ($trole =~ /^cr/) { 
                   5529:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   5530:             } else {
                   5531:                 next if (!exists($roles{$trole}));
                   5532:             }
                   5533:             if ($tend) {
                   5534:                 next if ($tend < $now);
                   5535:             }
                   5536:             if ($tstart) {
                   5537:                 next if ($tstart > $now);
                   5538:             }
1.1058    raeburn  5539:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  5540:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  5541:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  5542:             if ($secpart eq '') {
                   5543:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   5544:                 $sec = 'none';
1.1058    raeburn  5545:                 $value .= $cnum.'/';
1.482     raeburn  5546:             } else {
                   5547:                 $cnum = $cnumpart;
                   5548:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  5549:                 $value .= $cnum.'/'.$sec;
                   5550:             }
                   5551:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5552:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5553:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5554:                 }
                   5555:             } else {
                   5556:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  5557:             }
1.482     raeburn  5558:         }
                   5559:     } else {
                   5560:         foreach my $key (keys(%env)) {
1.483     albertel 5561: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   5562:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  5563: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   5564: 	        next if ($role eq 'ca' || $role eq 'aa');
                   5565: 	        next if (%roles && !exists($roles{$role}));
                   5566: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   5567:                 my $active=1;
                   5568:                 if ($starttime) {
                   5569: 		    if ($now<$starttime) { $active=0; }
                   5570:                 }
                   5571:                 if ($endtime) {
                   5572:                     if ($now>$endtime) { $active=0; }
                   5573:                 }
                   5574:                 if ($active) {
1.1058    raeburn  5575:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  5576:                     if ($sec eq '') {
                   5577:                         $sec = 'none';
1.1058    raeburn  5578:                     } else {
                   5579:                         $value .= $sec;
                   5580:                     }
                   5581:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   5582:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   5583:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   5584:                         }
                   5585:                     } else {
                   5586:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  5587:                     }
1.474     raeburn  5588:                 }
                   5589:             }
1.51      www      5590:         }
                   5591:     }
1.474     raeburn  5592:     return %courses;
1.51      www      5593: }
1.37      matthew  5594: 
1.54      www      5595: ###############################################
1.474     raeburn  5596: 
                   5597: sub blockcheck {
1.1372    raeburn  5598:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
                   5599:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
                   5600:         my ($has_evb,$check_ipaccess);
                   5601:         my $dom = $env{'user.domain'};
                   5602:         if ($env{'request.course.id'}) {
                   5603:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5604:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5605:             my $checkrole = "cm./$cdom/$cnum";
                   5606:             my $sec = $env{'request.course.sec'};
                   5607:             if ($sec ne '') {
                   5608:                 $checkrole .= "/$sec";
                   5609:             }
                   5610:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   5611:                 ($env{'request.role'} !~ /^st/)) {
                   5612:                 $has_evb = 1;
                   5613:             }
                   5614:             unless ($has_evb) {
                   5615:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
                   5616:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
                   5617:                     if ($udom eq $cdom) {
                   5618:                         $check_ipaccess = 1;
                   5619:                     }
                   5620:                 }
                   5621:             }
1.1375    raeburn  5622:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
                   5623:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
                   5624:             my $checkrole;
                   5625:             if ($env{'request.role.domain'} eq '') {
                   5626:                 $checkrole = "cm./$env{'user.domain'}/";
                   5627:             } else {
                   5628:                 $checkrole = "cm./$env{'request.role.domain'}/";
                   5629:             }
                   5630:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
                   5631:                 $has_evb = 1;
                   5632:             }
1.1372    raeburn  5633:         }
                   5634:         unless ($has_evb || $check_ipaccess) {
                   5635:             my @machinedoms = &Apache::lonnet::current_machine_domains();
                   5636:             if (($dom eq 'public') && ($activity eq 'port')) {
                   5637:                 $dom = $udom;
                   5638:             }
                   5639:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
                   5640:                 $check_ipaccess = 1;
                   5641:             } else {
                   5642:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   5643:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
                   5644:                 my $prim = &Apache::lonnet::domain($dom,'primary');
                   5645:                 my $intdom = &Apache::lonnet::internet_dom($prim);
                   5646:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
                   5647:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   5648:                         $check_ipaccess = 1;
                   5649:                     }
                   5650:                 }
                   5651:             }
                   5652:         }
                   5653:         if ($check_ipaccess) {
                   5654:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
                   5655:             unless (defined($cached)) {
                   5656:                 my %domconfig =
                   5657:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
                   5658:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
                   5659:             }
                   5660:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
                   5661:                 foreach my $id (keys(%{$ipaccessref})) {
                   5662:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
                   5663:                         my $range = $ipaccessref->{$id}->{'ip'};
                   5664:                         if ($range) {
                   5665:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
                   5666:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
                   5667:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
                   5668:                                         return ('','','',$id,$dom);
                   5669:                                         last;
                   5670:                                     }
                   5671:                                 }
                   5672:                             }
                   5673:                         }
                   5674:                     }
                   5675:                 }
                   5676:             }
                   5677:         }
1.1373    raeburn  5678:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5679:             return ();
                   5680:         }
1.1372    raeburn  5681:     }
1.1189    raeburn  5682:     if (defined($udom) && defined($uname)) {
                   5683:         # If uname and udom are for a course, check for blocks in the course.
                   5684:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   5685:             my ($startblock,$endblock,$triggerblock) =
1.1347    raeburn  5686:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
1.1189    raeburn  5687:             return ($startblock,$endblock,$triggerblock);
                   5688:         }
                   5689:     } else {
1.490     raeburn  5690:         $udom = $env{'user.domain'};
                   5691:         $uname = $env{'user.name'};
                   5692:     }
                   5693: 
1.502     raeburn  5694:     my $startblock = 0;
                   5695:     my $endblock = 0;
1.1062    raeburn  5696:     my $triggerblock = '';
1.1373    raeburn  5697:     my %live_courses;
                   5698:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
                   5699:         %live_courses = &findallcourses(undef,$uname,$udom);
                   5700:     }
1.474     raeburn  5701: 
1.490     raeburn  5702:     # If uname is for a user, and activity is course-specific, i.e.,
                   5703:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  5704: 
1.490     raeburn  5705:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1282    raeburn  5706:          $activity eq 'groups' || $activity eq 'printout' ||
1.1346    raeburn  5707:          $activity eq 'search' || $activity eq 'reinit' ||
                   5708:          $activity eq 'alert') &&
1.1189    raeburn  5709:         ($env{'request.course.id'})) {
1.490     raeburn  5710:         foreach my $key (keys(%live_courses)) {
                   5711:             if ($key ne $env{'request.course.id'}) {
                   5712:                 delete($live_courses{$key});
                   5713:             }
                   5714:         }
                   5715:     }
                   5716: 
                   5717:     my $otheruser = 0;
                   5718:     my %own_courses;
                   5719:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   5720:         # Resource belongs to user other than current user.
                   5721:         $otheruser = 1;
                   5722:         # Gather courses for current user
                   5723:         %own_courses = 
                   5724:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   5725:     }
                   5726: 
                   5727:     # Gather active course roles - course coordinator, instructor, 
                   5728:     # exam proctor, ta, student, or custom role.
1.474     raeburn  5729: 
                   5730:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  5731:         my ($cdom,$cnum);
                   5732:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   5733:             $cdom = $env{'course.'.$course.'.domain'};
                   5734:             $cnum = $env{'course.'.$course.'.num'};
                   5735:         } else {
1.490     raeburn  5736:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  5737:         }
                   5738:         my $no_ownblock = 0;
                   5739:         my $no_userblock = 0;
1.533     raeburn  5740:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  5741:             # Check if current user has 'evb' priv for this
                   5742:             if (defined($own_courses{$course})) {
                   5743:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   5744:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   5745:                     if ($sec ne 'none') {
                   5746:                         $checkrole .= '/'.$sec;
                   5747:                     }
                   5748:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5749:                         $no_ownblock = 1;
                   5750:                         last;
                   5751:                     }
                   5752:                 }
                   5753:             }
                   5754:             # if they have 'evb' priv and are currently not playing student
                   5755:             next if (($no_ownblock) &&
                   5756:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   5757:         }
1.474     raeburn  5758:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  5759:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  5760:             if ($sec ne 'none') {
1.482     raeburn  5761:                 $checkrole .= '/'.$sec;
1.474     raeburn  5762:             }
1.490     raeburn  5763:             if ($otheruser) {
                   5764:                 # Resource belongs to user other than current user.
                   5765:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  5766:                 my (%allroles,%userroles);
                   5767:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   5768:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   5769:                         my ($trole,$tdom,$tnum,$tsec);
                   5770:                         if ($entry =~ /^cr/) {
                   5771:                             ($trole,$tdom,$tnum,$tsec) = 
                   5772:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   5773:                         } else {
                   5774:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   5775:                         }
                   5776:                         my ($spec,$area,$trest);
                   5777:                         $area = '/'.$tdom.'/'.$tnum;
                   5778:                         $trest = $tnum;
                   5779:                         if ($tsec ne '') {
                   5780:                             $area .= '/'.$tsec;
                   5781:                             $trest .= '/'.$tsec;
                   5782:                         }
                   5783:                         $spec = $trole.'.'.$area;
                   5784:                         if ($trole =~ /^cr/) {
                   5785:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   5786:                                                               $tdom,$spec,$trest,$area);
                   5787:                         } else {
                   5788:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   5789:                                                                 $tdom,$spec,$trest,$area);
                   5790:                         }
                   5791:                     }
1.1276    raeburn  5792:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  5793:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   5794:                         if ($1) {
                   5795:                             $no_userblock = 1;
                   5796:                             last;
                   5797:                         }
1.486     raeburn  5798:                     }
                   5799:                 }
1.490     raeburn  5800:             } else {
                   5801:                 # Resource belongs to current user
                   5802:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  5803:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   5804:                     $no_ownblock = 1;
                   5805:                     last;
                   5806:                 }
1.474     raeburn  5807:             }
                   5808:         }
                   5809:         # if they have the evb priv and are currently not playing student
1.482     raeburn  5810:         next if (($no_ownblock) &&
1.491     albertel 5811:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  5812:         next if ($no_userblock);
1.474     raeburn  5813: 
1.1303    raeburn  5814:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  5815:         # of specified user, unless user has 'evb' privilege.
1.1284    raeburn  5816: 
1.1062    raeburn  5817:         my ($start,$end,$trigger) = 
1.1347    raeburn  5818:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
1.502     raeburn  5819:         if (($start != 0) && 
                   5820:             (($startblock == 0) || ($startblock > $start))) {
                   5821:             $startblock = $start;
1.1062    raeburn  5822:             if ($trigger ne '') {
                   5823:                 $triggerblock = $trigger;
                   5824:             }
1.502     raeburn  5825:         }
                   5826:         if (($end != 0)  &&
                   5827:             (($endblock == 0) || ($endblock < $end))) {
                   5828:             $endblock = $end;
1.1062    raeburn  5829:             if ($trigger ne '') {
                   5830:                 $triggerblock = $trigger;
                   5831:             }
1.502     raeburn  5832:         }
1.490     raeburn  5833:     }
1.1062    raeburn  5834:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  5835: }
                   5836: 
                   5837: sub get_blocks {
1.1347    raeburn  5838:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
1.490     raeburn  5839:     my $startblock = 0;
                   5840:     my $endblock = 0;
1.1062    raeburn  5841:     my $triggerblock = '';
1.490     raeburn  5842:     my $course = $cdom.'_'.$cnum;
                   5843:     $setters->{$course} = {};
                   5844:     $setters->{$course}{'staff'} = [];
                   5845:     $setters->{$course}{'times'} = [];
1.1062    raeburn  5846:     $setters->{$course}{'triggers'} = [];
                   5847:     my (@blockers,%triggered);
                   5848:     my $now = time;
                   5849:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   5850:     if ($activity eq 'docs') {
1.1348    raeburn  5851:         my ($blocked,$nosymbcache,$noenccheck);
1.1347    raeburn  5852:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
                   5853:             $blocked = 1;
                   5854:             $nosymbcache = 1;
1.1348    raeburn  5855:             $noenccheck = 1;
1.1347    raeburn  5856:         }
1.1348    raeburn  5857:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
1.1062    raeburn  5858:         foreach my $block (@blockers) {
                   5859:             if ($block =~ /^firstaccess____(.+)$/) {
                   5860:                 my $item = $1;
                   5861:                 my $type = 'map';
                   5862:                 my $timersymb = $item;
                   5863:                 if ($item eq 'course') {
                   5864:                     $type = 'course';
                   5865:                 } elsif ($item =~ /___\d+___/) {
                   5866:                     $type = 'resource';
                   5867:                 } else {
                   5868:                     $timersymb = &Apache::lonnet::symbread($item);
                   5869:                 }
                   5870:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5871:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   5872:                 $triggered{$block} = {
                   5873:                                        start => $start,
                   5874:                                        end   => $end,
                   5875:                                        type  => $type,
                   5876:                                      };
                   5877:             }
                   5878:         }
                   5879:     } else {
                   5880:         foreach my $block (keys(%commblocks)) {
                   5881:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   5882:                 my ($start,$end) = ($1,$2);
                   5883:                 if ($start <= time && $end >= time) {
                   5884:                     if (ref($commblocks{$block}) eq 'HASH') {
                   5885:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5886:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5887:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   5888:                                     push(@blockers,$block);
                   5889:                                 }
                   5890:                             }
                   5891:                         }
                   5892:                     }
                   5893:                 }
                   5894:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   5895:                 my $item = $1;
                   5896:                 my $timersymb = $item; 
                   5897:                 my $type = 'map';
                   5898:                 if ($item eq 'course') {
                   5899:                     $type = 'course';
                   5900:                 } elsif ($item =~ /___\d+___/) {
                   5901:                     $type = 'resource';
                   5902:                 } else {
                   5903:                     $timersymb = &Apache::lonnet::symbread($item);
                   5904:                 }
                   5905:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   5906:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   5907:                 if ($start && $end) {
                   5908:                     if (($start <= time) && ($end >= time)) {
1.1281    raeburn  5909:                         if (ref($commblocks{$block}) eq 'HASH') {
                   5910:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   5911:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   5912:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
                   5913:                                         push(@blockers,$block);
                   5914:                                         $triggered{$block} = {
                   5915:                                                                start => $start,
                   5916:                                                                end   => $end,
                   5917:                                                                type  => $type,
                   5918:                                                              };
                   5919:                                     }
                   5920:                                 }
                   5921:                             }
1.1062    raeburn  5922:                         }
                   5923:                     }
1.490     raeburn  5924:                 }
1.1062    raeburn  5925:             }
                   5926:         }
                   5927:     }
                   5928:     foreach my $blocker (@blockers) {
                   5929:         my ($staff_name,$staff_dom,$title,$blocks) =
                   5930:             &parse_block_record($commblocks{$blocker});
                   5931:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   5932:         my ($start,$end,$triggertype);
                   5933:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   5934:             ($start,$end) = ($1,$2);
                   5935:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   5936:             $start = $triggered{$blocker}{'start'};
                   5937:             $end = $triggered{$blocker}{'end'};
                   5938:             $triggertype = $triggered{$blocker}{'type'};
                   5939:         }
                   5940:         if ($start) {
                   5941:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   5942:             if ($triggertype) {
                   5943:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   5944:             } else {
                   5945:                 push(@{$$setters{$course}{'triggers'}},0);
                   5946:             }
                   5947:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   5948:                 $startblock = $start;
                   5949:                 if ($triggertype) {
                   5950:                     $triggerblock = $blocker;
1.474     raeburn  5951:                 }
                   5952:             }
1.1062    raeburn  5953:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   5954:                $endblock = $end;
                   5955:                if ($triggertype) {
                   5956:                    $triggerblock = $blocker;
                   5957:                }
                   5958:             }
1.474     raeburn  5959:         }
                   5960:     }
1.1062    raeburn  5961:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  5962: }
                   5963: 
                   5964: sub parse_block_record {
                   5965:     my ($record) = @_;
                   5966:     my ($setuname,$setudom,$title,$blocks);
                   5967:     if (ref($record) eq 'HASH') {
                   5968:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   5969:         $title = &unescape($record->{'event'});
                   5970:         $blocks = $record->{'blocks'};
                   5971:     } else {
                   5972:         my @data = split(/:/,$record,3);
                   5973:         if (scalar(@data) eq 2) {
                   5974:             $title = $data[1];
                   5975:             ($setuname,$setudom) = split(/@/,$data[0]);
                   5976:         } else {
                   5977:             ($setuname,$setudom,$title) = @data;
                   5978:         }
                   5979:         $blocks = { 'com' => 'on' };
                   5980:     }
                   5981:     return ($setuname,$setudom,$title,$blocks);
                   5982: }
                   5983: 
1.854     kalberla 5984: sub blocking_status {
1.1372    raeburn  5985:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
1.1061    raeburn  5986:     my %setters;
1.890     droeschl 5987: 
1.1061    raeburn  5988: # check for active blocking
1.1372    raeburn  5989:     if ($clientip eq '') {
                   5990:         $clientip = &Apache::lonnet::get_requestor_ip();
                   5991:     }
                   5992:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   5993:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
1.1062    raeburn  5994:     my $blocked = 0;
1.1372    raeburn  5995:     if (($startblock && $endblock) || ($by_ip)) {
1.1062    raeburn  5996:         $blocked = 1;
                   5997:     }
1.890     droeschl 5998: 
1.1061    raeburn  5999: # caller just wants to know whether a block is active
                   6000:     if (!wantarray) { return $blocked; }
                   6001: 
                   6002: # build a link to a popup window containing the details
                   6003:     my $querystring  = "?activity=$activity";
1.1351    raeburn  6004: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
                   6005:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
1.1232    raeburn  6006:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
                   6007:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  6008:     } elsif ($activity eq 'docs') {
1.1347    raeburn  6009:         my $showurl = &Apache::lonenc::check_encrypt($url);
                   6010:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
                   6011:         if ($symb) {
                   6012:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
                   6013:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
                   6014:         }
1.1062    raeburn  6015:     }
1.1061    raeburn  6016: 
                   6017:     my $output .= <<'END_MYBLOCK';
                   6018: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   6019:     var options = "width=" + w + ",height=" + h + ",";
                   6020:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   6021:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   6022:     var newWin = window.open(url, wdwName, options);
                   6023:     newWin.focus();
                   6024: }
1.890     droeschl 6025: END_MYBLOCK
1.854     kalberla 6026: 
1.1061    raeburn  6027:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 6028:   
1.1061    raeburn  6029:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  6030:     my $text = &mt('Communication Blocked');
1.1217    raeburn  6031:     my $class = 'LC_comblock';
1.1062    raeburn  6032:     if ($activity eq 'docs') {
                   6033:         $text = &mt('Content Access Blocked');
1.1217    raeburn  6034:         $class = '';
1.1063    raeburn  6035:     } elsif ($activity eq 'printout') {
                   6036:         $text = &mt('Printing Blocked');
1.1232    raeburn  6037:     } elsif ($activity eq 'passwd') {
                   6038:         $text = &mt('Password Changing Blocked');
1.1345    raeburn  6039:     } elsif ($activity eq 'grades') {
                   6040:         $text = &mt('Gradebook Blocked');
1.1346    raeburn  6041:     } elsif ($activity eq 'search') {
                   6042:         $text = &mt('Search Blocked');
1.1282    raeburn  6043:     } elsif ($activity eq 'alert') {
                   6044:         $text = &mt('Checking Critical Messages Blocked');
                   6045:     } elsif ($activity eq 'reinit') {
                   6046:         $text = &mt('Checking Course Update Blocked');
1.1351    raeburn  6047:     } elsif ($activity eq 'about') {
                   6048:         $text = &mt('Access to User Information Pages Blocked');
1.1373    raeburn  6049:     } elsif ($activity eq 'wishlist') {
                   6050:         $text = &mt('Access to Stored Links Blocked');
                   6051:     } elsif ($activity eq 'annotate') {
                   6052:         $text = &mt('Access to Annotations Blocked');
1.1062    raeburn  6053:     }
1.1061    raeburn  6054:     $output .= <<"END_BLOCK";
1.1217    raeburn  6055: <div class='$class'>
1.869     kalberla 6056:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 6057:   title='$text'>
                   6058:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 6059:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 6060:   title='$text'>$text</a>
1.867     kalberla 6061: </div>
                   6062: 
                   6063: END_BLOCK
1.474     raeburn  6064: 
1.1061    raeburn  6065:     return ($blocked, $output);
1.854     kalberla 6066: }
1.490     raeburn  6067: 
1.60      matthew  6068: ###############################################
                   6069: 
1.682     raeburn  6070: sub check_ip_acc {
1.1201    raeburn  6071:     my ($acc,$clientip)=@_;
1.682     raeburn  6072:     &Apache::lonxml::debug("acc is $acc");
                   6073:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   6074:         return 1;
                   6075:     }
1.1339    raeburn  6076:     my ($ip,$allowed);
                   6077:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
                   6078:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
                   6079:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
                   6080:     } else {
1.1350    raeburn  6081:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
                   6082:         $ip = $remote_ip || $env{'request.host'} || $clientip;
1.1339    raeburn  6083:     }
1.682     raeburn  6084: 
                   6085:     my $name;
1.1219    raeburn  6086:     my %access = (
                   6087:                      allowfrom => 1,
                   6088:                      denyfrom  => 0,
                   6089:                  );
                   6090:     my @allows;
                   6091:     my @denies;
                   6092:     foreach my $item (split(',',$acc)) {
                   6093:         $item =~ s/^\s*//;
                   6094:         $item =~ s/\s*$//;
                   6095:         my $pattern;
                   6096:         if ($item =~ /^\!(.+)$/) {
                   6097:             push(@denies,$1);
                   6098:         } else {
                   6099:             push(@allows,$item);
                   6100:         }
                   6101:    }
                   6102:    my $numdenies = scalar(@denies);
                   6103:    my $numallows = scalar(@allows);
                   6104:    my $count = 0;
                   6105:    foreach my $pattern (@denies,@allows) {
                   6106:         $count ++; 
                   6107:         my $acctype = 'allowfrom';
                   6108:         if ($count <= $numdenies) {
                   6109:             $acctype = 'denyfrom';
                   6110:         }
1.682     raeburn  6111:         if ($pattern =~ /\*$/) {
                   6112:             #35.8.*
                   6113:             $pattern=~s/\*//;
1.1219    raeburn  6114:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6115:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   6116:             #35.8.3.[34-56]
                   6117:             my $low=$2;
                   6118:             my $high=$3;
                   6119:             $pattern=$1;
                   6120:             if ($ip =~ /^\Q$pattern\E/) {
                   6121:                 my $last=(split(/\./,$ip))[3];
1.1219    raeburn  6122:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
1.682     raeburn  6123:             }
                   6124:         } elsif ($pattern =~ /^\*/) {
                   6125:             #*.msu.edu
                   6126:             $pattern=~s/\*//;
                   6127:             if (!defined($name)) {
                   6128:                 use Socket;
                   6129:                 my $netaddr=inet_aton($ip);
                   6130:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6131:             }
1.1219    raeburn  6132:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
1.682     raeburn  6133:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   6134:             #127.0.0.1
1.1219    raeburn  6135:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
1.682     raeburn  6136:         } else {
                   6137:             #some.name.com
                   6138:             if (!defined($name)) {
                   6139:                 use Socket;
                   6140:                 my $netaddr=inet_aton($ip);
                   6141:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   6142:             }
1.1219    raeburn  6143:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
                   6144:         }
                   6145:         if ($allowed =~ /^(0|1)$/) { last; }
                   6146:     }
                   6147:     if ($allowed eq '') {
                   6148:         if ($numdenies && !$numallows) {
                   6149:             $allowed = 1;
                   6150:         } else {
                   6151:             $allowed = 0;
1.682     raeburn  6152:         }
                   6153:     }
                   6154:     return $allowed;
                   6155: }
                   6156: 
                   6157: ###############################################
                   6158: 
1.60      matthew  6159: =pod
                   6160: 
1.112     bowersj2 6161: =head1 Domain Template Functions
                   6162: 
                   6163: =over 4
                   6164: 
                   6165: =item * &determinedomain()
1.60      matthew  6166: 
                   6167: Inputs: $domain (usually will be undef)
                   6168: 
1.63      www      6169: Returns: Determines which domain should be used for designs
1.60      matthew  6170: 
                   6171: =cut
1.54      www      6172: 
1.60      matthew  6173: ###############################################
1.63      www      6174: sub determinedomain {
                   6175:     my $domain=shift;
1.531     albertel 6176:     if (! $domain) {
1.60      matthew  6177:         # Determine domain if we have not been given one
1.893     raeburn  6178:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 6179:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   6180:         if ($env{'request.role.domain'}) { 
                   6181:             $domain=$env{'request.role.domain'}; 
1.60      matthew  6182:         }
                   6183:     }
1.63      www      6184:     return $domain;
                   6185: }
                   6186: ###############################################
1.517     raeburn  6187: 
1.518     albertel 6188: sub devalidate_domconfig_cache {
                   6189:     my ($udom)=@_;
                   6190:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   6191: }
                   6192: 
                   6193: # ---------------------- Get domain configuration for a domain
                   6194: sub get_domainconf {
                   6195:     my ($udom) = @_;
                   6196:     my $cachetime=1800;
                   6197:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   6198:     if (defined($cached)) { return %{$result}; }
                   6199: 
                   6200:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  6201: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  6202:     my (%designhash,%legacy);
1.518     albertel 6203:     if (keys(%domconfig) > 0) {
                   6204:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  6205:             if (keys(%{$domconfig{'login'}})) {
                   6206:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  6207:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  6208:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   6209:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6210:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   6211:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   6212:                                         if ($key eq 'loginvia') {
                   6213:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   6214:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   6215:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   6216:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   6217: 
                   6218:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   6219:                                                 } else {
                   6220:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   6221:                                                 }
1.948     raeburn  6222:                                             }
1.1208    raeburn  6223:                                         } elsif ($key eq 'headtag') {
                   6224:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   6225:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  6226:                                             }
1.946     raeburn  6227:                                         }
1.1208    raeburn  6228:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   6229:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   6230:                                         }
1.946     raeburn  6231:                                     }
                   6232:                                 }
                   6233:                             }
1.1366    raeburn  6234:                         } elsif ($key eq 'saml') {
                   6235:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   6236:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
                   6237:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
                   6238:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
1.1386    raeburn  6239:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
1.1366    raeburn  6240:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
                   6241:                                         }
                   6242:                                     }
                   6243:                                 }
                   6244:                             }
1.946     raeburn  6245:                         } else {
                   6246:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   6247:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   6248:                                     $domconfig{'login'}{$key}{$img};
                   6249:                             }
1.699     raeburn  6250:                         }
                   6251:                     } else {
                   6252:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   6253:                     }
1.632     raeburn  6254:                 }
                   6255:             } else {
                   6256:                 $legacy{'login'} = 1;
1.518     albertel 6257:             }
1.632     raeburn  6258:         } else {
                   6259:             $legacy{'login'} = 1;
1.518     albertel 6260:         }
                   6261:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  6262:             if (keys(%{$domconfig{'rolecolors'}})) {
                   6263:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   6264:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   6265:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   6266:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   6267:                         }
1.518     albertel 6268:                     }
                   6269:                 }
1.632     raeburn  6270:             } else {
                   6271:                 $legacy{'rolecolors'} = 1;
1.518     albertel 6272:             }
1.632     raeburn  6273:         } else {
                   6274:             $legacy{'rolecolors'} = 1;
1.518     albertel 6275:         }
1.948     raeburn  6276:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6277:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   6278:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   6279:             }
                   6280:         }
1.632     raeburn  6281:         if (keys(%legacy) > 0) {
                   6282:             my %legacyhash = &get_legacy_domconf($udom);
                   6283:             foreach my $item (keys(%legacyhash)) {
                   6284:                 if ($item =~ /^\Q$udom\E\.login/) {
                   6285:                     if ($legacy{'login'}) { 
                   6286:                         $designhash{$item} = $legacyhash{$item};
                   6287:                     }
                   6288:                 } else {
                   6289:                     if ($legacy{'rolecolors'}) {
                   6290:                         $designhash{$item} = $legacyhash{$item};
                   6291:                     }
1.518     albertel 6292:                 }
                   6293:             }
                   6294:         }
1.632     raeburn  6295:     } else {
                   6296:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 6297:     }
                   6298:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   6299: 				  $cachetime);
                   6300:     return %designhash;
                   6301: }
                   6302: 
1.632     raeburn  6303: sub get_legacy_domconf {
                   6304:     my ($udom) = @_;
                   6305:     my %legacyhash;
                   6306:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   6307:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   6308:     if (-e $designfile) {
1.1317    raeburn  6309:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  6310:             while (my $line = <$fh>) {
                   6311:                 next if ($line =~ /^\#/);
                   6312:                 chomp($line);
                   6313:                 my ($key,$val)=(split(/\=/,$line));
                   6314:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   6315:             }
                   6316:             close($fh);
                   6317:         }
                   6318:     }
1.1026    raeburn  6319:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  6320:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   6321:     }
                   6322:     return %legacyhash;
                   6323: }
                   6324: 
1.63      www      6325: =pod
                   6326: 
1.112     bowersj2 6327: =item * &domainlogo()
1.63      www      6328: 
                   6329: Inputs: $domain (usually will be undef)
                   6330: 
                   6331: Returns: A link to a domain logo, if the domain logo exists.
                   6332: If the domain logo does not exist, a description of the domain.
                   6333: 
                   6334: =cut
1.112     bowersj2 6335: 
1.63      www      6336: ###############################################
                   6337: sub domainlogo {
1.517     raeburn  6338:     my $domain = &determinedomain(shift);
1.518     albertel 6339:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  6340:     # See if there is a logo
                   6341:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  6342:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 6343:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   6344: 	    if ($imgsrc =~ m{^/res/}) {
                   6345: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   6346: 		&Apache::lonnet::repcopy($local_name);
                   6347: 	    }
                   6348: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.1374    raeburn  6349:         }
                   6350:         my $alttext = $domain;
                   6351:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
                   6352:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
                   6353:         }
                   6354:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
1.514     albertel 6355:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   6356:         return &Apache::lonnet::domain($domain,'description');
1.59      www      6357:     } else {
1.60      matthew  6358:         return '';
1.59      www      6359:     }
                   6360: }
1.63      www      6361: ##############################################
                   6362: 
                   6363: =pod
                   6364: 
1.112     bowersj2 6365: =item * &designparm()
1.63      www      6366: 
                   6367: Inputs: $which parameter; $domain (usually will be undef)
                   6368: 
                   6369: Returns: value of designparamter $which
                   6370: 
                   6371: =cut
1.112     bowersj2 6372: 
1.397     albertel 6373: 
1.400     albertel 6374: ##############################################
1.397     albertel 6375: sub designparm {
                   6376:     my ($which,$domain)=@_;
                   6377:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   6378:         return $env{'environment.color.'.$which};
1.96      www      6379:     }
1.63      www      6380:     $domain=&determinedomain($domain);
1.1016    raeburn  6381:     my %domdesign;
                   6382:     unless ($domain eq 'public') {
                   6383:         %domdesign = &get_domainconf($domain);
                   6384:     }
1.520     raeburn  6385:     my $output;
1.517     raeburn  6386:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   6387:         $output = $domdesign{$domain.'.'.$which};
1.63      www      6388:     } else {
1.520     raeburn  6389:         $output = $defaultdesign{$which};
                   6390:     }
                   6391:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  6392:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 6393:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   6394:             if ($output =~ m{^/res/}) {
                   6395:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   6396:                 &Apache::lonnet::repcopy($local_name);
                   6397:             }
1.520     raeburn  6398:             $output = &lonhttpdurl($output);
                   6399:         }
1.63      www      6400:     }
1.520     raeburn  6401:     return $output;
1.63      www      6402: }
1.59      www      6403: 
1.822     bisitz   6404: ##############################################
                   6405: =pod
                   6406: 
1.832     bisitz   6407: =item * &authorspace()
                   6408: 
1.1028    raeburn  6409: Inputs: $url (usually will be undef).
1.832     bisitz   6410: 
1.1132    raeburn  6411: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  6412:          directory being viewed (or for which action is being taken). 
                   6413:          If $url is provided, and begins /priv/<domain>/<uname>
                   6414:          the path will be that portion of the $context argument.
                   6415:          Otherwise the path will be for the author space of the current
                   6416:          user when the current role is author, or for that of the 
                   6417:          co-author/assistant co-author space when the current role 
                   6418:          is co-author or assistant co-author.
1.832     bisitz   6419: 
                   6420: =cut
                   6421: 
                   6422: sub authorspace {
1.1028    raeburn  6423:     my ($url) = @_;
                   6424:     if ($url ne '') {
                   6425:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   6426:            return $1;
                   6427:         }
                   6428:     }
1.832     bisitz   6429:     my $caname = '';
1.1024    www      6430:     my $cadom = '';
1.1028    raeburn  6431:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      6432:         ($cadom,$caname) =
1.832     bisitz   6433:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  6434:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   6435:         $caname = $env{'user.name'};
1.1024    www      6436:         $cadom = $env{'user.domain'};
1.832     bisitz   6437:     }
1.1028    raeburn  6438:     if (($caname ne '') && ($cadom ne '')) {
                   6439:         return "/priv/$cadom/$caname/";
                   6440:     }
                   6441:     return;
1.832     bisitz   6442: }
                   6443: 
                   6444: ##############################################
                   6445: =pod
                   6446: 
1.822     bisitz   6447: =item * &head_subbox()
                   6448: 
                   6449: Inputs: $content (contains HTML code with page functions, etc.)
                   6450: 
                   6451: Returns: HTML div with $content
                   6452:          To be included in page header
                   6453: 
                   6454: =cut
                   6455: 
                   6456: sub head_subbox {
                   6457:     my ($content)=@_;
                   6458:     my $output =
1.993     raeburn  6459:         '<div class="LC_head_subbox">'
1.822     bisitz   6460:        .$content
                   6461:        .'</div>'
                   6462: }
                   6463: 
                   6464: ##############################################
                   6465: =pod
                   6466: 
                   6467: =item * &CSTR_pageheader()
                   6468: 
1.1026    raeburn  6469: Input: (optional) filename from which breadcrumb trail is built.
                   6470:        In most cases no input as needed, as $env{'request.filename'}
                   6471:        is appropriate for use in building the breadcrumb trail.
1.1379    raeburn  6472:        frameset flag
                   6473:        If page header is being requested for use in a frameset, then
                   6474:        the second (option) argument -- frameset will be true, and
                   6475:        the target attribute set for links should be target="_parent".
1.1407    raeburn  6476:        If $title is supplied as the thitd arg, that will be used to 
                   6477:        the left of the breadcrumbs tail for the current path.
1.822     bisitz   6478: 
                   6479: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  6480:          To be included on Authoring Space pages
1.822     bisitz   6481: 
                   6482: =cut
                   6483: 
                   6484: sub CSTR_pageheader {
1.1407    raeburn  6485:     my ($trailfile,$frameset,$title) = @_;
1.1026    raeburn  6486:     if ($trailfile eq '') {
                   6487:         $trailfile = $env{'request.filename'};
                   6488:     }
                   6489: 
                   6490: # this is for resources; directories have customtitle, and crumbs
                   6491: # and select recent are created in lonpubdir.pm
                   6492: 
                   6493:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      6494:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  6495:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  6496:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   6497:     $formaction =~ s{/+}{/}g;
1.822     bisitz   6498: 
                   6499:     my $parentpath = '';
                   6500:     my $lastitem = '';
                   6501:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   6502:         $parentpath = $1;
                   6503:         $lastitem = $2;
                   6504:     } else {
                   6505:         $lastitem = $thisdisfn;
                   6506:     }
1.921     bisitz   6507: 
1.1406    raeburn  6508:     my $crsauthor;
1.1246    raeburn  6509:     if (($env{'request.course.id'}) &&
                   6510:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
1.1247    raeburn  6511:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
1.1246    raeburn  6512:         $crsauthor = 1;
1.1406    raeburn  6513:         if ($title eq '') {
                   6514:             $title = &mt('Course Authoring Space');
                   6515:         }
                   6516:     } elsif ($title eq '') {
1.1246    raeburn  6517:         $title = &mt('Authoring Space');
                   6518:     }
                   6519: 
1.1379    raeburn  6520:     my ($target,$crumbtarget) = (' target="_top"','_top');
                   6521:     if ($frameset) {
                   6522:         $target = ' target="_parent"';
                   6523:         $crumbtarget = '_parent';
                   6524:     } elsif (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
1.1314    raeburn  6525:         $target = '';
                   6526:         $crumbtarget = '';
1.1379    raeburn  6527:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
1.1378    raeburn  6528:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
                   6529:         $crumbtarget = $env{'request.deeplink.target'};
                   6530:     }
1.1313    raeburn  6531: 
1.921     bisitz   6532:     my $output =
1.1407    raeburn  6533:          '<div>'
1.822     bisitz   6534:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1246    raeburn  6535:         .'<b>'.$title.'</b> '
1.1314    raeburn  6536:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
                   6537:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
1.921     bisitz   6538: 
                   6539:     if ($lastitem) {
                   6540:         $output .=
                   6541:              '<span class="LC_filename">'
                   6542:             .$lastitem
                   6543:             .'</span>';
                   6544:     }
1.1245    raeburn  6545: 
1.1246    raeburn  6546:     if ($crsauthor) {
1.1379    raeburn  6547:         $output .= '</form>'.&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6548:     } else {
                   6549:         $output .=
                   6550:              '<br />'
1.1314    raeburn  6551:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
1.1246    raeburn  6552:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   6553:             .'</form>'
1.1379    raeburn  6554:             .&Apache::lonmenu::constspaceform($frameset);
1.1246    raeburn  6555:     }
1.1407    raeburn  6556:     $output .= '</div>';
1.921     bisitz   6557: 
                   6558:     return $output;
1.822     bisitz   6559: }
                   6560: 
1.1419    raeburn  6561: ##############################################
                   6562: =pod
                   6563: 
                   6564: =item * &nocodemirror()
                   6565: 
                   6566: Input: None
                   6567: 
                   6568: Returns: 1 if CodeMirror is deactivated based on
                   6569:          user's preference, or domain default,
                   6570:          if user indicated use of default.
                   6571: 
                   6572: =cut
                   6573: 
1.1416    raeburn  6574: sub nocodemirror {
                   6575:     my $nocodem = $env{'environment.nocodemirror'};
                   6576:     unless ($nocodem) {
                   6577:         my %domdefs = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   6578:         if ($domdefs{'nocodemirror'}) {
                   6579:             $nocodem = 'yes';
                   6580:         }
                   6581:     }
1.1417    raeburn  6582:     if ($nocodem eq 'yes') {
                   6583:         return 1;
                   6584:     }
                   6585:     return;
1.1416    raeburn  6586: }
                   6587: 
1.1419    raeburn  6588: ##############################################
                   6589: =pod
                   6590: 
                   6591: =item * &permitted_editors()
                   6592: 
1.1422    raeburn  6593: Input: $uri (optional)
1.1419    raeburn  6594: 
                   6595: Returns: %editors hash in which keys are editors
                   6596:          permitted in current Authoring Space.
                   6597:          Value for each key is 1. Possible keys
                   6598:          are: edit, xml, and daxe. If no specific
                   6599:          set of editors has been set for the Author
                   6600:          who owns the Authoring Space, then the
                   6601:          domain default will be used.  If no domain
                   6602:          default has been set, then the keys will be
                   6603:          edit and xml.
                   6604: 
                   6605: =cut
                   6606: 
1.1418    raeburn  6607: sub permitted_editors {
1.1422    raeburn  6608:     my ($uri) = @_;
1.1418    raeburn  6609:     my ($is_author,$is_coauthor,$auname,$audom,%editors);
                   6610:     if ($env{'request.role'} =~ m{^au\./}) {
                   6611:         $is_author = 1;
                   6612:     } elsif ($env{'request.role'} =~ m{^(?:ca|aa)\./($match_domain)/($match_username)}) {
                   6613:         ($audom,$auname) = ($1,$2);
                   6614:         if (($audom ne '') && ($auname ne '')) {
                   6615:             if (($env{'user.domain'} eq $audom) &&
                   6616:                 ($env{'user.name'} eq $auname)) {
                   6617:                 $is_author = 1;
                   6618:             } else {
                   6619:                 $is_coauthor = 1;
                   6620:             }
                   6621:         }
                   6622:     } elsif ($env{'request.course.id'}) {
                   6623:         if ($env{'request.editurl'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6624:             ($audom,$auname) = ($1,$2);
                   6625:         } elsif ($env{'request.uri'} =~ m{^/priv/($match_domain)/($match_username)/}) {
                   6626:             ($audom,$auname) = ($1,$2);
1.1422    raeburn  6627:         } elsif (($uri eq '/daxesave') &&
                   6628:                  ($env{'form.path'} =~ m{^/daxeopen/priv/($match_domain)/($match_username)/})) {
                   6629:             ($audom,$auname) = ($1,$2);
1.1418    raeburn  6630:         }
                   6631:         if (($audom ne '') && ($auname ne '')) {
                   6632:             if (($env{'user.domain'} eq $audom) &&
                   6633:                 ($env{'user.name'} eq $auname)) {
                   6634:                 $is_author = 1;
                   6635:             } else {
                   6636:                 $is_coauthor = 1;
                   6637:             }
                   6638:         }
                   6639:     }
                   6640:     if ($is_author) {
                   6641:         if (exists($env{'environment.editors'})) {
                   6642:             map { $editors{$_} = 1; } split(/,/,$env{'environment.editors'});
                   6643:         } else {
                   6644:             %editors = ( edit => 1,
                   6645:                          xml => 1,
                   6646:                        );
                   6647:         }
                   6648:     } elsif ($is_coauthor) {
                   6649:         if (exists($env{"environment.internal.editors./$audom/$auname"})) {
                   6650:             map { $editors{$_} = 1; } split(/,/,$env{"environment.internal.editors./$audom/$auname"});
                   6651:         } else {
                   6652:             %editors = ( edit => 1,
                   6653:                          xml => 1,
                   6654:                        );
                   6655:         }
                   6656:     } else {
                   6657:         %editors = ( edit => 1,
                   6658:                      xml => 1,
                   6659:                    );
                   6660:     }
                   6661:     return %editors;
                   6662: }
                   6663: 
1.60      matthew  6664: ###############################################
                   6665: ###############################################
                   6666: 
                   6667: =pod
                   6668: 
1.112     bowersj2 6669: =back
                   6670: 
1.549     albertel 6671: =head1 HTML Helpers
1.112     bowersj2 6672: 
                   6673: =over 4
                   6674: 
                   6675: =item * &bodytag()
1.60      matthew  6676: 
                   6677: Returns a uniform header for LON-CAPA web pages.
                   6678: 
                   6679: Inputs: 
                   6680: 
1.112     bowersj2 6681: =over 4
                   6682: 
                   6683: =item * $title, A title to be displayed on the page.
                   6684: 
                   6685: =item * $function, the current role (can be undef).
                   6686: 
                   6687: =item * $addentries, extra parameters for the <body> tag.
                   6688: 
                   6689: =item * $bodyonly, if defined, only return the <body> tag.
                   6690: 
                   6691: =item * $domain, if defined, force a given domain.
                   6692: 
                   6693: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      6694:             text interface only)
1.60      matthew  6695: 
1.814     bisitz   6696: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   6697:                      navigational links
1.317     albertel 6698: 
1.338     albertel 6699: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   6700: 
1.460     albertel 6701: =item * $args, optional argument valid values are
                   6702:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1274    raeburn  6703:             use_absolute     -> for external resource or syllabus, this will
                   6704:                                 contain https://<hostname> if server uses
                   6705:                                 https (as per hosts.tab), but request is for http
                   6706:             hostname         -> hostname, from $r->hostname().
1.460     albertel 6707: 
1.1096    raeburn  6708: =item * $advtoolsref, optional argument, ref to an array containing
                   6709:             inlineremote items to be added in "Functions" menu below
                   6710:             breadcrumbs.
                   6711: 
1.1316    raeburn  6712: =item * $ltiscope, optional argument, will be one of: resource, map or
                   6713:             course, if LON-CAPA is in LTI Provider context. Value is
                   6714:             the scope of use, i.e., launch was for access to a single, a map
                   6715:             or the entire course.
                   6716: 
                   6717: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
                   6718:             context, this will contain the URL for the landing item in
                   6719:             the course, after launch from an LTI Consumer
                   6720: 
1.1318    raeburn  6721: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
                   6722:             context, this will contain a reference to hash of items
                   6723:             to be included in the page header and/or inline menu.
                   6724: 
1.1385    raeburn  6725: =item * $menucoll, optional argument, if specific menu collection is in
                   6726:             effect, either set as the default for the course, or set for
                   6727:             the deeplink paramater for $env{'request.deeplink.login'}
                   6728:             then $menucoll will be the number of that collection. 
                   6729: 
                   6730: =item * $menuref, optional argument, reference to a hash, containing the
                   6731:             menu options included for the menu in effect, based on the
                   6732:             configuration for the numbered menu collection in use.  
                   6733: 
                   6734: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
                   6735:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
                   6736:             if so, $showncrumbsref is set there to 1, and will propagate back
                   6737:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
                   6738:             being called a second time.
                   6739: 
1.112     bowersj2 6740: =back
                   6741: 
1.60      matthew  6742: Returns: A uniform header for LON-CAPA web pages.  
                   6743: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   6744: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   6745: other decorations will be returned.
                   6746: 
                   6747: =cut
                   6748: 
1.54      www      6749: sub bodytag {
1.831     bisitz   6750:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1359    raeburn  6751:         $no_nav_bar,$bgcolor,$args,$advtoolsref,$ltiscope,$ltiuri,
1.1385    raeburn  6752:         $ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
1.339     albertel 6753: 
1.954     raeburn  6754:     my $public;
                   6755:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   6756:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   6757:         $public = 1;
                   6758:     }
1.460     albertel 6759:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  6760:     my $httphost = $args->{'use_absolute'};
1.1274    raeburn  6761:     my $hostname = $args->{'hostname'};
1.339     albertel 6762: 
1.183     matthew  6763:     $function = &get_users_function() if (!$function);
1.339     albertel 6764:     my $img =    &designparm($function.'.img',$domain);
                   6765:     my $font =   &designparm($function.'.font',$domain);
                   6766:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   6767: 
1.803     bisitz   6768:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 6769: 		   'bgcolor' => $pgbg,
1.339     albertel 6770: 		   'text'    => $font,
                   6771:                    'alink'   => &designparm($function.'.alink',$domain),
                   6772: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   6773: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 6774:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 6775: 
1.63      www      6776:  # role and realm
1.1178    raeburn  6777:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   6778:     if ($realm) {
                   6779:         $realm = '/'.$realm;
                   6780:     }
1.1357    raeburn  6781:     if ($role eq 'ca') {
1.479     albertel 6782:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 6783:         $realm = &plainname($rname,$rdom);
1.378     raeburn  6784:     } 
1.55      www      6785: # realm
1.1357    raeburn  6786:     my ($cid,$sec);
1.258     albertel 6787:     if ($env{'request.course.id'}) {
1.1357    raeburn  6788:         $cid = $env{'request.course.id'};
                   6789:         if ($env{'request.course.sec'}) {
                   6790:             $sec = $env{'request.course.sec'};
                   6791:         }
                   6792:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
                   6793:         if (&Apache::lonnet::is_course($1,$2)) {
                   6794:             $cid = $1.'_'.$2;
                   6795:             $sec = $3;
                   6796:         }
                   6797:     }
                   6798:     if ($cid) {
1.378     raeburn  6799:         if ($env{'request.role'} !~ /^cr/) {
                   6800:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1257    raeburn  6801:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1269    raeburn  6802:             if ($env{'request.role.desc'}) {
                   6803:                 $role = $env{'request.role.desc'};
                   6804:             } else {
                   6805:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   6806:             }
1.1257    raeburn  6807:         } else {
                   6808:             $role = (split(/\//,$role,4))[-1]; 
1.378     raeburn  6809:         }
1.1357    raeburn  6810:         if ($sec) {
                   6811:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
1.898     raeburn  6812:         }   
1.1357    raeburn  6813: 	$realm = $env{'course.'.$cid.'.description'};
1.378     raeburn  6814:     } else {
                   6815:         $role = &Apache::lonnet::plaintext($role);
1.54      www      6816:     }
1.433     albertel 6817: 
1.359     albertel 6818:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 6819: 
1.438     albertel 6820:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 6821: 
1.101     www      6822: # construct main body tag
1.359     albertel 6823:     my $bodytag = "<body $extra_body_attr>".
1.1235    raeburn  6824: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 6825: 
1.1131    raeburn  6826:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   6827: 
1.1130    raeburn  6828:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  6829:         return $bodytag;
1.1130    raeburn  6830:     }
1.359     albertel 6831: 
1.954     raeburn  6832:     if ($public) {
1.433     albertel 6833: 	undef($role);
                   6834:     }
1.1318    raeburn  6835: 
1.1359    raeburn  6836:     my $showcrstitle = 1;
1.1357    raeburn  6837:     if (($cid) && ($env{'request.lti.login'})) {
1.1318    raeburn  6838:         if (ref($ltimenu) eq 'HASH') {
                   6839:             unless ($ltimenu->{'role'}) {
                   6840:                 undef($role);
                   6841:             }
                   6842:             unless ($ltimenu->{'coursetitle'}) {
                   6843:                 $realm='&nbsp;';
1.1359    raeburn  6844:                 $showcrstitle = 0;
                   6845:             }
                   6846:         }
                   6847:     } elsif (($cid) && ($menucoll)) {
                   6848:         if (ref($menuref) eq 'HASH') {
                   6849:             unless ($menuref->{'role'}) {
                   6850:                 undef($role);
                   6851:             }
                   6852:             unless ($menuref->{'crs'}) {
                   6853:                 $realm='&nbsp;';
                   6854:                 $showcrstitle = 0;
1.1318    raeburn  6855:             }
                   6856:         }
                   6857:     }
                   6858: 
1.762     bisitz   6859:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 6860:     #
                   6861:     # Extra info if you are the DC
                   6862:     my $dc_info = '';
1.1359    raeburn  6863:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
1.1357    raeburn  6864:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
1.917     raeburn  6865:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      6866:         $dc_info =~ s/\s+$//;
1.359     albertel 6867:     }
                   6868: 
1.1237    raeburn  6869:     my $crstype;
1.1357    raeburn  6870:     if ($cid) {
                   6871:         $crstype = $env{'course.'.$cid.'.type'};
1.1237    raeburn  6872:     } elsif ($args->{'crstype'}) {
                   6873:         $crstype = $args->{'crstype'};
                   6874:     }
                   6875:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
                   6876:         undef($role);
                   6877:     } else {
1.1242    raeburn  6878:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.1237    raeburn  6879:     }
1.853     droeschl 6880: 
1.903     droeschl 6881:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   6882: 
                   6883:         #    if ($env{'request.state'} eq 'construct') {
                   6884:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   6885:         #    }
                   6886: 
1.1130    raeburn  6887:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  6888:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 6889: 
1.1423    raeburn  6890:         if ($args->{'collapsible_header'} ne '') {
1.1421    raeburn  6891:             my $alttext = &mt('menu state: collapsed');
                   6892:             my $tooltip = &mt('display standard menus');
                   6893:             $bodytag .= <<"END";
                   6894: <div id="LC_expandingContainer" style="display:inline;">
                   6895: <div id="LC_collapsible" class="LC_collapse_trigger" style="position: absolute;top: -5px;left: 0px; z-index:101; display:inline;">
                   6896: <a href="#" style="text-decoration:none;"><img class="LC_collapsible_indicator" alt="$alttext" title="$tooltip" src="/res/adm/pages/collapsed.png" style="border:0;margin:0;padding:0;max-width:100%;height:auto" /></a></div>
                   6897: <div class="LC_menus_content hidden">
                   6898: END
                   6899:         }
1.1318    raeburn  6900:         unless ($args->{'no_primary_menu'}) {
1.1369    raeburn  6901:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
1.1380    raeburn  6902:                                                               $args->{'links_disabled'},
1.1421    raeburn  6903:                                                               $args->{'links_target'},
                   6904:                                                               $args->{'collapsible_header'});
1.359     albertel 6905: 
1.1318    raeburn  6906:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
                   6907:                 if ($dc_info) {
                   6908:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   6909:                 }
                   6910:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
                   6911:                                <em>$realm</em> $dc_info</div>|;
                   6912:                 return $bodytag;
                   6913:             }
1.894     droeschl 6914: 
1.1318    raeburn  6915:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   6916:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
                   6917:             }
1.916     droeschl 6918: 
1.1318    raeburn  6919:             $bodytag .= $right;
1.852     droeschl 6920: 
1.1318    raeburn  6921:             if ($dc_info) {
                   6922:                 $dc_info = &dc_courseid_toggle($dc_info);
                   6923:             }
                   6924:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.917     raeburn  6925:         }
1.916     droeschl 6926: 
1.1169    raeburn  6927:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  6928:         if ($args->{'no_secondary_menu'}) {
                   6929:             return $bodytag;
                   6930:         }
1.1169    raeburn  6931:         #don't show menus for public users
1.954     raeburn  6932:         if (!$public){
1.1318    raeburn  6933:             unless ($args->{'no_inline_menu'}) {
                   6934:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
1.1359    raeburn  6935:                                                             $args->{'no_primary_menu'},
1.1369    raeburn  6936:                                                             $menucoll,$menuref,
1.1380    raeburn  6937:                                                             $args->{'links_disabled'},
                   6938:                                                             $args->{'links_target'});
1.1318    raeburn  6939:             }
1.903     droeschl 6940:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  6941:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   6942:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 6943:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1385    raeburn  6944:                                 $args->{'bread_crumbs'},'','',$hostname,
                   6945:                                 $ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6946:             } elsif ($forcereg) {
                   6947:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1385    raeburn  6948:                                 $args->{'group'},$args->{'hide_buttons'},
                   6949:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
1.1096    raeburn  6950:             } else {
                   6951:                 $bodytag .= 
                   6952:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   6953:                                                         $forcereg,$args->{'group'},
                   6954:                                                         $args->{'bread_crumbs'},
1.1274    raeburn  6955:                                                         $advtoolsref,'',$hostname);
1.920     raeburn  6956:             }
1.903     droeschl 6957:         }else{
                   6958:             # this is to seperate menu from content when there's no secondary
                   6959:             # menu. Especially needed for public accessible ressources.
                   6960:             $bodytag .= '<hr style="clear:both" />';
                   6961:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  6962:         }
1.1423    raeburn  6963:         if ($args->{'collapsible_header'} ne '') {
                   6964:             $bodytag .= $args->{'collapsible_header'}.
                   6965:                         '<div id="LC_collapsible_separator"></div>'.
1.1421    raeburn  6966:                         '</div></div>';
                   6967:         }
1.235     raeburn  6968:         return $bodytag;
1.182     matthew  6969: }
                   6970: 
1.917     raeburn  6971: sub dc_courseid_toggle {
                   6972:     my ($dc_info) = @_;
1.980     raeburn  6973:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  6974:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  6975:            &mt('(More ...)').'</a></span>'.
                   6976:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   6977: }
                   6978: 
1.330     albertel 6979: sub make_attr_string {
                   6980:     my ($register,$attr_ref) = @_;
                   6981: 
                   6982:     if ($attr_ref && !ref($attr_ref)) {
                   6983: 	die("addentries Must be a hash ref ".
                   6984: 	    join(':',caller(1))." ".
                   6985: 	    join(':',caller(0))." ");
                   6986:     }
                   6987: 
                   6988:     if ($register) {
1.339     albertel 6989: 	my ($on_load,$on_unload);
                   6990: 	foreach my $key (keys(%{$attr_ref})) {
                   6991: 	    if      (lc($key) eq 'onload') {
                   6992: 		$on_load.=$attr_ref->{$key}.';';
                   6993: 		delete($attr_ref->{$key});
                   6994: 
                   6995: 	    } elsif (lc($key) eq 'onunload') {
                   6996: 		$on_unload.=$attr_ref->{$key}.';';
                   6997: 		delete($attr_ref->{$key});
                   6998: 	    }
                   6999: 	}
1.953     droeschl 7000: 	$attr_ref->{'onload'}  = $on_load;
                   7001: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 7002:     }
1.339     albertel 7003: 
1.330     albertel 7004:     my $attr_string;
1.1159    raeburn  7005:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 7006: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   7007:     }
                   7008:     return $attr_string;
                   7009: }
                   7010: 
                   7011: 
1.182     matthew  7012: ###############################################
1.251     albertel 7013: ###############################################
                   7014: 
                   7015: =pod
                   7016: 
                   7017: =item * &endbodytag()
                   7018: 
                   7019: Returns a uniform footer for LON-CAPA web pages.
                   7020: 
1.635     raeburn  7021: Inputs: 1 - optional reference to an args hash
                   7022: If in the hash, key for noredirectlink has a value which evaluates to true,
                   7023: a 'Continue' link is not displayed if the page contains an
                   7024: internal redirect in the <head></head> section,
                   7025: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 7026: 
                   7027: =cut
                   7028: 
                   7029: sub endbodytag {
1.635     raeburn  7030:     my ($args) = @_;
1.1080    raeburn  7031:     my $endbodytag;
                   7032:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   7033:         $endbodytag='</body>';
                   7034:     }
1.315     albertel 7035:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  7036:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
1.1386    raeburn  7037:             my ($endbodyjs,$idattr);
                   7038:             if ($env{'internal.head.to_opener'}) {
                   7039:                 my $linkid = 'LC_continue_link';
                   7040:                 $idattr = ' id="'.$linkid.'"';
                   7041:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
                   7042:                 $endbodyjs=<<ENDJS;
                   7043: <script type="text/javascript">
                   7044: // <![CDATA[
                   7045: function ebFunction(evt) {
                   7046:     evt.preventDefault();
                   7047:     var dest = '$redirect_for_js';
                   7048:     if (window.opener != null && !window.opener.closed) {
                   7049:         window.opener.location.href=dest;
                   7050:         window.close();
                   7051:     } else {
                   7052:         window.location.href=dest;
                   7053:     }
                   7054:     return false;
                   7055: }
                   7056: 
                   7057: \$(document).ready(function () {
                   7058:   if (document.getElementById('$linkid')) {
                   7059:     var clickelem = document.getElementById('$linkid');
                   7060:     clickelem.addEventListener('click',ebFunction,false);
                   7061:   }
                   7062: });
                   7063: // ]]>
                   7064: </script>
                   7065: ENDJS
                   7066:             }
1.635     raeburn  7067: 	    $endbodytag=
1.1386    raeburn  7068: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
1.635     raeburn  7069: 	        &mt('Continue').'</a>'.
                   7070: 	        $endbodytag;
                   7071:         }
1.315     albertel 7072:     }
1.1411    raeburn  7073:     if ((ref($args) eq 'HASH') && ($args->{'dashjs'})) {
                   7074:         $endbodytag = &Apache::lonhtmlcommon::dash_to_minus_js().$endbodytag;
                   7075:     }
1.251     albertel 7076:     return $endbodytag;
                   7077: }
                   7078: 
1.352     albertel 7079: =pod
                   7080: 
                   7081: =item * &standard_css()
                   7082: 
                   7083: Returns a style sheet
                   7084: 
                   7085: Inputs: (all optional)
                   7086:             domain         -> force to color decorate a page for a specific
                   7087:                                domain
                   7088:             function       -> force usage of a specific rolish color scheme
                   7089:             bgcolor        -> override the default page bgcolor
                   7090: 
                   7091: =cut
                   7092: 
1.343     albertel 7093: sub standard_css {
1.345     albertel 7094:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 7095:     $function  = &get_users_function() if (!$function);
                   7096:     my $img    = &designparm($function.'.img',   $domain);
                   7097:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   7098:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 7099:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 7100: #second colour for later usage
1.345     albertel 7101:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 7102:     my $pgbg_or_bgcolor =
                   7103: 	         $bgcolor ||
1.352     albertel 7104: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 7105:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 7106:     my $alink  = &designparm($function.'.alink', $domain);
                   7107:     my $vlink  = &designparm($function.'.vlink', $domain);
                   7108:     my $link   = &designparm($function.'.link',  $domain);
                   7109: 
1.602     albertel 7110:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 7111:     my $mono                 = 'monospace';
1.850     bisitz   7112:     my $data_table_head      = $sidebg;
                   7113:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   7114:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 7115:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 7116:     my $data_table_highlight = '#FFFF00';
1.352     albertel 7117:     my $mail_new             = '#FFBB77';
                   7118:     my $mail_new_hover       = '#DD9955';
                   7119:     my $mail_read            = '#BBBB77';
                   7120:     my $mail_read_hover      = '#999944';
                   7121:     my $mail_replied         = '#AAAA88';
                   7122:     my $mail_replied_hover   = '#888855';
                   7123:     my $mail_other           = '#99BBBB';
                   7124:     my $mail_other_hover     = '#669999';
1.391     albertel 7125:     my $table_header         = '#DDDDDD';
1.489     raeburn  7126:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   7127:     my $lg_border_color      = '#C8C8C8';
1.952     onken    7128:     my $button_hover         = '#BF2317';
1.392     albertel 7129: 
1.608     albertel 7130:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   7131:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   7132:                                              : '0 3px 0 4px';
1.448     albertel 7133: 
1.523     albertel 7134: 
1.343     albertel 7135:     return <<END;
1.947     droeschl 7136: 
                   7137: /* needed for iframe to allow 100% height in FF */
                   7138: body, html { 
                   7139:     margin: 0;
                   7140:     padding: 0 0.5%;
                   7141:     height: 99%; /* to avoid scrollbars */
                   7142: }
                   7143: 
1.795     www      7144: body {
1.911     bisitz   7145:   font-family: $sans;
                   7146:   line-height:130%;
                   7147:   font-size:0.83em;
                   7148:   color:$font;
1.795     www      7149: }
                   7150: 
1.959     onken    7151: a:focus,
                   7152: a:focus img {
1.795     www      7153:   color: red;
                   7154: }
1.698     harmsja  7155: 
1.911     bisitz   7156: form, .inline {
                   7157:   display: inline;
1.795     www      7158: }
1.721     harmsja  7159: 
1.1421    raeburn  7160: .LC_menus_content.shown{
                   7161:   display: inline;
                   7162: }
                   7163: 
                   7164: .LC_menus_content.hidden {
                   7165:   display: none;
                   7166: }
                   7167: 
1.795     www      7168: .LC_right {
1.911     bisitz   7169:   text-align:right;
1.795     www      7170: }
                   7171: 
                   7172: .LC_middle {
1.911     bisitz   7173:   vertical-align:middle;
1.795     www      7174: }
1.721     harmsja  7175: 
1.1130    raeburn  7176: .LC_floatleft {
                   7177:   float: left;
                   7178: }
                   7179: 
                   7180: .LC_floatright {
                   7181:   float: right;
                   7182: }
                   7183: 
1.911     bisitz   7184: .LC_400Box {
                   7185:   width:400px;
                   7186: }
1.721     harmsja  7187: 
1.1421    raeburn  7188: #LC_collapsible_separator {
                   7189:     border: 1px solid black;
                   7190:     width: 99.9%;
                   7191:     height: 0px;
                   7192: }
                   7193: 
1.947     droeschl 7194: .LC_iframecontainer {
                   7195:     width: 98%;
                   7196:     margin: 0;
                   7197:     position: fixed;
                   7198:     top: 8.5em;
                   7199:     bottom: 0;
                   7200: }
                   7201: 
                   7202: .LC_iframecontainer iframe{
                   7203:     border: none;
                   7204:     width: 100%;
                   7205:     height: 100%;
                   7206: }
                   7207: 
1.778     bisitz   7208: .LC_filename {
                   7209:   font-family: $mono;
                   7210:   white-space:pre;
1.921     bisitz   7211:   font-size: 120%;
1.778     bisitz   7212: }
                   7213: 
                   7214: .LC_fileicon {
                   7215:   border: none;
                   7216:   height: 1.3em;
                   7217:   vertical-align: text-bottom;
                   7218:   margin-right: 0.3em;
                   7219:   text-decoration:none;
                   7220: }
                   7221: 
1.1008    www      7222: .LC_setting {
                   7223:   text-decoration:underline;
                   7224: }
                   7225: 
1.350     albertel 7226: .LC_error {
                   7227:   color: red;
                   7228: }
1.795     www      7229: 
1.1097    bisitz   7230: .LC_warning {
                   7231:   color: darkorange;
                   7232: }
                   7233: 
1.457     albertel 7234: .LC_diff_removed {
1.733     bisitz   7235:   color: red;
1.394     albertel 7236: }
1.532     albertel 7237: 
                   7238: .LC_info,
1.457     albertel 7239: .LC_success,
                   7240: .LC_diff_added {
1.350     albertel 7241:   color: green;
                   7242: }
1.795     www      7243: 
1.802     bisitz   7244: div.LC_confirm_box {
                   7245:   background-color: #FAFAFA;
                   7246:   border: 1px solid $lg_border_color;
                   7247:   margin-right: 0;
                   7248:   padding: 5px;
                   7249: }
                   7250: 
                   7251: div.LC_confirm_box .LC_error img,
                   7252: div.LC_confirm_box .LC_success img {
                   7253:   vertical-align: middle;
                   7254: }
                   7255: 
1.1242    raeburn  7256: .LC_maxwidth {
                   7257:   max-width: 100%;
                   7258:   height: auto;
                   7259: }
                   7260: 
1.1243    raeburn  7261: .LC_textsize_mobile {
                   7262:   \@media only screen and (max-device-width: 480px) {
                   7263:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   7264:   }
                   7265: }
                   7266: 
1.440     albertel 7267: .LC_icon {
1.771     droeschl 7268:   border: none;
1.790     droeschl 7269:   vertical-align: middle;
1.771     droeschl 7270: }
                   7271: 
1.543     albertel 7272: .LC_docs_spacer {
                   7273:   width: 25px;
                   7274:   height: 1px;
1.771     droeschl 7275:   border: none;
1.543     albertel 7276: }
1.346     albertel 7277: 
1.532     albertel 7278: .LC_internal_info {
1.735     bisitz   7279:   color: #999999;
1.532     albertel 7280: }
                   7281: 
1.794     www      7282: .LC_discussion {
1.1050    www      7283:   background: $data_table_dark;
1.911     bisitz   7284:   border: 1px solid black;
                   7285:   margin: 2px;
1.794     www      7286: }
                   7287: 
                   7288: .LC_disc_action_left {
1.1050    www      7289:   background: $sidebg;
1.911     bisitz   7290:   text-align: left;
1.1050    www      7291:   padding: 4px;
                   7292:   margin: 2px;
1.794     www      7293: }
                   7294: 
                   7295: .LC_disc_action_right {
1.1050    www      7296:   background: $sidebg;
1.911     bisitz   7297:   text-align: right;
1.1050    www      7298:   padding: 4px;
                   7299:   margin: 2px;
1.794     www      7300: }
                   7301: 
                   7302: .LC_disc_new_item {
1.911     bisitz   7303:   background: white;
                   7304:   border: 2px solid red;
1.1050    www      7305:   margin: 4px;
                   7306:   padding: 4px;
1.794     www      7307: }
                   7308: 
                   7309: .LC_disc_old_item {
1.911     bisitz   7310:   background: white;
1.1050    www      7311:   margin: 4px;
                   7312:   padding: 4px;
1.794     www      7313: }
                   7314: 
1.458     albertel 7315: table.LC_pastsubmission {
                   7316:   border: 1px solid black;
                   7317:   margin: 2px;
                   7318: }
                   7319: 
1.924     bisitz   7320: table#LC_menubuttons {
1.345     albertel 7321:   width: 100%;
                   7322:   background: $pgbg;
1.392     albertel 7323:   border: 2px;
1.402     albertel 7324:   border-collapse: separate;
1.803     bisitz   7325:   padding: 0;
1.345     albertel 7326: }
1.392     albertel 7327: 
1.801     tempelho 7328: table#LC_title_bar a {
                   7329:   color: $fontmenu;
                   7330: }
1.836     bisitz   7331: 
1.807     droeschl 7332: table#LC_title_bar {
1.819     tempelho 7333:   clear: both;
1.836     bisitz   7334:   display: none;
1.807     droeschl 7335: }
                   7336: 
1.795     www      7337: table#LC_title_bar,
1.933     droeschl 7338: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 7339: table#LC_title_bar.LC_with_remote {
1.359     albertel 7340:   width: 100%;
1.392     albertel 7341:   border-color: $pgbg;
                   7342:   border-style: solid;
                   7343:   border-width: $border;
1.379     albertel 7344:   background: $pgbg;
1.801     tempelho 7345:   color: $fontmenu;
1.392     albertel 7346:   border-collapse: collapse;
1.803     bisitz   7347:   padding: 0;
1.819     tempelho 7348:   margin: 0;
1.359     albertel 7349: }
1.795     www      7350: 
1.933     droeschl 7351: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 7352:     margin: 0;
                   7353:     padding: 0;
1.933     droeschl 7354:     position: relative;
                   7355:     list-style: none;
1.913     droeschl 7356: }
1.933     droeschl 7357: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 7358:     display: inline;
                   7359: }
1.933     droeschl 7360: 
                   7361: .LC_breadcrumb_tools_navigation {
1.913     droeschl 7362:     padding: 0;
1.933     droeschl 7363:     margin: 0;
                   7364:     float: left;
1.913     droeschl 7365: }
1.933     droeschl 7366: .LC_breadcrumb_tools_tools {
                   7367:     padding: 0;
                   7368:     margin: 0;
1.913     droeschl 7369:     float: right;
                   7370: }
                   7371: 
1.1240    raeburn  7372: .LC_placement_prog {
                   7373:     padding-right: 20px;
                   7374:     font-weight: bold;
                   7375:     font-size: 90%;
                   7376: }
                   7377: 
1.359     albertel 7378: table#LC_title_bar td {
                   7379:   background: $tabbg;
                   7380: }
1.795     www      7381: 
1.911     bisitz   7382: table#LC_menubuttons img {
1.803     bisitz   7383:   border: none;
1.346     albertel 7384: }
1.795     www      7385: 
1.842     droeschl 7386: .LC_breadcrumbs_component {
1.911     bisitz   7387:   float: right;
                   7388:   margin: 0 1em;
1.357     albertel 7389: }
1.842     droeschl 7390: .LC_breadcrumbs_component img {
1.911     bisitz   7391:   vertical-align: middle;
1.777     tempelho 7392: }
1.795     www      7393: 
1.1243    raeburn  7394: .LC_breadcrumbs_hoverable {
                   7395:   background: $sidebg;
                   7396: }
                   7397: 
1.383     albertel 7398: td.LC_table_cell_checkbox {
                   7399:   text-align: center;
                   7400: }
1.795     www      7401: 
                   7402: .LC_fontsize_small {
1.911     bisitz   7403:   font-size: 70%;
1.705     tempelho 7404: }
                   7405: 
1.844     bisitz   7406: #LC_breadcrumbs {
1.911     bisitz   7407:   clear:both;
                   7408:   background: $sidebg;
                   7409:   border-bottom: 1px solid $lg_border_color;
                   7410:   line-height: 2.5em;
1.933     droeschl 7411:   overflow: hidden;
1.911     bisitz   7412:   margin: 0;
                   7413:   padding: 0;
1.995     raeburn  7414:   text-align: left;
1.819     tempelho 7415: }
1.862     bisitz   7416: 
1.1098    bisitz   7417: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   7418:   clear:both;
                   7419:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 7420:   border: 1px solid $sidebg;
1.1098    bisitz   7421:   margin: 0 0 10px 0;
1.966     bisitz   7422:   padding: 3px;
1.995     raeburn  7423:   text-align: left;
1.822     bisitz   7424: }
                   7425: 
1.795     www      7426: .LC_fontsize_medium {
1.911     bisitz   7427:   font-size: 85%;
1.705     tempelho 7428: }
                   7429: 
1.795     www      7430: .LC_fontsize_large {
1.911     bisitz   7431:   font-size: 120%;
1.705     tempelho 7432: }
                   7433: 
1.346     albertel 7434: .LC_menubuttons_inline_text {
                   7435:   color: $font;
1.698     harmsja  7436:   font-size: 90%;
1.701     harmsja  7437:   padding-left:3px;
1.346     albertel 7438: }
                   7439: 
1.934     droeschl 7440: .LC_menubuttons_inline_text img{
                   7441:   vertical-align: middle;
                   7442: }
                   7443: 
1.1051    www      7444: li.LC_menubuttons_inline_text img {
1.951     onken    7445:   cursor:pointer;
1.1002    droeschl 7446:   text-decoration: none;
1.951     onken    7447: }
                   7448: 
1.526     www      7449: .LC_menubuttons_link {
                   7450:   text-decoration: none;
                   7451: }
1.795     www      7452: 
1.522     albertel 7453: .LC_menubuttons_category {
1.521     www      7454:   color: $font;
1.526     www      7455:   background: $pgbg;
1.521     www      7456:   font-size: larger;
                   7457:   font-weight: bold;
                   7458: }
                   7459: 
1.346     albertel 7460: td.LC_menubuttons_text {
1.911     bisitz   7461:   color: $font;
1.346     albertel 7462: }
1.706     harmsja  7463: 
1.346     albertel 7464: .LC_current_location {
                   7465:   background: $tabbg;
                   7466: }
1.795     www      7467: 
1.1286    raeburn  7468: td.LC_zero_height {
                   7469:   line-height: 0; 
                   7470:   cellpadding: 0;
                   7471: }
                   7472: 
1.938     bisitz   7473: table.LC_data_table {
1.347     albertel 7474:   border: 1px solid #000000;
1.402     albertel 7475:   border-collapse: separate;
1.426     albertel 7476:   border-spacing: 1px;
1.610     albertel 7477:   background: $pgbg;
1.347     albertel 7478: }
1.795     www      7479: 
1.422     albertel 7480: .LC_data_table_dense {
                   7481:   font-size: small;
                   7482: }
1.795     www      7483: 
1.507     raeburn  7484: table.LC_nested_outer {
                   7485:   border: 1px solid #000000;
1.589     raeburn  7486:   border-collapse: collapse;
1.803     bisitz   7487:   border-spacing: 0;
1.507     raeburn  7488:   width: 100%;
                   7489: }
1.795     www      7490: 
1.879     raeburn  7491: table.LC_innerpickbox,
1.507     raeburn  7492: table.LC_nested {
1.803     bisitz   7493:   border: none;
1.589     raeburn  7494:   border-collapse: collapse;
1.803     bisitz   7495:   border-spacing: 0;
1.507     raeburn  7496:   width: 100%;
                   7497: }
1.795     www      7498: 
1.911     bisitz   7499: table.LC_data_table tr th,
                   7500: table.LC_calendar tr th,
1.879     raeburn  7501: table.LC_prior_tries tr th,
                   7502: table.LC_innerpickbox tr th {
1.349     albertel 7503:   font-weight: bold;
                   7504:   background-color: $data_table_head;
1.801     tempelho 7505:   color:$fontmenu;
1.701     harmsja  7506:   font-size:90%;
1.347     albertel 7507: }
1.795     www      7508: 
1.879     raeburn  7509: table.LC_innerpickbox tr th,
                   7510: table.LC_innerpickbox tr td {
                   7511:   vertical-align: top;
                   7512: }
                   7513: 
1.711     raeburn  7514: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   7515:   background-color: #CCCCCC;
1.711     raeburn  7516:   font-weight: bold;
                   7517:   text-align: left;
                   7518: }
1.795     www      7519: 
1.912     bisitz   7520: table.LC_data_table tr.LC_odd_row > td {
                   7521:   background-color: $data_table_light;
                   7522:   padding: 2px;
                   7523:   vertical-align: top;
                   7524: }
                   7525: 
1.809     bisitz   7526: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 7527:   background-color: $data_table_light;
1.912     bisitz   7528:   vertical-align: top;
                   7529: }
                   7530: 
                   7531: table.LC_data_table tr.LC_even_row > td {
                   7532:   background-color: $data_table_dark;
1.425     albertel 7533:   padding: 2px;
1.900     bisitz   7534:   vertical-align: top;
1.347     albertel 7535: }
1.795     www      7536: 
1.809     bisitz   7537: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 7538:   background-color: $data_table_dark;
1.900     bisitz   7539:   vertical-align: top;
1.347     albertel 7540: }
1.795     www      7541: 
1.425     albertel 7542: table.LC_data_table tr.LC_data_table_highlight td {
                   7543:   background-color: $data_table_darker;
                   7544: }
1.795     www      7545: 
1.639     raeburn  7546: table.LC_data_table tr td.LC_leftcol_header {
                   7547:   background-color: $data_table_head;
                   7548:   font-weight: bold;
                   7549: }
1.795     www      7550: 
1.451     albertel 7551: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  7552: table.LC_nested tr.LC_empty_row td {
1.421     albertel 7553:   font-weight: bold;
                   7554:   font-style: italic;
                   7555:   text-align: center;
                   7556:   padding: 8px;
1.347     albertel 7557: }
1.795     www      7558: 
1.1114    raeburn  7559: table.LC_data_table tr.LC_empty_row td,
                   7560: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   7561:   background-color: $sidebg;
                   7562: }
                   7563: 
                   7564: table.LC_nested tr.LC_empty_row td {
                   7565:   background-color: #FFFFFF;
                   7566: }
                   7567: 
1.890     droeschl 7568: table.LC_caption {
                   7569: }
                   7570: 
1.507     raeburn  7571: table.LC_nested tr.LC_empty_row td {
1.465     albertel 7572:   padding: 4ex
                   7573: }
1.795     www      7574: 
1.507     raeburn  7575: table.LC_nested_outer tr th {
                   7576:   font-weight: bold;
1.801     tempelho 7577:   color:$fontmenu;
1.507     raeburn  7578:   background-color: $data_table_head;
1.701     harmsja  7579:   font-size: small;
1.507     raeburn  7580:   border-bottom: 1px solid #000000;
                   7581: }
1.795     www      7582: 
1.507     raeburn  7583: table.LC_nested_outer tr td.LC_subheader {
                   7584:   background-color: $data_table_head;
                   7585:   font-weight: bold;
                   7586:   font-size: small;
                   7587:   border-bottom: 1px solid #000000;
                   7588:   text-align: right;
1.451     albertel 7589: }
1.795     www      7590: 
1.507     raeburn  7591: table.LC_nested tr.LC_info_row td {
1.735     bisitz   7592:   background-color: #CCCCCC;
1.451     albertel 7593:   font-weight: bold;
                   7594:   font-size: small;
1.507     raeburn  7595:   text-align: center;
                   7596: }
1.795     www      7597: 
1.589     raeburn  7598: table.LC_nested tr.LC_info_row td.LC_left_item,
                   7599: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  7600:   text-align: left;
1.451     albertel 7601: }
1.795     www      7602: 
1.507     raeburn  7603: table.LC_nested td {
1.735     bisitz   7604:   background-color: #FFFFFF;
1.451     albertel 7605:   font-size: small;
1.507     raeburn  7606: }
1.795     www      7607: 
1.507     raeburn  7608: table.LC_nested_outer tr th.LC_right_item,
                   7609: table.LC_nested tr.LC_info_row td.LC_right_item,
                   7610: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   7611: table.LC_nested tr td.LC_right_item {
1.451     albertel 7612:   text-align: right;
                   7613: }
                   7614: 
1.507     raeburn  7615: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   7616:   background-color: #EEEEEE;
1.451     albertel 7617: }
                   7618: 
1.473     raeburn  7619: table.LC_createuser {
                   7620: }
                   7621: 
                   7622: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  7623:   font-size: small;
1.473     raeburn  7624: }
                   7625: 
                   7626: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   7627:   background-color: #CCCCCC;
1.473     raeburn  7628:   font-weight: bold;
                   7629:   text-align: center;
                   7630: }
                   7631: 
1.349     albertel 7632: table.LC_calendar {
                   7633:   border: 1px solid #000000;
                   7634:   border-collapse: collapse;
1.917     raeburn  7635:   width: 98%;
1.349     albertel 7636: }
1.795     www      7637: 
1.349     albertel 7638: table.LC_calendar_pickdate {
                   7639:   font-size: xx-small;
                   7640: }
1.795     www      7641: 
1.349     albertel 7642: table.LC_calendar tr td {
                   7643:   border: 1px solid #000000;
                   7644:   vertical-align: top;
1.917     raeburn  7645:   width: 14%;
1.349     albertel 7646: }
1.795     www      7647: 
1.349     albertel 7648: table.LC_calendar tr td.LC_calendar_day_empty {
                   7649:   background-color: $data_table_dark;
                   7650: }
1.795     www      7651: 
1.779     bisitz   7652: table.LC_calendar tr td.LC_calendar_day_current {
                   7653:   background-color: $data_table_highlight;
1.777     tempelho 7654: }
1.795     www      7655: 
1.938     bisitz   7656: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 7657:   background-color: $mail_new;
                   7658: }
1.795     www      7659: 
1.938     bisitz   7660: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 7661:   background-color: $mail_new_hover;
                   7662: }
1.795     www      7663: 
1.938     bisitz   7664: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 7665:   background-color: $mail_read;
                   7666: }
1.795     www      7667: 
1.938     bisitz   7668: /*
                   7669: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 7670:   background-color: $mail_read_hover;
                   7671: }
1.938     bisitz   7672: */
1.795     www      7673: 
1.938     bisitz   7674: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 7675:   background-color: $mail_replied;
                   7676: }
1.795     www      7677: 
1.938     bisitz   7678: /*
                   7679: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 7680:   background-color: $mail_replied_hover;
                   7681: }
1.938     bisitz   7682: */
1.795     www      7683: 
1.938     bisitz   7684: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 7685:   background-color: $mail_other;
                   7686: }
1.795     www      7687: 
1.938     bisitz   7688: /*
                   7689: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 7690:   background-color: $mail_other_hover;
                   7691: }
1.938     bisitz   7692: */
1.494     raeburn  7693: 
1.777     tempelho 7694: table.LC_data_table tr > td.LC_browser_file,
                   7695: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   7696:   background: #AAEE77;
1.389     albertel 7697: }
1.795     www      7698: 
1.777     tempelho 7699: table.LC_data_table tr > td.LC_browser_file_locked,
                   7700: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 7701:   background: #FFAA99;
1.387     albertel 7702: }
1.795     www      7703: 
1.777     tempelho 7704: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   7705:   background: #888888;
1.779     bisitz   7706: }
1.795     www      7707: 
1.777     tempelho 7708: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   7709: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   7710:   background: #F8F866;
1.777     tempelho 7711: }
1.795     www      7712: 
1.696     bisitz   7713: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   7714:   background: #E0E8FF;
1.387     albertel 7715: }
1.696     bisitz   7716: 
1.707     bisitz   7717: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   7718:   /* background: #77FF77; */
1.707     bisitz   7719: }
1.795     www      7720: 
1.707     bisitz   7721: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   7722:   border-right: 8px solid #FFFF77;
1.707     bisitz   7723: }
1.795     www      7724: 
1.707     bisitz   7725: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   7726:   border-right: 8px solid #FFAA77;
1.707     bisitz   7727: }
1.795     www      7728: 
1.707     bisitz   7729: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   7730:   border-right: 8px solid #FF7777;
1.707     bisitz   7731: }
1.795     www      7732: 
1.707     bisitz   7733: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   7734:   border-right: 8px solid #AAFF77;
1.707     bisitz   7735: }
1.795     www      7736: 
1.707     bisitz   7737: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   7738:   border-right: 8px solid #11CC55;
1.707     bisitz   7739: }
                   7740: 
1.388     albertel 7741: span.LC_current_location {
1.701     harmsja  7742:   font-size:larger;
1.388     albertel 7743:   background: $pgbg;
                   7744: }
1.387     albertel 7745: 
1.1029    www      7746: span.LC_current_nav_location {
                   7747:   font-weight:bold;
                   7748:   background: $sidebg;
                   7749: }
                   7750: 
1.395     albertel 7751: span.LC_parm_menu_item {
                   7752:   font-size: larger;
                   7753: }
1.795     www      7754: 
1.395     albertel 7755: span.LC_parm_scope_all {
                   7756:   color: red;
                   7757: }
1.795     www      7758: 
1.395     albertel 7759: span.LC_parm_scope_folder {
                   7760:   color: green;
                   7761: }
1.795     www      7762: 
1.395     albertel 7763: span.LC_parm_scope_resource {
                   7764:   color: orange;
                   7765: }
1.795     www      7766: 
1.395     albertel 7767: span.LC_parm_part {
                   7768:   color: blue;
                   7769: }
1.795     www      7770: 
1.911     bisitz   7771: span.LC_parm_folder,
                   7772: span.LC_parm_symb {
1.395     albertel 7773:   font-size: x-small;
                   7774:   font-family: $mono;
                   7775:   color: #AAAAAA;
                   7776: }
                   7777: 
1.977     bisitz   7778: ul.LC_parm_parmlist li {
                   7779:   display: inline-block;
                   7780:   padding: 0.3em 0.8em;
                   7781:   vertical-align: top;
                   7782:   width: 150px;
                   7783:   border-top:1px solid $lg_border_color;
                   7784: }
                   7785: 
1.795     www      7786: td.LC_parm_overview_level_menu,
                   7787: td.LC_parm_overview_map_menu,
                   7788: td.LC_parm_overview_parm_selectors,
                   7789: td.LC_parm_overview_restrictions  {
1.396     albertel 7790:   border: 1px solid black;
                   7791:   border-collapse: collapse;
                   7792: }
1.795     www      7793: 
1.1285    raeburn  7794: span.LC_parm_recursive,
                   7795: td.LC_parm_recursive {
                   7796:   font-weight: bold;
                   7797:   font-size: smaller;
                   7798: }
                   7799: 
1.396     albertel 7800: table.LC_parm_overview_restrictions td {
                   7801:   border-width: 1px 4px 1px 4px;
                   7802:   border-style: solid;
                   7803:   border-color: $pgbg;
                   7804:   text-align: center;
                   7805: }
1.795     www      7806: 
1.396     albertel 7807: table.LC_parm_overview_restrictions th {
                   7808:   background: $tabbg;
                   7809:   border-width: 1px 4px 1px 4px;
                   7810:   border-style: solid;
                   7811:   border-color: $pgbg;
                   7812: }
1.795     www      7813: 
1.398     albertel 7814: table#LC_helpmenu {
1.803     bisitz   7815:   border: none;
1.398     albertel 7816:   height: 55px;
1.803     bisitz   7817:   border-spacing: 0;
1.398     albertel 7818: }
                   7819: 
                   7820: table#LC_helpmenu fieldset legend {
                   7821:   font-size: larger;
                   7822: }
1.795     www      7823: 
1.397     albertel 7824: table#LC_helpmenu_links {
                   7825:   width: 100%;
                   7826:   border: 1px solid black;
                   7827:   background: $pgbg;
1.803     bisitz   7828:   padding: 0;
1.397     albertel 7829:   border-spacing: 1px;
                   7830: }
1.795     www      7831: 
1.397     albertel 7832: table#LC_helpmenu_links tr td {
                   7833:   padding: 1px;
                   7834:   background: $tabbg;
1.399     albertel 7835:   text-align: center;
                   7836:   font-weight: bold;
1.397     albertel 7837: }
1.396     albertel 7838: 
1.795     www      7839: table#LC_helpmenu_links a:link,
                   7840: table#LC_helpmenu_links a:visited,
1.397     albertel 7841: table#LC_helpmenu_links a:active {
                   7842:   text-decoration: none;
                   7843:   color: $font;
                   7844: }
1.795     www      7845: 
1.397     albertel 7846: table#LC_helpmenu_links a:hover {
                   7847:   text-decoration: underline;
                   7848:   color: $vlink;
                   7849: }
1.396     albertel 7850: 
1.417     albertel 7851: .LC_chrt_popup_exists {
                   7852:   border: 1px solid #339933;
                   7853:   margin: -1px;
                   7854: }
1.795     www      7855: 
1.417     albertel 7856: .LC_chrt_popup_up {
                   7857:   border: 1px solid yellow;
                   7858:   margin: -1px;
                   7859: }
1.795     www      7860: 
1.417     albertel 7861: .LC_chrt_popup {
                   7862:   border: 1px solid #8888FF;
                   7863:   background: #CCCCFF;
                   7864: }
1.795     www      7865: 
1.421     albertel 7866: table.LC_pick_box {
                   7867:   border-collapse: separate;
                   7868:   background: white;
                   7869:   border: 1px solid black;
                   7870:   border-spacing: 1px;
                   7871: }
1.795     www      7872: 
1.421     albertel 7873: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   7874:   background: $sidebg;
1.421     albertel 7875:   font-weight: bold;
1.900     bisitz   7876:   text-align: left;
1.740     bisitz   7877:   vertical-align: top;
1.421     albertel 7878:   width: 184px;
                   7879:   padding: 8px;
                   7880: }
1.795     www      7881: 
1.579     raeburn  7882: table.LC_pick_box td.LC_pick_box_value {
                   7883:   text-align: left;
                   7884:   padding: 8px;
                   7885: }
1.795     www      7886: 
1.579     raeburn  7887: table.LC_pick_box td.LC_pick_box_select {
                   7888:   text-align: left;
                   7889:   padding: 8px;
                   7890: }
1.795     www      7891: 
1.424     albertel 7892: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   7893:   padding: 0;
1.421     albertel 7894:   height: 1px;
                   7895:   background: black;
                   7896: }
1.795     www      7897: 
1.421     albertel 7898: table.LC_pick_box td.LC_pick_box_submit {
                   7899:   text-align: right;
                   7900: }
1.795     www      7901: 
1.579     raeburn  7902: table.LC_pick_box td.LC_evenrow_value {
                   7903:   text-align: left;
                   7904:   padding: 8px;
                   7905:   background-color: $data_table_light;
                   7906: }
1.795     www      7907: 
1.579     raeburn  7908: table.LC_pick_box td.LC_oddrow_value {
                   7909:   text-align: left;
                   7910:   padding: 8px;
                   7911:   background-color: $data_table_light;
                   7912: }
1.795     www      7913: 
1.579     raeburn  7914: span.LC_helpform_receipt_cat {
                   7915:   font-weight: bold;
                   7916: }
1.795     www      7917: 
1.424     albertel 7918: table.LC_group_priv_box {
                   7919:   background: white;
                   7920:   border: 1px solid black;
                   7921:   border-spacing: 1px;
                   7922: }
1.795     www      7923: 
1.424     albertel 7924: table.LC_group_priv_box td.LC_pick_box_title {
                   7925:   background: $tabbg;
                   7926:   font-weight: bold;
                   7927:   text-align: right;
                   7928:   width: 184px;
                   7929: }
1.795     www      7930: 
1.424     albertel 7931: table.LC_group_priv_box td.LC_groups_fixed {
                   7932:   background: $data_table_light;
                   7933:   text-align: center;
                   7934: }
1.795     www      7935: 
1.424     albertel 7936: table.LC_group_priv_box td.LC_groups_optional {
                   7937:   background: $data_table_dark;
                   7938:   text-align: center;
                   7939: }
1.795     www      7940: 
1.424     albertel 7941: table.LC_group_priv_box td.LC_groups_functionality {
                   7942:   background: $data_table_darker;
                   7943:   text-align: center;
                   7944:   font-weight: bold;
                   7945: }
1.795     www      7946: 
1.424     albertel 7947: table.LC_group_priv td {
                   7948:   text-align: left;
1.803     bisitz   7949:   padding: 0;
1.424     albertel 7950: }
                   7951: 
                   7952: .LC_navbuttons {
                   7953:   margin: 2ex 0ex 2ex 0ex;
                   7954: }
1.795     www      7955: 
1.423     albertel 7956: .LC_topic_bar {
                   7957:   font-weight: bold;
                   7958:   background: $tabbg;
1.918     wenzelju 7959:   margin: 1em 0em 1em 2em;
1.805     bisitz   7960:   padding: 3px;
1.918     wenzelju 7961:   font-size: 1.2em;
1.423     albertel 7962: }
1.795     www      7963: 
1.423     albertel 7964: .LC_topic_bar span {
1.918     wenzelju 7965:   left: 0.5em;
                   7966:   position: absolute;
1.423     albertel 7967:   vertical-align: middle;
1.918     wenzelju 7968:   font-size: 1.2em;
1.423     albertel 7969: }
1.795     www      7970: 
1.423     albertel 7971: table.LC_course_group_status {
                   7972:   margin: 20px;
                   7973: }
1.795     www      7974: 
1.423     albertel 7975: table.LC_status_selector td {
                   7976:   vertical-align: top;
                   7977:   text-align: center;
1.424     albertel 7978:   padding: 4px;
                   7979: }
1.795     www      7980: 
1.599     albertel 7981: div.LC_feedback_link {
1.616     albertel 7982:   clear: both;
1.829     kalberla 7983:   background: $sidebg;
1.779     bisitz   7984:   width: 100%;
1.829     kalberla 7985:   padding-bottom: 10px;
                   7986:   border: 1px $tabbg solid;
1.833     kalberla 7987:   height: 22px;
                   7988:   line-height: 22px;
                   7989:   padding-top: 5px;
                   7990: }
                   7991: 
                   7992: div.LC_feedback_link img {
                   7993:   height: 22px;
1.867     kalberla 7994:   vertical-align:middle;
1.829     kalberla 7995: }
                   7996: 
1.911     bisitz   7997: div.LC_feedback_link a {
1.829     kalberla 7998:   text-decoration: none;
1.489     raeburn  7999: }
1.795     www      8000: 
1.867     kalberla 8001: div.LC_comblock {
1.911     bisitz   8002:   display:inline;
1.867     kalberla 8003:   color:$font;
                   8004:   font-size:90%;
                   8005: }
                   8006: 
                   8007: div.LC_feedback_link div.LC_comblock {
                   8008:   padding-left:5px;
                   8009: }
                   8010: 
                   8011: div.LC_feedback_link div.LC_comblock a {
                   8012:   color:$font;
                   8013: }
                   8014: 
1.489     raeburn  8015: span.LC_feedback_link {
1.858     bisitz   8016:   /* background: $feedback_link_bg; */
1.599     albertel 8017:   font-size: larger;
                   8018: }
1.795     www      8019: 
1.599     albertel 8020: span.LC_message_link {
1.858     bisitz   8021:   /* background: $feedback_link_bg; */
1.599     albertel 8022:   font-size: larger;
                   8023:   position: absolute;
                   8024:   right: 1em;
1.489     raeburn  8025: }
1.421     albertel 8026: 
1.515     albertel 8027: table.LC_prior_tries {
1.524     albertel 8028:   border: 1px solid #000000;
                   8029:   border-collapse: separate;
                   8030:   border-spacing: 1px;
1.515     albertel 8031: }
1.523     albertel 8032: 
1.515     albertel 8033: table.LC_prior_tries td {
1.524     albertel 8034:   padding: 2px;
1.515     albertel 8035: }
1.523     albertel 8036: 
                   8037: .LC_answer_correct {
1.795     www      8038:   background: lightgreen;
                   8039:   color: darkgreen;
                   8040:   padding: 6px;
1.523     albertel 8041: }
1.795     www      8042: 
1.523     albertel 8043: .LC_answer_charged_try {
1.797     www      8044:   background: #FFAAAA;
1.795     www      8045:   color: darkred;
                   8046:   padding: 6px;
1.523     albertel 8047: }
1.795     www      8048: 
1.779     bisitz   8049: .LC_answer_not_charged_try,
1.523     albertel 8050: .LC_answer_no_grade,
                   8051: .LC_answer_late {
1.795     www      8052:   background: lightyellow;
1.523     albertel 8053:   color: black;
1.795     www      8054:   padding: 6px;
1.523     albertel 8055: }
1.795     www      8056: 
1.523     albertel 8057: .LC_answer_previous {
1.795     www      8058:   background: lightblue;
                   8059:   color: darkblue;
                   8060:   padding: 6px;
1.523     albertel 8061: }
1.795     www      8062: 
1.779     bisitz   8063: .LC_answer_no_message {
1.777     tempelho 8064:   background: #FFFFFF;
                   8065:   color: black;
1.795     www      8066:   padding: 6px;
1.779     bisitz   8067: }
1.795     www      8068: 
1.1334    raeburn  8069: .LC_answer_unknown,
                   8070: .LC_answer_warning {
1.779     bisitz   8071:   background: orange;
                   8072:   color: black;
1.795     www      8073:   padding: 6px;
1.777     tempelho 8074: }
1.795     www      8075: 
1.529     albertel 8076: span.LC_prior_numerical,
                   8077: span.LC_prior_string,
                   8078: span.LC_prior_custom,
                   8079: span.LC_prior_reaction,
                   8080: span.LC_prior_math {
1.925     bisitz   8081:   font-family: $mono;
1.523     albertel 8082:   white-space: pre;
                   8083: }
                   8084: 
1.525     albertel 8085: span.LC_prior_string {
1.925     bisitz   8086:   font-family: $mono;
1.525     albertel 8087:   white-space: pre;
                   8088: }
                   8089: 
1.523     albertel 8090: table.LC_prior_option {
                   8091:   width: 100%;
                   8092:   border-collapse: collapse;
                   8093: }
1.795     www      8094: 
1.911     bisitz   8095: table.LC_prior_rank,
1.795     www      8096: table.LC_prior_match {
1.528     albertel 8097:   border-collapse: collapse;
                   8098: }
1.795     www      8099: 
1.528     albertel 8100: table.LC_prior_option tr td,
                   8101: table.LC_prior_rank tr td,
                   8102: table.LC_prior_match tr td {
1.524     albertel 8103:   border: 1px solid #000000;
1.515     albertel 8104: }
                   8105: 
1.855     bisitz   8106: .LC_nobreak {
1.544     albertel 8107:   white-space: nowrap;
1.519     raeburn  8108: }
                   8109: 
1.576     raeburn  8110: span.LC_cusr_emph {
                   8111:   font-style: italic;
                   8112: }
                   8113: 
1.633     raeburn  8114: span.LC_cusr_subheading {
                   8115:   font-weight: normal;
                   8116:   font-size: 85%;
                   8117: }
                   8118: 
1.861     bisitz   8119: div.LC_docs_entry_move {
1.859     bisitz   8120:   border: 1px solid #BBBBBB;
1.545     albertel 8121:   background: #DDDDDD;
1.861     bisitz   8122:   width: 22px;
1.859     bisitz   8123:   padding: 1px;
                   8124:   margin: 0;
1.545     albertel 8125: }
                   8126: 
1.861     bisitz   8127: table.LC_data_table tr > td.LC_docs_entry_commands,
                   8128: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 8129:   font-size: x-small;
                   8130: }
1.795     www      8131: 
1.861     bisitz   8132: .LC_docs_entry_parameter {
                   8133:   white-space: nowrap;
                   8134: }
                   8135: 
1.544     albertel 8136: .LC_docs_copy {
1.545     albertel 8137:   color: #000099;
1.544     albertel 8138: }
1.795     www      8139: 
1.544     albertel 8140: .LC_docs_cut {
1.545     albertel 8141:   color: #550044;
1.544     albertel 8142: }
1.795     www      8143: 
1.544     albertel 8144: .LC_docs_rename {
1.545     albertel 8145:   color: #009900;
1.544     albertel 8146: }
1.795     www      8147: 
1.544     albertel 8148: .LC_docs_remove {
1.545     albertel 8149:   color: #990000;
                   8150: }
                   8151: 
1.1284    raeburn  8152: .LC_docs_alias {
                   8153:   color: #440055;  
                   8154: }
                   8155: 
1.1286    raeburn  8156: .LC_domprefs_email,
1.1284    raeburn  8157: .LC_docs_alias_name,
1.547     albertel 8158: .LC_docs_reinit_warn,
                   8159: .LC_docs_ext_edit {
                   8160:   font-size: x-small;
                   8161: }
                   8162: 
1.545     albertel 8163: table.LC_docs_adddocs td,
                   8164: table.LC_docs_adddocs th {
                   8165:   border: 1px solid #BBBBBB;
                   8166:   padding: 4px;
                   8167:   background: #DDDDDD;
1.543     albertel 8168: }
                   8169: 
1.584     albertel 8170: table.LC_sty_begin {
                   8171:   background: #BBFFBB;
                   8172: }
1.795     www      8173: 
1.584     albertel 8174: table.LC_sty_end {
                   8175:   background: #FFBBBB;
                   8176: }
                   8177: 
1.589     raeburn  8178: table.LC_double_column {
1.803     bisitz   8179:   border-width: 0;
1.589     raeburn  8180:   border-collapse: collapse;
                   8181:   width: 100%;
                   8182:   padding: 2px;
                   8183: }
                   8184: 
                   8185: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  8186:   top: 2px;
1.589     raeburn  8187:   left: 2px;
                   8188:   width: 47%;
                   8189:   vertical-align: top;
                   8190: }
                   8191: 
                   8192: table.LC_double_column tr td.LC_right_col {
                   8193:   top: 2px;
1.779     bisitz   8194:   right: 2px;
1.589     raeburn  8195:   width: 47%;
                   8196:   vertical-align: top;
                   8197: }
                   8198: 
1.591     raeburn  8199: div.LC_left_float {
                   8200:   float: left;
                   8201:   padding-right: 5%;
1.597     albertel 8202:   padding-bottom: 4px;
1.591     raeburn  8203: }
                   8204: 
                   8205: div.LC_clear_float_header {
1.597     albertel 8206:   padding-bottom: 2px;
1.591     raeburn  8207: }
                   8208: 
                   8209: div.LC_clear_float_footer {
1.597     albertel 8210:   padding-top: 10px;
1.591     raeburn  8211:   clear: both;
                   8212: }
                   8213: 
1.597     albertel 8214: div.LC_grade_show_user {
1.941     bisitz   8215: /*  border-left: 5px solid $sidebg; */
                   8216:   border-top: 5px solid #000000;
                   8217:   margin: 50px 0 0 0;
1.936     bisitz   8218:   padding: 15px 0 5px 10px;
1.597     albertel 8219: }
1.795     www      8220: 
1.936     bisitz   8221: div.LC_grade_show_user_odd_row {
1.941     bisitz   8222: /*  border-left: 5px solid #000000; */
                   8223: }
                   8224: 
                   8225: div.LC_grade_show_user div.LC_Box {
                   8226:   margin-right: 50px;
1.597     albertel 8227: }
                   8228: 
                   8229: div.LC_grade_submissions,
                   8230: div.LC_grade_message_center,
1.936     bisitz   8231: div.LC_grade_info_links {
1.597     albertel 8232:   margin: 5px;
                   8233:   width: 99%;
                   8234:   background: #FFFFFF;
                   8235: }
1.795     www      8236: 
1.597     albertel 8237: div.LC_grade_submissions_header,
1.936     bisitz   8238: div.LC_grade_message_center_header {
1.705     tempelho 8239:   font-weight: bold;
                   8240:   font-size: large;
1.597     albertel 8241: }
1.795     www      8242: 
1.597     albertel 8243: div.LC_grade_submissions_body,
1.936     bisitz   8244: div.LC_grade_message_center_body {
1.597     albertel 8245:   border: 1px solid black;
                   8246:   width: 99%;
                   8247:   background: #FFFFFF;
                   8248: }
1.795     www      8249: 
1.613     albertel 8250: table.LC_scantron_action {
                   8251:   width: 100%;
                   8252: }
1.795     www      8253: 
1.613     albertel 8254: table.LC_scantron_action tr th {
1.698     harmsja  8255:   font-weight:bold;
                   8256:   font-style:normal;
1.613     albertel 8257: }
1.795     www      8258: 
1.779     bisitz   8259: .LC_edit_problem_header,
1.614     albertel 8260: div.LC_edit_problem_footer {
1.705     tempelho 8261:   font-weight: normal;
                   8262:   font-size:  medium;
1.602     albertel 8263:   margin: 2px;
1.1060    bisitz   8264:   background-color: $sidebg;
1.600     albertel 8265: }
1.795     www      8266: 
1.600     albertel 8267: div.LC_edit_problem_header,
1.602     albertel 8268: div.LC_edit_problem_header div,
1.614     albertel 8269: div.LC_edit_problem_footer,
                   8270: div.LC_edit_problem_footer div,
1.602     albertel 8271: div.LC_edit_problem_editxml_header,
                   8272: div.LC_edit_problem_editxml_header div {
1.1205    golterma 8273:   z-index: 100;
1.600     albertel 8274: }
1.795     www      8275: 
1.600     albertel 8276: div.LC_edit_problem_header_title {
1.705     tempelho 8277:   font-weight: bold;
                   8278:   font-size: larger;
1.602     albertel 8279:   background: $tabbg;
                   8280:   padding: 3px;
1.1060    bisitz   8281:   margin: 0 0 5px 0;
1.602     albertel 8282: }
1.795     www      8283: 
1.602     albertel 8284: table.LC_edit_problem_header_title {
                   8285:   width: 100%;
1.600     albertel 8286:   background: $tabbg;
1.602     albertel 8287: }
                   8288: 
1.1205    golterma 8289: div.LC_edit_actionbar {
                   8290:     background-color: $sidebg;
1.1218    droeschl 8291:     margin: 0;
                   8292:     padding: 0;
                   8293:     line-height: 200%;
1.602     albertel 8294: }
1.795     www      8295: 
1.1218    droeschl 8296: div.LC_edit_actionbar div{
                   8297:     padding: 0;
                   8298:     margin: 0;
                   8299:     display: inline-block;
1.600     albertel 8300: }
1.795     www      8301: 
1.1124    bisitz   8302: .LC_edit_opt {
                   8303:   padding-left: 1em;
                   8304:   white-space: nowrap;
                   8305: }
                   8306: 
1.1152    golterma 8307: .LC_edit_problem_latexhelper{
                   8308:     text-align: right;
                   8309: }
                   8310: 
                   8311: #LC_edit_problem_colorful div{
                   8312:     margin-left: 40px;
                   8313: }
                   8314: 
1.1205    golterma 8315: #LC_edit_problem_codemirror div{
                   8316:     margin-left: 0px;
                   8317: }
                   8318: 
1.911     bisitz   8319: img.stift {
1.803     bisitz   8320:   border-width: 0;
                   8321:   vertical-align: middle;
1.677     riegler  8322: }
1.680     riegler  8323: 
1.923     bisitz   8324: table td.LC_mainmenu_col_fieldset {
1.680     riegler  8325:   vertical-align: top;
1.777     tempelho 8326: }
1.795     www      8327: 
1.716     raeburn  8328: div.LC_createcourse {
1.911     bisitz   8329:   margin: 10px 10px 10px 10px;
1.716     raeburn  8330: }
                   8331: 
1.917     raeburn  8332: .LC_dccid {
1.1130    raeburn  8333:   float: right;
1.917     raeburn  8334:   margin: 0.2em 0 0 0;
                   8335:   padding: 0;
                   8336:   font-size: 90%;
                   8337:   display:none;
                   8338: }
                   8339: 
1.897     wenzelju 8340: ol.LC_primary_menu a:hover,
1.721     harmsja  8341: ol#LC_MenuBreadcrumbs a:hover,
                   8342: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 8343: ul#LC_secondary_menu a:hover,
1.721     harmsja  8344: .LC_FormSectionClearButton input:hover
1.795     www      8345: ul.LC_TabContent   li:hover a {
1.952     onken    8346:   color:$button_hover;
1.911     bisitz   8347:   text-decoration:none;
1.693     droeschl 8348: }
                   8349: 
1.779     bisitz   8350: h1 {
1.911     bisitz   8351:   padding: 0;
                   8352:   line-height:130%;
1.693     droeschl 8353: }
1.698     harmsja  8354: 
1.911     bisitz   8355: h2,
                   8356: h3,
                   8357: h4,
                   8358: h5,
                   8359: h6 {
                   8360:   margin: 5px 0 5px 0;
                   8361:   padding: 0;
                   8362:   line-height:130%;
1.693     droeschl 8363: }
1.795     www      8364: 
                   8365: .LC_hcell {
1.911     bisitz   8366:   padding:3px 15px 3px 15px;
                   8367:   margin: 0;
                   8368:   background-color:$tabbg;
                   8369:   color:$fontmenu;
                   8370:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 8371: }
1.795     www      8372: 
1.840     bisitz   8373: .LC_Box > .LC_hcell {
1.911     bisitz   8374:   margin: 0 -10px 10px -10px;
1.835     bisitz   8375: }
                   8376: 
1.721     harmsja  8377: .LC_noBorder {
1.911     bisitz   8378:   border: 0;
1.698     harmsja  8379: }
1.693     droeschl 8380: 
1.721     harmsja  8381: .LC_FormSectionClearButton input {
1.911     bisitz   8382:   background-color:transparent;
                   8383:   border: none;
                   8384:   cursor:pointer;
                   8385:   text-decoration:underline;
1.693     droeschl 8386: }
1.763     bisitz   8387: 
                   8388: .LC_help_open_topic {
1.911     bisitz   8389:   color: #FFFFFF;
                   8390:   background-color: #EEEEFF;
                   8391:   margin: 1px;
                   8392:   padding: 4px;
                   8393:   border: 1px solid #000033;
                   8394:   white-space: nowrap;
                   8395:   /* vertical-align: middle; */
1.759     neumanie 8396: }
1.693     droeschl 8397: 
1.911     bisitz   8398: dl,
                   8399: ul,
                   8400: div,
                   8401: fieldset {
                   8402:   margin: 10px 10px 10px 0;
                   8403:   /* overflow: hidden; */
1.693     droeschl 8404: }
1.795     www      8405: 
1.1404    raeburn  8406: fieldset#LC_selectuser {
                   8407:     margin: 0;
                   8408:     padding: 0;
                   8409: }
                   8410: 
1.1211    raeburn  8411: article.geogebraweb div {
                   8412:     margin: 0;
                   8413: }
                   8414: 
1.838     bisitz   8415: fieldset > legend {
1.911     bisitz   8416:   font-weight: bold;
                   8417:   padding: 0 5px 0 5px;
1.838     bisitz   8418: }
                   8419: 
1.813     bisitz   8420: #LC_nav_bar {
1.911     bisitz   8421:   float: left;
1.995     raeburn  8422:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   8423:   margin: 0 0 2px 0;
1.807     droeschl 8424: }
                   8425: 
1.916     droeschl 8426: #LC_realm {
                   8427:   margin: 0.2em 0 0 0;
                   8428:   padding: 0;
                   8429:   font-weight: bold;
                   8430:   text-align: center;
1.995     raeburn  8431:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 8432: }
                   8433: 
1.911     bisitz   8434: #LC_nav_bar em {
                   8435:   font-weight: bold;
                   8436:   font-style: normal;
1.807     droeschl 8437: }
                   8438: 
1.897     wenzelju 8439: ol.LC_primary_menu {
1.934     droeschl 8440:   margin: 0;
1.1076    raeburn  8441:   padding: 0;
1.807     droeschl 8442: }
                   8443: 
1.852     droeschl 8444: ol#LC_PathBreadcrumbs {
1.911     bisitz   8445:   margin: 0;
1.693     droeschl 8446: }
                   8447: 
1.897     wenzelju 8448: ol.LC_primary_menu li {
1.1076    raeburn  8449:   color: RGB(80, 80, 80);
                   8450:   vertical-align: middle;
                   8451:   text-align: left;
                   8452:   list-style: none;
1.1205    golterma 8453:   position: relative;
1.1076    raeburn  8454:   float: left;
1.1205    golterma 8455:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   8456:   line-height: 1.5em;
1.1076    raeburn  8457: }
                   8458: 
1.1205    golterma 8459: ol.LC_primary_menu li a,
                   8460: ol.LC_primary_menu li p {
1.1076    raeburn  8461:   display: block;
                   8462:   margin: 0;
                   8463:   padding: 0 5px 0 10px;
                   8464:   text-decoration: none;
                   8465: }
                   8466: 
1.1205    golterma 8467: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   8468:   display: inline-block;
                   8469:   width: 95%;
                   8470:   text-align: left;
                   8471: }
                   8472: 
                   8473: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   8474:   display: inline-block;	
                   8475:   width: 5%;
                   8476:   float: right;
                   8477:   text-align: right;
                   8478:   font-size: 70%;
                   8479: }
                   8480: 
                   8481: ol.LC_primary_menu ul {
1.1076    raeburn  8482:   display: none;
1.1205    golterma 8483:   width: 15em;
1.1076    raeburn  8484:   background-color: $data_table_light;
1.1205    golterma 8485:   position: absolute;
                   8486:   top: 100%;
1.1076    raeburn  8487: }
                   8488: 
1.1205    golterma 8489: ol.LC_primary_menu ul ul {
                   8490:   left: 100%;
                   8491:   top: 0;
                   8492: }
                   8493: 
                   8494: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  8495:   display: block;
                   8496:   position: absolute;
                   8497:   margin: 0;
                   8498:   padding: 0;
1.1078    raeburn  8499:   z-index: 2;
1.1076    raeburn  8500: }
                   8501: 
                   8502: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 8503: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  8504:   font-size: 90%;
1.911     bisitz   8505:   vertical-align: top;
1.1076    raeburn  8506:   float: none;
1.1079    raeburn  8507:   border-left: 1px solid black;
                   8508:   border-right: 1px solid black;
1.1205    golterma 8509: /* A dark bottom border to visualize different menu options; 
                   8510: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   8511:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  8512: }
                   8513: 
1.1205    golterma 8514: ol.LC_primary_menu li li p:hover {
                   8515:   color:$button_hover;
                   8516:   text-decoration:none;
                   8517:   background-color:$data_table_dark;
1.1076    raeburn  8518: }
                   8519: 
                   8520: ol.LC_primary_menu li li a:hover {
                   8521:    color:$button_hover;
                   8522:    background-color:$data_table_dark;
1.693     droeschl 8523: }
                   8524: 
1.1205    golterma 8525: /* Font-size equal to the size of the predecessors*/
                   8526: ol.LC_primary_menu li:hover li li {
                   8527:   font-size: 100%;
                   8528: }
                   8529: 
1.897     wenzelju 8530: ol.LC_primary_menu li img {
1.911     bisitz   8531:   vertical-align: bottom;
1.934     droeschl 8532:   height: 1.1em;
1.1077    raeburn  8533:   margin: 0.2em 0 0 0;
1.693     droeschl 8534: }
                   8535: 
1.897     wenzelju 8536: ol.LC_primary_menu a {
1.911     bisitz   8537:   color: RGB(80, 80, 80);
                   8538:   text-decoration: none;
1.693     droeschl 8539: }
1.795     www      8540: 
1.949     droeschl 8541: ol.LC_primary_menu a.LC_new_message {
                   8542:   font-weight:bold;
                   8543:   color: darkred;
                   8544: }
                   8545: 
1.975     raeburn  8546: ol.LC_docs_parameters {
                   8547:   margin-left: 0;
                   8548:   padding: 0;
                   8549:   list-style: none;
                   8550: }
                   8551: 
                   8552: ol.LC_docs_parameters li {
                   8553:   margin: 0;
                   8554:   padding-right: 20px;
                   8555:   display: inline;
                   8556: }
                   8557: 
1.976     raeburn  8558: ol.LC_docs_parameters li:before {
                   8559:   content: "\\002022 \\0020";
                   8560: }
                   8561: 
                   8562: li.LC_docs_parameters_title {
                   8563:   font-weight: bold;
                   8564: }
                   8565: 
                   8566: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   8567:   content: "";
                   8568: }
                   8569: 
1.897     wenzelju 8570: ul#LC_secondary_menu {
1.1107    raeburn  8571:   clear: right;
1.911     bisitz   8572:   color: $fontmenu;
                   8573:   background: $tabbg;
                   8574:   list-style: none;
                   8575:   padding: 0;
                   8576:   margin: 0;
                   8577:   width: 100%;
1.995     raeburn  8578:   text-align: left;
1.1107    raeburn  8579:   float: left;
1.808     droeschl 8580: }
                   8581: 
1.897     wenzelju 8582: ul#LC_secondary_menu li {
1.911     bisitz   8583:   font-weight: bold;
                   8584:   line-height: 1.8em;
1.1107    raeburn  8585:   border-right: 1px solid black;
                   8586:   float: left;
                   8587: }
                   8588: 
                   8589: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   8590:   background-color: $data_table_light;
                   8591: }
                   8592: 
                   8593: ul#LC_secondary_menu li a {
1.911     bisitz   8594:   padding: 0 0.8em;
1.1107    raeburn  8595: }
                   8596: 
                   8597: ul#LC_secondary_menu li ul {
                   8598:   display: none;
                   8599: }
                   8600: 
                   8601: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   8602:   display: block;
                   8603:   position: absolute;
                   8604:   margin: 0;
                   8605:   padding: 0;
                   8606:   list-style:none;
                   8607:   float: none;
                   8608:   background-color: $data_table_light;
                   8609:   z-index: 2;
                   8610:   margin-left: -1px;
                   8611: }
                   8612: 
                   8613: ul#LC_secondary_menu li ul li {
                   8614:   font-size: 90%;
                   8615:   vertical-align: top;
                   8616:   border-left: 1px solid black;
1.911     bisitz   8617:   border-right: 1px solid black;
1.1119    raeburn  8618:   background-color: $data_table_light;
1.1107    raeburn  8619:   list-style:none;
                   8620:   float: none;
                   8621: }
                   8622: 
                   8623: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   8624:   background-color: $data_table_dark;
1.807     droeschl 8625: }
                   8626: 
1.847     tempelho 8627: ul.LC_TabContent {
1.911     bisitz   8628:   display:block;
                   8629:   background: $sidebg;
                   8630:   border-bottom: solid 1px $lg_border_color;
                   8631:   list-style:none;
1.1020    raeburn  8632:   margin: -1px -10px 0 -10px;
1.911     bisitz   8633:   padding: 0;
1.693     droeschl 8634: }
                   8635: 
1.795     www      8636: ul.LC_TabContent li,
                   8637: ul.LC_TabContentBigger li {
1.911     bisitz   8638:   float:left;
1.741     harmsja  8639: }
1.795     www      8640: 
1.897     wenzelju 8641: ul#LC_secondary_menu li a {
1.911     bisitz   8642:   color: $fontmenu;
                   8643:   text-decoration: none;
1.693     droeschl 8644: }
1.795     www      8645: 
1.721     harmsja  8646: ul.LC_TabContent {
1.952     onken    8647:   min-height:20px;
1.721     harmsja  8648: }
1.795     www      8649: 
                   8650: ul.LC_TabContent li {
1.911     bisitz   8651:   vertical-align:middle;
1.959     onken    8652:   padding: 0 16px 0 10px;
1.911     bisitz   8653:   background-color:$tabbg;
                   8654:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  8655:   border-left: solid 1px $font;
1.721     harmsja  8656: }
1.795     www      8657: 
1.847     tempelho 8658: ul.LC_TabContent .right {
1.911     bisitz   8659:   float:right;
1.847     tempelho 8660: }
                   8661: 
1.911     bisitz   8662: ul.LC_TabContent li a,
                   8663: ul.LC_TabContent li {
                   8664:   color:rgb(47,47,47);
                   8665:   text-decoration:none;
                   8666:   font-size:95%;
                   8667:   font-weight:bold;
1.952     onken    8668:   min-height:20px;
                   8669: }
                   8670: 
1.959     onken    8671: ul.LC_TabContent li a:hover,
                   8672: ul.LC_TabContent li a:focus {
1.952     onken    8673:   color: $button_hover;
1.959     onken    8674:   background:none;
                   8675:   outline:none;
1.952     onken    8676: }
                   8677: 
                   8678: ul.LC_TabContent li:hover {
                   8679:   color: $button_hover;
                   8680:   cursor:pointer;
1.721     harmsja  8681: }
1.795     www      8682: 
1.911     bisitz   8683: ul.LC_TabContent li.active {
1.952     onken    8684:   color: $font;
1.911     bisitz   8685:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    8686:   border-bottom:solid 1px #FFFFFF;
                   8687:   cursor: default;
1.744     ehlerst  8688: }
1.795     www      8689: 
1.959     onken    8690: ul.LC_TabContent li.active a {
                   8691:   color:$font;
                   8692:   background:#FFFFFF;
                   8693:   outline: none;
                   8694: }
1.1047    raeburn  8695: 
                   8696: ul.LC_TabContent li.goback {
                   8697:   float: left;
                   8698:   border-left: none;
                   8699: }
                   8700: 
1.870     tempelho 8701: #maincoursedoc {
1.911     bisitz   8702:   clear:both;
1.870     tempelho 8703: }
                   8704: 
                   8705: ul.LC_TabContentBigger {
1.911     bisitz   8706:   display:block;
                   8707:   list-style:none;
                   8708:   padding: 0;
1.870     tempelho 8709: }
                   8710: 
1.795     www      8711: ul.LC_TabContentBigger li {
1.911     bisitz   8712:   vertical-align:bottom;
                   8713:   height: 30px;
                   8714:   font-size:110%;
                   8715:   font-weight:bold;
                   8716:   color: #737373;
1.841     tempelho 8717: }
                   8718: 
1.957     onken    8719: ul.LC_TabContentBigger li.active {
                   8720:   position: relative;
                   8721:   top: 1px;
                   8722: }
                   8723: 
1.870     tempelho 8724: ul.LC_TabContentBigger li a {
1.911     bisitz   8725:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   8726:   height: 30px;
                   8727:   line-height: 30px;
                   8728:   text-align: center;
                   8729:   display: block;
                   8730:   text-decoration: none;
1.958     onken    8731:   outline: none;  
1.741     harmsja  8732: }
1.795     www      8733: 
1.870     tempelho 8734: ul.LC_TabContentBigger li.active a {
1.911     bisitz   8735:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   8736:   color:$font;
1.744     ehlerst  8737: }
1.795     www      8738: 
1.870     tempelho 8739: ul.LC_TabContentBigger li b {
1.911     bisitz   8740:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   8741:   display: block;
                   8742:   float: left;
                   8743:   padding: 0 30px;
1.957     onken    8744:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 8745: }
                   8746: 
1.956     onken    8747: ul.LC_TabContentBigger li:hover b {
                   8748:   color:$button_hover;
                   8749: }
                   8750: 
1.870     tempelho 8751: ul.LC_TabContentBigger li.active b {
1.911     bisitz   8752:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   8753:   color:$font;
1.957     onken    8754:   border: 0;
1.741     harmsja  8755: }
1.693     droeschl 8756: 
1.870     tempelho 8757: 
1.862     bisitz   8758: ul.LC_CourseBreadcrumbs {
                   8759:   background: $sidebg;
1.1020    raeburn  8760:   height: 2em;
1.862     bisitz   8761:   padding-left: 10px;
1.1020    raeburn  8762:   margin: 0;
1.862     bisitz   8763:   list-style-position: inside;
                   8764: }
                   8765: 
1.911     bisitz   8766: ol#LC_MenuBreadcrumbs,
1.862     bisitz   8767: ol#LC_PathBreadcrumbs {
1.911     bisitz   8768:   padding-left: 10px;
                   8769:   margin: 0;
1.933     droeschl 8770:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 8771: }
                   8772: 
1.911     bisitz   8773: ol#LC_MenuBreadcrumbs li,
                   8774: ol#LC_PathBreadcrumbs li,
1.862     bisitz   8775: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   8776:   display: inline;
1.933     droeschl 8777:   white-space: normal;  
1.693     droeschl 8778: }
                   8779: 
1.823     bisitz   8780: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   8781: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   8782:   text-decoration: none;
                   8783:   font-size:90%;
1.693     droeschl 8784: }
1.795     www      8785: 
1.969     droeschl 8786: ol#LC_MenuBreadcrumbs h1 {
                   8787:   display: inline;
                   8788:   font-size: 90%;
                   8789:   line-height: 2.5em;
                   8790:   margin: 0;
                   8791:   padding: 0;
                   8792: }
                   8793: 
1.795     www      8794: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   8795:   text-decoration:none;
                   8796:   font-size:100%;
                   8797:   font-weight:bold;
1.693     droeschl 8798: }
1.795     www      8799: 
1.840     bisitz   8800: .LC_Box {
1.911     bisitz   8801:   border: solid 1px $lg_border_color;
                   8802:   padding: 0 10px 10px 10px;
1.746     neumanie 8803: }
1.795     www      8804: 
1.1020    raeburn  8805: .LC_DocsBox {
                   8806:   border: solid 1px $lg_border_color;
                   8807:   padding: 0 0 10px 10px;
                   8808: }
                   8809: 
1.795     www      8810: .LC_AboutMe_Image {
1.911     bisitz   8811:   float:left;
                   8812:   margin-right:10px;
1.747     neumanie 8813: }
1.795     www      8814: 
                   8815: .LC_Clear_AboutMe_Image {
1.911     bisitz   8816:   clear:left;
1.747     neumanie 8817: }
1.795     www      8818: 
1.721     harmsja  8819: dl.LC_ListStyleClean dt {
1.911     bisitz   8820:   padding-right: 5px;
                   8821:   display: table-header-group;
1.693     droeschl 8822: }
                   8823: 
1.721     harmsja  8824: dl.LC_ListStyleClean dd {
1.911     bisitz   8825:   display: table-row;
1.693     droeschl 8826: }
                   8827: 
1.721     harmsja  8828: .LC_ListStyleClean,
                   8829: .LC_ListStyleSimple,
                   8830: .LC_ListStyleNormal,
1.795     www      8831: .LC_ListStyleSpecial {
1.911     bisitz   8832:   /* display:block; */
                   8833:   list-style-position: inside;
                   8834:   list-style-type: none;
                   8835:   overflow: hidden;
                   8836:   padding: 0;
1.693     droeschl 8837: }
                   8838: 
1.721     harmsja  8839: .LC_ListStyleSimple li,
                   8840: .LC_ListStyleSimple dd,
                   8841: .LC_ListStyleNormal li,
                   8842: .LC_ListStyleNormal dd,
                   8843: .LC_ListStyleSpecial li,
1.795     www      8844: .LC_ListStyleSpecial dd {
1.911     bisitz   8845:   margin: 0;
                   8846:   padding: 5px 5px 5px 10px;
                   8847:   clear: both;
1.693     droeschl 8848: }
                   8849: 
1.721     harmsja  8850: .LC_ListStyleClean li,
                   8851: .LC_ListStyleClean dd {
1.911     bisitz   8852:   padding-top: 0;
                   8853:   padding-bottom: 0;
1.693     droeschl 8854: }
                   8855: 
1.721     harmsja  8856: .LC_ListStyleSimple dd,
1.795     www      8857: .LC_ListStyleSimple li {
1.911     bisitz   8858:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 8859: }
                   8860: 
1.721     harmsja  8861: .LC_ListStyleSpecial li,
                   8862: .LC_ListStyleSpecial dd {
1.911     bisitz   8863:   list-style-type: none;
                   8864:   background-color: RGB(220, 220, 220);
                   8865:   margin-bottom: 4px;
1.693     droeschl 8866: }
                   8867: 
1.721     harmsja  8868: table.LC_SimpleTable {
1.911     bisitz   8869:   margin:5px;
                   8870:   border:solid 1px $lg_border_color;
1.795     www      8871: }
1.693     droeschl 8872: 
1.721     harmsja  8873: table.LC_SimpleTable tr {
1.911     bisitz   8874:   padding: 0;
                   8875:   border:solid 1px $lg_border_color;
1.693     droeschl 8876: }
1.795     www      8877: 
                   8878: table.LC_SimpleTable thead {
1.911     bisitz   8879:   background:rgb(220,220,220);
1.693     droeschl 8880: }
                   8881: 
1.721     harmsja  8882: div.LC_columnSection {
1.911     bisitz   8883:   display: block;
                   8884:   clear: both;
                   8885:   overflow: hidden;
                   8886:   margin: 0;
1.693     droeschl 8887: }
                   8888: 
1.721     harmsja  8889: div.LC_columnSection>* {
1.911     bisitz   8890:   float: left;
                   8891:   margin: 10px 20px 10px 0;
                   8892:   overflow:hidden;
1.693     droeschl 8893: }
1.721     harmsja  8894: 
1.795     www      8895: table em {
1.911     bisitz   8896:   font-weight: bold;
                   8897:   font-style: normal;
1.748     schulted 8898: }
1.795     www      8899: 
1.779     bisitz   8900: table.LC_tableBrowseRes,
1.795     www      8901: table.LC_tableOfContent {
1.911     bisitz   8902:   border:none;
                   8903:   border-spacing: 1px;
                   8904:   padding: 3px;
                   8905:   background-color: #FFFFFF;
                   8906:   font-size: 90%;
1.753     droeschl 8907: }
1.789     droeschl 8908: 
1.911     bisitz   8909: table.LC_tableOfContent {
                   8910:   border-collapse: collapse;
1.789     droeschl 8911: }
                   8912: 
1.771     droeschl 8913: table.LC_tableBrowseRes a,
1.768     schulted 8914: table.LC_tableOfContent a {
1.911     bisitz   8915:   background-color: transparent;
                   8916:   text-decoration: none;
1.753     droeschl 8917: }
                   8918: 
1.795     www      8919: table.LC_tableOfContent img {
1.911     bisitz   8920:   border: none;
                   8921:   height: 1.3em;
                   8922:   vertical-align: text-bottom;
                   8923:   margin-right: 0.3em;
1.753     droeschl 8924: }
1.757     schulted 8925: 
1.795     www      8926: a#LC_content_toolbar_firsthomework {
1.911     bisitz   8927:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  8928: }
                   8929: 
1.795     www      8930: a#LC_content_toolbar_everything {
1.911     bisitz   8931:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  8932: }
                   8933: 
1.795     www      8934: a#LC_content_toolbar_uncompleted {
1.911     bisitz   8935:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  8936: }
                   8937: 
1.795     www      8938: #LC_content_toolbar_clearbubbles {
1.911     bisitz   8939:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  8940: }
                   8941: 
1.795     www      8942: a#LC_content_toolbar_changefolder {
1.911     bisitz   8943:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 8944: }
                   8945: 
1.795     www      8946: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   8947:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 8948: }
                   8949: 
1.1043    raeburn  8950: a#LC_content_toolbar_edittoplevel {
                   8951:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   8952: }
                   8953: 
1.1384    raeburn  8954: a#LC_content_toolbar_printout {
                   8955:   background-image:url(/res/adm/pages/printout.gif);
                   8956: }
                   8957: 
1.795     www      8958: ul#LC_toolbar li a:hover {
1.911     bisitz   8959:   background-position: bottom center;
1.757     schulted 8960: }
                   8961: 
1.795     www      8962: ul#LC_toolbar {
1.911     bisitz   8963:   padding: 0;
                   8964:   margin: 2px;
                   8965:   list-style:none;
                   8966:   position:relative;
                   8967:   background-color:white;
1.1082    raeburn  8968:   overflow: auto;
1.757     schulted 8969: }
                   8970: 
1.795     www      8971: ul#LC_toolbar li {
1.911     bisitz   8972:   border:1px solid white;
                   8973:   padding: 0;
                   8974:   margin: 0;
                   8975:   float: left;
                   8976:   display:inline;
                   8977:   vertical-align:middle;
1.1082    raeburn  8978:   white-space: nowrap;
1.911     bisitz   8979: }
1.757     schulted 8980: 
1.783     amueller 8981: 
1.795     www      8982: a.LC_toolbarItem {
1.911     bisitz   8983:   display:block;
                   8984:   padding: 0;
                   8985:   margin: 0;
                   8986:   height: 32px;
                   8987:   width: 32px;
                   8988:   color:white;
                   8989:   border: none;
                   8990:   background-repeat:no-repeat;
                   8991:   background-color:transparent;
1.757     schulted 8992: }
                   8993: 
1.915     droeschl 8994: ul.LC_funclist {
                   8995:     margin: 0;
                   8996:     padding: 0.5em 1em 0.5em 0;
                   8997: }
                   8998: 
1.933     droeschl 8999: ul.LC_funclist > li:first-child {
                   9000:     font-weight:bold; 
                   9001:     margin-left:0.8em;
                   9002: }
                   9003: 
1.915     droeschl 9004: ul.LC_funclist + ul.LC_funclist {
                   9005:     /* 
                   9006:        left border as a seperator if we have more than
                   9007:        one list 
                   9008:     */
                   9009:     border-left: 1px solid $sidebg;
                   9010:     /* 
                   9011:        this hides the left border behind the border of the 
                   9012:        outer box if element is wrapped to the next 'line' 
                   9013:     */
                   9014:     margin-left: -1px;
                   9015: }
                   9016: 
1.843     bisitz   9017: ul.LC_funclist li {
1.915     droeschl 9018:   display: inline;
1.782     bisitz   9019:   white-space: nowrap;
1.915     droeschl 9020:   margin: 0 0 0 25px;
                   9021:   line-height: 150%;
1.782     bisitz   9022: }
                   9023: 
1.974     wenzelju 9024: .LC_hidden {
                   9025:   display: none;
                   9026: }
                   9027: 
1.1030    www      9028: .LCmodal-overlay {
                   9029: 		position:fixed;
                   9030: 		top:0;
                   9031: 		right:0;
                   9032: 		bottom:0;
                   9033: 		left:0;
                   9034: 		height:100%;
                   9035: 		width:100%;
                   9036: 		margin:0;
                   9037: 		padding:0;
                   9038: 		background:#999;
                   9039: 		opacity:.75;
                   9040: 		filter: alpha(opacity=75);
                   9041: 		-moz-opacity: 0.75;
                   9042: 		z-index:101;
                   9043: }
                   9044: 
                   9045: * html .LCmodal-overlay {   
                   9046: 		position: absolute;
                   9047: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   9048: }
                   9049: 
                   9050: .LCmodal-window {
                   9051: 		position:fixed;
                   9052: 		top:50%;
                   9053: 		left:50%;
                   9054: 		margin:0;
                   9055: 		padding:0;
                   9056: 		z-index:102;
                   9057: 	}
                   9058: 
                   9059: * html .LCmodal-window {
                   9060: 		position:absolute;
                   9061: }
                   9062: 
                   9063: .LCclose-window {
                   9064: 		position:absolute;
                   9065: 		width:32px;
                   9066: 		height:32px;
                   9067: 		right:8px;
                   9068: 		top:8px;
                   9069: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   9070: 		text-indent:-99999px;
                   9071: 		overflow:hidden;
                   9072: 		cursor:pointer;
                   9073: }
                   9074: 
1.1369    raeburn  9075: .LCisDisabled {
                   9076:   cursor: not-allowed;
                   9077:   opacity: 0.5;
                   9078: }
                   9079: 
                   9080: a[aria-disabled="true"] {
                   9081:   color: currentColor;
                   9082:   display: inline-block;  /* For IE11/ MS Edge bug */
                   9083:   pointer-events: none;
                   9084:   text-decoration: none;
                   9085: }
                   9086: 
1.1335    raeburn  9087: pre.LC_wordwrap {
                   9088:   white-space: pre-wrap;
                   9089:   white-space: -moz-pre-wrap;
                   9090:   white-space: -pre-wrap;
                   9091:   white-space: -o-pre-wrap;
                   9092:   word-wrap: break-word;
                   9093: }
                   9094: 
1.1100    raeburn  9095: /*
1.1231    damieng  9096:   styles used for response display
                   9097: */
                   9098: div.LC_radiofoil, div.LC_rankfoil {
                   9099:   margin: .5em 0em .5em 0em;
                   9100: }
                   9101: table.LC_itemgroup {
                   9102:   margin-top: 1em;
                   9103: }
                   9104: 
                   9105: /*
1.1100    raeburn  9106:   styles used by TTH when "Default set of options to pass to tth/m
                   9107:   when converting TeX" in course settings has been set
                   9108: 
                   9109:   option passed: -t
                   9110: 
                   9111: */
                   9112: 
                   9113: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   9114: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   9115: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   9116: td div.norm {line-height:normal;}
                   9117: 
                   9118: /*
                   9119:   option passed -y3
                   9120: */
                   9121: 
                   9122: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   9123: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   9124: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   9125: 
1.1230    damieng  9126: /*
                   9127:   sections with roles, for content only
                   9128: */
                   9129: section[class^="role-"] {
                   9130:   padding-left: 10px;
                   9131:   padding-right: 5px;
                   9132:   margin-top: 8px;
                   9133:   margin-bottom: 8px;
                   9134:   border: 1px solid #2A4;
                   9135:   border-radius: 5px;
                   9136:   box-shadow: 0px 1px 1px #BBB;
                   9137: }
                   9138: section[class^="role-"]>h1 {
                   9139:   position: relative;
                   9140:   margin: 0px;
                   9141:   padding-top: 10px;
                   9142:   padding-left: 40px;
                   9143: }
                   9144: section[class^="role-"]>h1:before {
                   9145:   position: absolute;
                   9146:   left: -5px;
                   9147:   top: 5px;
                   9148: }
                   9149: section.role-activity>h1:before {
                   9150:   content:url('/adm/daxe/images/section_icons/activity.png');
                   9151: }
                   9152: section.role-advice>h1:before {
                   9153:   content:url('/adm/daxe/images/section_icons/advice.png');
                   9154: }
                   9155: section.role-bibliography>h1:before {
                   9156:   content:url('/adm/daxe/images/section_icons/bibliography.png');
                   9157: }
                   9158: section.role-citation>h1:before {
                   9159:   content:url('/adm/daxe/images/section_icons/citation.png');
                   9160: }
                   9161: section.role-conclusion>h1:before {
                   9162:   content:url('/adm/daxe/images/section_icons/conclusion.png');
                   9163: }
                   9164: section.role-definition>h1:before {
                   9165:   content:url('/adm/daxe/images/section_icons/definition.png');
                   9166: }
                   9167: section.role-demonstration>h1:before {
                   9168:   content:url('/adm/daxe/images/section_icons/demonstration.png');
                   9169: }
                   9170: section.role-example>h1:before {
                   9171:   content:url('/adm/daxe/images/section_icons/example.png');
                   9172: }
                   9173: section.role-explanation>h1:before {
                   9174:   content:url('/adm/daxe/images/section_icons/explanation.png');
                   9175: }
                   9176: section.role-introduction>h1:before {
                   9177:   content:url('/adm/daxe/images/section_icons/introduction.png');
                   9178: }
                   9179: section.role-method>h1:before {
                   9180:   content:url('/adm/daxe/images/section_icons/method.png');
                   9181: }
                   9182: section.role-more_information>h1:before {
                   9183:   content:url('/adm/daxe/images/section_icons/more_information.png');
                   9184: }
                   9185: section.role-objectives>h1:before {
                   9186:   content:url('/adm/daxe/images/section_icons/objectives.png');
                   9187: }
                   9188: section.role-prerequisites>h1:before {
                   9189:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
                   9190: }
                   9191: section.role-remark>h1:before {
                   9192:   content:url('/adm/daxe/images/section_icons/remark.png');
                   9193: }
                   9194: section.role-reminder>h1:before {
                   9195:   content:url('/adm/daxe/images/section_icons/reminder.png');
                   9196: }
                   9197: section.role-summary>h1:before {
                   9198:   content:url('/adm/daxe/images/section_icons/summary.png');
                   9199: }
                   9200: section.role-syntax>h1:before {
                   9201:   content:url('/adm/daxe/images/section_icons/syntax.png');
                   9202: }
                   9203: section.role-warning>h1:before {
                   9204:   content:url('/adm/daxe/images/section_icons/warning.png');
                   9205: }
                   9206: 
1.1269    raeburn  9207: #LC_minitab_header {
                   9208:   float:left;
                   9209:   width:100%;
                   9210:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   9211:   font-size:93%;
                   9212:   line-height:normal;
                   9213:   margin: 0.5em 0 0.5em 0;
                   9214: }
                   9215: #LC_minitab_header ul {
                   9216:   margin:0;
                   9217:   padding:10px 10px 0;
                   9218:   list-style:none;
                   9219: }
                   9220: #LC_minitab_header li {
                   9221:   float:left;
                   9222:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   9223:   margin:0;
                   9224:   padding:0 0 0 9px;
                   9225: }
                   9226: #LC_minitab_header a {
                   9227:   display:block;
                   9228:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   9229:   padding:5px 15px 4px 6px;
                   9230: }
                   9231: #LC_minitab_header #LC_current_minitab {
                   9232:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   9233: }
                   9234: #LC_minitab_header #LC_current_minitab a {
                   9235:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   9236:   padding-bottom:5px;
                   9237: }
                   9238: 
                   9239: 
1.343     albertel 9240: END
                   9241: }
                   9242: 
1.306     albertel 9243: =pod
                   9244: 
                   9245: =item * &headtag()
                   9246: 
                   9247: Returns a uniform footer for LON-CAPA web pages.
                   9248: 
1.307     albertel 9249: Inputs: $title - optional title for the head
                   9250:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 9251:         $args - optional arguments
1.319     albertel 9252:             force_register - if is true call registerurl so the remote is 
                   9253:                              informed
1.415     albertel 9254:             redirect       -> array ref of
                   9255:                                    1- seconds before redirect occurs
                   9256:                                    2- url to redirect to
                   9257:                                    3- whether the side effect should occur
1.315     albertel 9258:                            (side effect of setting 
                   9259:                                $env{'internal.head.redirect'} to the url 
1.1386    raeburn  9260:                                redirected to)
                   9261:                                    4- whether the redirect target should be
                   9262:                                       the opener of the current (pop-up)
                   9263:                                       window (side effect of setting
                   9264:                                       $env{'internal.head.to_opener'} to
                   9265:                                       1, if true.
1.1388    raeburn  9266:                                    5- whether encrypt check should be skipped
1.352     albertel 9267:             domain         -> force to color decorate a page for a specific
                   9268:                                domain
                   9269:             function       -> force usage of a specific rolish color scheme
                   9270:             bgcolor        -> override the default page bgcolor
1.460     albertel 9271:             no_auto_mt_title
                   9272:                            -> prevent &mt()ing the title arg
1.464     albertel 9273: 
1.306     albertel 9274: =cut
                   9275: 
                   9276: sub headtag {
1.313     albertel 9277:     my ($title,$head_extra,$args) = @_;
1.306     albertel 9278:     
1.363     albertel 9279:     my $function = $args->{'function'} || &get_users_function();
                   9280:     my $domain   = $args->{'domain'}   || &determinedomain();
                   9281:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  9282:     my $httphost = $args->{'use_absolute'};
1.418     albertel 9283:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 9284: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 9285: 		   #time(),
1.418     albertel 9286: 		   $env{'environment.color.timestamp'},
1.363     albertel 9287: 		   $function,$domain,$bgcolor);
                   9288: 
1.369     www      9289:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 9290: 
1.308     albertel 9291:     my $result =
                   9292: 	'<head>'.
1.1160    raeburn  9293: 	&font_settings($args);
1.319     albertel 9294: 
1.1188    raeburn  9295:     my $inhibitprint;
                   9296:     if ($args->{'print_suppress'}) {
                   9297:         $inhibitprint = &print_suppression();
                   9298:     }
1.1064    raeburn  9299: 
1.461     albertel 9300:     if (!$args->{'frameset'}) {
                   9301: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   9302:     }
1.962     droeschl 9303:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   9304:         $result .= Apache::lonxml::display_title();
1.319     albertel 9305:     }
1.436     albertel 9306:     if (!$args->{'no_nav_bar'} 
                   9307: 	&& !$args->{'only_body'}
                   9308: 	&& !$args->{'frameset'}) {
1.1154    raeburn  9309: 	$result .= &help_menu_js($httphost);
1.1032    www      9310:         $result.=&modal_window();
1.1038    www      9311:         $result.=&togglebox_script();
1.1034    www      9312:         $result.=&wishlist_window();
1.1041    www      9313:         $result.=&LCprogressbarUpdate_script();
1.1034    www      9314:     } else {
                   9315:         if ($args->{'add_modal'}) {
                   9316:            $result.=&modal_window();
                   9317:         }
                   9318:         if ($args->{'add_wishlist'}) {
                   9319:            $result.=&wishlist_window();
                   9320:         }
1.1038    www      9321:         if ($args->{'add_togglebox'}) {
                   9322:            $result.=&togglebox_script();
                   9323:         }
1.1041    www      9324:         if ($args->{'add_progressbar'}) {
                   9325:            $result.=&LCprogressbarUpdate_script();
                   9326:         }
1.436     albertel 9327:     }
1.314     albertel 9328:     if (ref($args->{'redirect'})) {
1.1388    raeburn  9329: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
                   9330:         if (!$skip_enc_check) {
                   9331:             $url = &Apache::lonenc::check_encrypt($url);
                   9332:         }
1.414     albertel 9333: 	if (!$inhibit_continue) {
                   9334: 	    $env{'internal.head.redirect'} = $url;
                   9335: 	}
1.1386    raeburn  9336: 	$result.=<<"ADDMETA";
1.313     albertel 9337: <meta http-equiv="pragma" content="no-cache" />
1.1386    raeburn  9338: ADDMETA
                   9339:         if ($to_opener) {
                   9340:             $env{'internal.head.to_opener'} = 1;
                   9341:             my $dest = &js_escape($url);
                   9342:             my $timeout = int($time * 1000);
                   9343:             $result .=<<"ENDJS";
                   9344: <script type="text/javascript">
                   9345: // <![CDATA[
                   9346: function LC_To_Opener() {
                   9347:     var dest = '$dest';
                   9348:     if (dest != '') {
                   9349:         if (window.opener != null && !window.opener.closed) {
                   9350:             window.opener.location.href=dest;
                   9351:             window.close();
                   9352:         } else {
                   9353:             window.location.href=dest;
                   9354:         }
                   9355:     }
                   9356: }
                   9357: \$(document).ready(function () {
                   9358:     setTimeout('LC_To_Opener()',$timeout);
                   9359: });
                   9360: // ]]>
                   9361: </script>
                   9362: ENDJS
                   9363:         } else {
                   9364:             $result.=<<"ADDMETA";
1.344     albertel 9365: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 9366: ADDMETA
1.1386    raeburn  9367:         }
1.1210    raeburn  9368:     } else {
                   9369:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   9370:             my $requrl = $env{'request.uri'};
                   9371:             if ($requrl eq '') {
                   9372:                 $requrl = $ENV{'REQUEST_URI'};
                   9373:                 $requrl =~ s/\?.+$//;
                   9374:             }
                   9375:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   9376:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   9377:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   9378:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   9379:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   9380:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
1.1340    raeburn  9381:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
1.1352    raeburn  9382:                     my ($offload,$offloadoth);
1.1210    raeburn  9383:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   9384:                         if ($domdefs{'offloadnow'}{$lonhost}) {
1.1340    raeburn  9385:                             $offload = 1;
1.1353    raeburn  9386:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9387:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9388:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9389:                                     $offloadoth = 1;
                   9390:                                     $dom_in_use = $env{'user.domain'};
                   9391:                                 }
                   9392:                             }
1.1340    raeburn  9393:                         }
                   9394:                     }
                   9395:                     unless ($offload) {
                   9396:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
                   9397:                             if ($domdefs{'offloadoth'}{$lonhost}) {
                   9398:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
                   9399:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
                   9400:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
                   9401:                                         $offload = 1;
1.1352    raeburn  9402:                                         $offloadoth = 1;
1.1340    raeburn  9403:                                         $dom_in_use = $env{'user.domain'};
                   9404:                                     }
1.1210    raeburn  9405:                                 }
1.1340    raeburn  9406:                             }
                   9407:                         }
                   9408:                     }
                   9409:                     if ($offload) {
1.1358    raeburn  9410:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
1.1352    raeburn  9411:                         if (($newserver eq '') && ($offloadoth)) {
                   9412:                             my @domains = &Apache::lonnet::current_machine_domains();
                   9413:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) { 
                   9414:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
                   9415:                             }
                   9416:                         }
1.1340    raeburn  9417:                         if (($newserver) && ($newserver ne $lonhost)) {
                   9418:                             my $numsec = 5;
                   9419:                             my $timeout = $numsec * 1000;
                   9420:                             my ($newurl,$locknum,%locks,$msg);
                   9421:                             if ($env{'request.role.adv'}) {
                   9422:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
                   9423:                             }
                   9424:                             my $disable_submit = 0;
                   9425:                             if ($requrl =~ /$LONCAPA::assess_re/) {
                   9426:                                 $disable_submit = 1;
                   9427:                             }
                   9428:                             if ($locknum) {
                   9429:                                 my @lockinfo = sort(values(%locks));
1.1354    raeburn  9430:                                 $msg = &mt('Once the following tasks are complete:')." \n".
1.1340    raeburn  9431:                                        join(", ",sort(values(%locks)))."\n";
                   9432:                                 if (&show_course()) {
                   9433:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
                   9434:                                 } else {
                   9435:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
1.1210    raeburn  9436:                                 }
1.1340    raeburn  9437:                             } else {
                   9438:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   9439:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
                   9440:                                 }
                   9441:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   9442:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
                   9443:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   9444:                                     $newurl .= '&role='.$env{'request.role'};
                   9445:                                 }
                   9446:                                 if ($env{'request.symb'}) {
                   9447:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
                   9448:                                     if ($shownsymb =~ m{^/enc/}) {
                   9449:                                         my $reqdmajor = 2;
                   9450:                                         my $reqdminor = 11;
                   9451:                                         my $reqdsubminor = 3;
                   9452:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
                   9453:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
                   9454:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
                   9455:                                         if (($major eq '' && $minor eq '') ||
                   9456:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
                   9457:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
                   9458:                                              ($reqdsubminor > $subminor))))) {
                   9459:                                             undef($shownsymb);
                   9460:                                         }
1.1210    raeburn  9461:                                     }
1.1340    raeburn  9462:                                     if ($shownsymb) {
                   9463:                                         &js_escape(\$shownsymb);
                   9464:                                         $newurl .= '&symb='.$shownsymb;
1.1210    raeburn  9465:                                     }
1.1340    raeburn  9466:                                 } else {
                   9467:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
                   9468:                                     &js_escape(\$shownurl);
                   9469:                                     $newurl .= '&origurl='.$shownurl;
1.1210    raeburn  9470:                                 }
1.1340    raeburn  9471:                             }
                   9472:                             &js_escape(\$msg);
                   9473:                             $result.=<<OFFLOAD
1.1210    raeburn  9474: <meta http-equiv="pragma" content="no-cache" />
                   9475: <script type="text/javascript">
1.1215    raeburn  9476: // <![CDATA[
1.1210    raeburn  9477: function LC_Offload_Now() {
                   9478:     var dest = "$newurl";
                   9479:     if (dest != '') {
                   9480:         window.location.href="$newurl";
                   9481:     }
                   9482: }
1.1214    raeburn  9483: \$(document).ready(function () {
                   9484:     window.alert('$msg');
                   9485:     if ($disable_submit) {
1.1210    raeburn  9486:         \$(".LC_hwk_submit").prop("disabled", true);
                   9487:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  9488:     }
                   9489:     setTimeout('LC_Offload_Now()', $timeout);
                   9490: });
1.1215    raeburn  9491: // ]]>
1.1210    raeburn  9492: </script>
                   9493: OFFLOAD
                   9494:                         }
                   9495:                     }
                   9496:                 }
                   9497:             }
                   9498:         }
1.313     albertel 9499:     }
1.306     albertel 9500:     if (!defined($title)) {
                   9501: 	$title = 'The LearningOnline Network with CAPA';
                   9502:     }
1.460     albertel 9503:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   9504:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  9505: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   9506:     if (!$args->{'frameset'}) {
                   9507:         $result .= ' /';
                   9508:     }
                   9509:     $result .= '>' 
1.1064    raeburn  9510:         .$inhibitprint
1.414     albertel 9511: 	.$head_extra;
1.1242    raeburn  9512:     my $clientmobile;
                   9513:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   9514:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   9515:     } else {
                   9516:         $clientmobile = $env{'browser.mobile'};
                   9517:     }
                   9518:     if ($clientmobile) {
1.1137    raeburn  9519:         $result .= '
                   9520: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   9521: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   9522:     }
1.1278    raeburn  9523:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 9524:     return $result.'</head>';
1.306     albertel 9525: }
                   9526: 
                   9527: =pod
                   9528: 
1.340     albertel 9529: =item * &font_settings()
                   9530: 
                   9531: Returns neccessary <meta> to set the proper encoding
                   9532: 
1.1160    raeburn  9533: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 9534: 
                   9535: =cut
                   9536: 
                   9537: sub font_settings {
1.1160    raeburn  9538:     my ($args) = @_;
1.340     albertel 9539:     my $headerstring='';
1.1160    raeburn  9540:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   9541:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  9542:         $headerstring.=
                   9543:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   9544:         if (!$args->{'frameset'}) {
                   9545: 	    $headerstring.= ' /';
                   9546:         }
                   9547: 	$headerstring .= '>'."\n";
1.340     albertel 9548:     }
                   9549:     return $headerstring;
                   9550: }
                   9551: 
1.341     albertel 9552: =pod
                   9553: 
1.1064    raeburn  9554: =item * &print_suppression()
                   9555: 
                   9556: In course context returns css which causes the body to be blank when media="print",
                   9557: if printout generation is unavailable for the current resource.
                   9558: 
                   9559: This could be because:
                   9560: 
                   9561: (a) printstartdate is in the future
                   9562: 
                   9563: (b) printenddate is in the past
                   9564: 
                   9565: (c) there is an active exam block with "printout"
                   9566: functionality blocked
                   9567: 
                   9568: Users with pav, pfo or evb privileges are exempt.
                   9569: 
                   9570: Inputs: none
                   9571: 
                   9572: =cut
                   9573: 
                   9574: 
                   9575: sub print_suppression {
                   9576:     my $noprint;
                   9577:     if ($env{'request.course.id'}) {
                   9578:         my $scope = $env{'request.course.id'};
                   9579:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9580:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   9581:             return;
                   9582:         }
                   9583:         if ($env{'request.course.sec'} ne '') {
                   9584:             $scope .= "/$env{'request.course.sec'}";
                   9585:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   9586:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  9587:                 return;
1.1064    raeburn  9588:             }
                   9589:         }
                   9590:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9591:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  9592:         my $clientip = &Apache::lonnet::get_requestor_ip();
                   9593:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
1.1064    raeburn  9594:         if ($blocked) {
                   9595:             my $checkrole = "cm./$cdom/$cnum";
                   9596:             if ($env{'request.course.sec'} ne '') {
                   9597:                 $checkrole .= "/$env{'request.course.sec'}";
                   9598:             }
                   9599:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   9600:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   9601:                 $noprint = 1;
                   9602:             }
                   9603:         }
                   9604:         unless ($noprint) {
                   9605:             my $symb = &Apache::lonnet::symbread();
                   9606:             if ($symb ne '') {
                   9607:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   9608:                 if (ref($navmap)) {
                   9609:                     my $res = $navmap->getBySymb($symb);
                   9610:                     if (ref($res)) {
                   9611:                         if (!$res->resprintable()) {
                   9612:                             $noprint = 1;
                   9613:                         }
                   9614:                     }
                   9615:                 }
                   9616:             }
                   9617:         }
                   9618:         if ($noprint) {
                   9619:             return <<"ENDSTYLE";
                   9620: <style type="text/css" media="print">
                   9621:     body { display:none }
                   9622: </style>
                   9623: ENDSTYLE
                   9624:         }
                   9625:     }
                   9626:     return;
                   9627: }
                   9628: 
                   9629: =pod
                   9630: 
1.341     albertel 9631: =item * &xml_begin()
                   9632: 
                   9633: Returns the needed doctype and <html>
                   9634: 
                   9635: Inputs: none
                   9636: 
                   9637: =cut
                   9638: 
                   9639: sub xml_begin {
1.1168    raeburn  9640:     my ($is_frameset) = @_;
1.341     albertel 9641:     my $output='';
                   9642: 
                   9643:     if ($env{'browser.mathml'}) {
                   9644: 	$output='<?xml version="1.0"?>'
                   9645:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   9646: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   9647:             
                   9648: #	    .'<!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">] >'
                   9649: 	    .'<!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">'
                   9650:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   9651: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  9652:     } elsif ($is_frameset) {
                   9653:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   9654:                 '<html>'."\n";
1.341     albertel 9655:     } else {
1.1168    raeburn  9656: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   9657:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 9658:     }
                   9659:     return $output;
                   9660: }
1.340     albertel 9661: 
                   9662: =pod
                   9663: 
1.306     albertel 9664: =item * &start_page()
                   9665: 
                   9666: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   9667: 
1.648     raeburn  9668: Inputs:
                   9669: 
                   9670: =over 4
                   9671: 
                   9672: $title - optional title for the page
                   9673: 
                   9674: $head_extra - optional extra HTML to incude inside the <head>
                   9675: 
                   9676: $args - additional optional args supported are:
                   9677: 
                   9678: =over 8
                   9679: 
                   9680:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 9681:                                     arg on
1.814     bisitz   9682:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  9683:              add_entries    -> additional attributes to add to the  <body>
                   9684:              domain         -> force to color decorate a page for a 
1.317     albertel 9685:                                     specific domain
1.648     raeburn  9686:              function       -> force usage of a specific rolish color
1.317     albertel 9687:                                     scheme
1.648     raeburn  9688:              redirect       -> see &headtag()
                   9689:              bgcolor        -> override the default page bg color
                   9690:              js_ready       -> return a string ready for being used in 
1.317     albertel 9691:                                     a javascript writeln
1.648     raeburn  9692:              html_encode    -> return a string ready for being used in 
1.320     albertel 9693:                                     a html attribute
1.648     raeburn  9694:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 9695:                                     $forcereg arg
1.648     raeburn  9696:              frameset       -> if true will start with a <frameset>
1.330     albertel 9697:                                     rather than <body>
1.648     raeburn  9698:              skip_phases    -> hash ref of 
1.338     albertel 9699:                                     head -> skip the <html><head> generation
                   9700:                                     body -> skip all <body> generation
1.648     raeburn  9701:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 9702:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  9703:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1272    raeburn  9704:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   9705:                                     to lonhtmlcommon::breadcrumbs
1.1096    raeburn  9706:              group          -> includes the current group, if page is for a 
1.1274    raeburn  9707:                                specific group
                   9708:              use_absolute   -> for request for external resource or syllabus, this
                   9709:                                will contain https://<hostname> if server uses
                   9710:                                https (as per hosts.tab), but request is for http
                   9711:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.1369    raeburn  9712:              links_disabled -> Links in primary and secondary menus are disabled
                   9713:                                (Can enable them once page has loaded - see lonroles.pm
                   9714:                                for an example).
1.1380    raeburn  9715:              links_target   -> Target for links, e.g., _parent (optional).
1.361     albertel 9716: 
1.648     raeburn  9717: =back
1.460     albertel 9718: 
1.648     raeburn  9719: =back
1.562     albertel 9720: 
1.306     albertel 9721: =cut
                   9722: 
                   9723: sub start_page {
1.309     albertel 9724:     my ($title,$head_extra,$args) = @_;
1.318     albertel 9725:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 9726: 
1.315     albertel 9727:     $env{'internal.start_page'}++;
1.1359    raeburn  9728:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
1.964     droeschl 9729: 
1.338     albertel 9730:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  9731:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 9732:     }
1.1316    raeburn  9733: 
                   9734:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
1.1318    raeburn  9735:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
                   9736:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
                   9737:                 $args->{'no_primary_menu'} = 1;
                   9738:             }
                   9739:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
                   9740:                 $args->{'no_inline_menu'} = 1;
                   9741:             }
                   9742:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
                   9743:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
                   9744:             }
                   9745:         } else {
                   9746:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9747:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
                   9748:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
                   9749:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
                   9750:                     $args->{'no_primary_menu'} = 1;
                   9751:                 }
                   9752:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
                   9753:                     $args->{'no_inline_menu'} = 1;
                   9754:                 }
                   9755:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
                   9756:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
                   9757:                 }
                   9758:             }
                   9759:         }
1.1316    raeburn  9760:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
                   9761:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
                   9762:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
1.1359    raeburn  9763:     } elsif ($env{'request.course.id'}) {
                   9764:         my $expiretime=600;
                   9765:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
                   9766:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
                   9767:         }
                   9768:         my ($deeplinkmenu,$menuref);
                   9769:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
                   9770:         if ($menucoll) {
                   9771:             if (ref($menuref) eq 'HASH') {
                   9772:                 %menu = %{$menuref};
                   9773:             }
                   9774:             if ($menu{'top'} eq 'n') {
                   9775:                 $args->{'no_primary_menu'} = 1;
                   9776:             }
                   9777:             if ($menu{'inline'} eq 'n') {
                   9778:                 unless (&Apache::lonnet::allowed('opa')) {
                   9779:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9780:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9781:                     my $crstype = &course_type();
                   9782:                     my $now = time;
                   9783:                     my $ccrole;
                   9784:                     if ($crstype eq 'Community') {
                   9785:                         $ccrole = 'co';
                   9786:                     } else {
                   9787:                         $ccrole = 'cc';
                   9788:                     }
                   9789:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
                   9790:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
                   9791:                         if ((($start) && ($start<0)) ||
                   9792:                             (($end) && ($end<$now))  ||
                   9793:                             (($start) && ($now<$start))) {
                   9794:                             $args->{'no_inline_menu'} = 1;
                   9795:                         }
                   9796:                     } else {
                   9797:                         $args->{'no_inline_menu'} = 1;
                   9798:                     }
                   9799:                 }
                   9800:             }
                   9801:         }
1.1316    raeburn  9802:     }
1.1359    raeburn  9803: 
1.1385    raeburn  9804:     my $showncrumbs;
1.338     albertel 9805:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   9806: 	if ($args->{'frameset'}) {
                   9807: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   9808: 						$args->{'add_entries'});
                   9809: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   9810:         } else {
                   9811:             $result .=
                   9812:                 &bodytag($title, 
                   9813:                          $args->{'function'},       $args->{'add_entries'},
                   9814:                          $args->{'only_body'},      $args->{'domain'},
                   9815:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  9816:                          $args->{'bgcolor'},        $args,
1.1385    raeburn  9817:                          \@advtools,$ltiscope,$ltiuri,\%ltimenu,$menucoll,
                   9818:                          \%menu,\$showncrumbs);
1.831     bisitz   9819:         }
1.330     albertel 9820:     }
1.338     albertel 9821: 
1.315     albertel 9822:     if ($args->{'js_ready'}) {
1.713     kaisler  9823: 		$result = &js_ready($result);
1.315     albertel 9824:     }
1.320     albertel 9825:     if ($args->{'html_encode'}) {
1.713     kaisler  9826: 		$result = &html_encode($result);
                   9827:     }
                   9828: 
1.813     bisitz   9829:     # Preparation for new and consistent functionlist at top of screen
                   9830:     # if ($args->{'functionlist'}) {
                   9831:     #            $result .= &build_functionlist();
                   9832:     #}
                   9833: 
1.964     droeschl 9834:     # Don't add anything more if only_body wanted or in const space
                   9835:     return $result if    $args->{'only_body'} 
                   9836:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   9837: 
                   9838:     #Breadcrumbs
1.758     kaisler  9839:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
1.1385    raeburn  9840:         unless ($showncrumbs) {
1.758     kaisler  9841: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   9842: 		#if any br links exists, add them to the breadcrumbs
                   9843: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   9844: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   9845: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   9846: 			}
                   9847: 		}
1.1096    raeburn  9848:                 # if @advtools array contains items add then to the breadcrumbs
                   9849:                 if (@advtools > 0) {
                   9850:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   9851:                 }
1.1272    raeburn  9852:                 my $menulink;
                   9853:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   9854:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
1.1312    raeburn  9855:                      ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
1.1272    raeburn  9856:                      ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
                   9857:                      ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
                   9858:                      (!$env{'request.role.adv'}))) {
                   9859:                     $menulink = 0;
                   9860:                 } else {
                   9861:                     undef($menulink);
                   9862:                 }
1.1385    raeburn  9863:                 my $linkprotout;
                   9864:                 if ($env{'request.deeplink.login'}) {
                   9865:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
                   9866:                     if ($linkprotout) {
                   9867:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
                   9868:                     }
                   9869:                 }
1.758     kaisler  9870: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   9871: 		if(exists($args->{'bread_crumbs_component'})){
1.1272    raeburn  9872: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.1237    raeburn  9873:                 } else {
1.1272    raeburn  9874: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  9875: 		}
1.1385    raeburn  9876:         }
1.320     albertel 9877:     }
1.315     albertel 9878:     return $result;
1.306     albertel 9879: }
                   9880: 
                   9881: sub end_page {
1.315     albertel 9882:     my ($args) = @_;
                   9883:     $env{'internal.end_page'}++;
1.330     albertel 9884:     my $result;
1.335     albertel 9885:     if ($args->{'discussion'}) {
                   9886: 	my ($target,$parser);
                   9887: 	if (ref($args->{'discussion'})) {
                   9888: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   9889: 				$args->{'discussion'}{'parser'});
                   9890: 	}
                   9891: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   9892:     }
1.330     albertel 9893:     if ($args->{'frameset'}) {
                   9894: 	$result .= '</frameset>';
                   9895:     } else {
1.635     raeburn  9896: 	$result .= &endbodytag($args);
1.330     albertel 9897:     }
1.1080    raeburn  9898:     unless ($args->{'notbody'}) {
                   9899:         $result .= "\n</html>";
                   9900:     }
1.330     albertel 9901: 
1.315     albertel 9902:     if ($args->{'js_ready'}) {
1.317     albertel 9903: 	$result = &js_ready($result);
1.315     albertel 9904:     }
1.335     albertel 9905: 
1.320     albertel 9906:     if ($args->{'html_encode'}) {
                   9907: 	$result = &html_encode($result);
                   9908:     }
1.335     albertel 9909: 
1.315     albertel 9910:     return $result;
                   9911: }
                   9912: 
1.1359    raeburn  9913: sub menucoll_in_effect {
                   9914:     my ($menucoll,$deeplinkmenu,%menu);
                   9915:     if ($env{'request.course.id'}) {
                   9916:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
1.1362    raeburn  9917:         if ($env{'request.deeplink.login'}) {
1.1370    raeburn  9918:             my ($deeplink_symb,$deeplink,$check_login_symb);
1.1362    raeburn  9919:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9920:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9921:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
                   9922:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
                   9923:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9924:                     if (ref($navmap)) {
                   9925:                         $deeplink = $navmap->get_mapparam(undef,
                   9926:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
                   9927:                                                           '0.deeplink');
1.1370    raeburn  9928:                     } else {
                   9929:                         $check_login_symb = 1;
1.1362    raeburn  9930:                     }
                   9931:                 } else {
1.1370    raeburn  9932:                     my $symb = &Apache::lonnet::symbread();
                   9933:                     if ($symb) {
                   9934:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   9935:                     } else {
                   9936:                         $check_login_symb = 1;
                   9937:                     }
1.1362    raeburn  9938:                 }
                   9939:             } else {
1.1370    raeburn  9940:                 $check_login_symb = 1;
                   9941:             }
                   9942:             if ($check_login_symb) {
1.1362    raeburn  9943:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
                   9944:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9945:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
                   9946:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   9947:                     if (ref($navmap)) {
                   9948:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                   9949:                     }
                   9950:                 } else {
                   9951:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
                   9952:                 }
                   9953:             }
1.1359    raeburn  9954:             if ($deeplink ne '') {
1.1378    raeburn  9955:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
1.1359    raeburn  9956:                 if ($display =~ /^\d+$/) {
                   9957:                     $deeplinkmenu = 1;
                   9958:                     $menucoll = $display;
                   9959:                 }
                   9960:             }
                   9961:         }
                   9962:         if ($menucoll) {
                   9963:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
                   9964:         }
                   9965:     }
                   9966:     return ($menucoll,$deeplinkmenu,\%menu);
                   9967: }
                   9968: 
1.1362    raeburn  9969: sub deeplink_login_symb {
                   9970:     my ($cnum,$cdom) = @_;
                   9971:     my $login_symb;
                   9972:     if ($env{'request.deeplink.login'}) {
1.1364    raeburn  9973:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
                   9974:     }
                   9975:     return $login_symb;
                   9976: }
                   9977: 
                   9978: sub symb_from_tinyurl {
                   9979:     my ($url,$cnum,$cdom) = @_;
                   9980:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
                   9981:         my $key = $1;
                   9982:         my ($tinyurl,$login);
                   9983:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
                   9984:         if (defined($cached)) {
                   9985:             $tinyurl = $result;
                   9986:         } else {
                   9987:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   9988:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
                   9989:             if ($currtiny{$key} ne '') {
                   9990:                 $tinyurl = $currtiny{$key};
                   9991:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
1.1362    raeburn  9992:             }
1.1364    raeburn  9993:         }
                   9994:         if ($tinyurl ne '') {
                   9995:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
                   9996:             if (wantarray) {
                   9997:                 return ($cnumreq,$symb);
                   9998:             } elsif ($cnumreq eq $cnum) {
                   9999:                 return $symb;
1.1362    raeburn  10000:             }
                   10001:         }
                   10002:     }
1.1364    raeburn  10003:     if (wantarray) {
                   10004:         return ();
                   10005:     } else {
                   10006:         return;
                   10007:     }
1.1362    raeburn  10008: }
                   10009: 
1.1405    raeburn  10010: sub usable_exttools {
                   10011:     my %tooltypes;
                   10012:     if ($env{'request.course.id'}) {
                   10013:         if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'}) {
                   10014:            if ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'both') {
                   10015:                %tooltypes = (
                   10016:                              crs => 1,
                   10017:                              dom => 1,
                   10018:                             );
                   10019:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'crs') {
                   10020:                $tooltypes{'crs'} = 1;
                   10021:            } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.exttool'} eq 'dom') {
                   10022:                $tooltypes{'dom'} = 1;
                   10023:            }
                   10024:         } else {
                   10025:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10026:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10027:             my $crstype = lc($env{'course.'.$env{'request.course.id'}.'.type'});
                   10028:             if ($crstype eq '') {
                   10029:                 $crstype = 'course';
                   10030:             }
                   10031:             if ($crstype eq 'course') {
                   10032:                 if ($env{'course.'.$env{'request.course.id'}.'internal.coursecode'}) {
                   10033:                     $crstype = 'official';
                   10034:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.textbook'}) {
                   10035:                     $crstype = 'textbook';
                   10036:                 } elsif ($env{'course.'.$env{'request.course.id'}.'.internal.lti'}) {
                   10037:                     $crstype = 'lti';
                   10038:                 } else {
                   10039:                     $crstype = 'unofficial';
                   10040:                 }
                   10041:             }
                   10042:             my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   10043:             if ($domdefaults{$crstype.'domexttool'}) {
                   10044:                 $tooltypes{'dom'} = 1;
                   10045:             }
                   10046:             if ($domdefaults{$crstype.'exttool'}) {
                   10047:                 $tooltypes{'crs'} = 1;
                   10048:             }
                   10049:         }
                   10050:     }
                   10051:     return %tooltypes;
                   10052: }
                   10053: 
1.1034    www      10054: sub wishlist_window {
                   10055:     return(<<'ENDWISHLIST');
1.1046    raeburn  10056: <script type="text/javascript">
1.1034    www      10057: // <![CDATA[
                   10058: // <!-- BEGIN LON-CAPA Internal
                   10059: function set_wishlistlink(title, path) {
                   10060:     if (!title) {
                   10061:         title = document.title;
                   10062:         title = title.replace(/^LON-CAPA /,'');
                   10063:     }
1.1175    raeburn  10064:     title = encodeURIComponent(title);
1.1203    raeburn  10065:     title = title.replace("'","\\\'");
1.1034    www      10066:     if (!path) {
                   10067:         path = location.pathname;
                   10068:     }
1.1175    raeburn  10069:     path = encodeURIComponent(path);
1.1203    raeburn  10070:     path = path.replace("'","\\\'");
1.1034    www      10071:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   10072:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   10073: }
                   10074: // END LON-CAPA Internal -->
                   10075: // ]]>
                   10076: </script>
                   10077: ENDWISHLIST
                   10078: }
                   10079: 
1.1030    www      10080: sub modal_window {
                   10081:     return(<<'ENDMODAL');
1.1046    raeburn  10082: <script type="text/javascript">
1.1030    www      10083: // <![CDATA[
                   10084: // <!-- BEGIN LON-CAPA Internal
                   10085: var modalWindow = {
                   10086: 	parent:"body",
                   10087: 	windowId:null,
                   10088: 	content:null,
                   10089: 	width:null,
                   10090: 	height:null,
                   10091: 	close:function()
                   10092: 	{
                   10093: 	        $(".LCmodal-window").remove();
                   10094: 	        $(".LCmodal-overlay").remove();
                   10095: 	},
                   10096: 	open:function()
                   10097: 	{
                   10098: 		var modal = "";
                   10099: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   10100: 		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;\">";
                   10101: 		modal += this.content;
                   10102: 		modal += "</div>";	
                   10103: 
                   10104: 		$(this.parent).append(modal);
                   10105: 
                   10106: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   10107: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   10108: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   10109: 	}
                   10110: };
1.1140    raeburn  10111: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      10112: 	{
1.1266    raeburn  10113:                 source = source.replace(/'/g,"&#39;");
1.1030    www      10114: 		modalWindow.windowId = "myModal";
                   10115: 		modalWindow.width = width;
                   10116: 		modalWindow.height = height;
1.1196    raeburn  10117: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      10118: 		modalWindow.open();
1.1208    raeburn  10119: 	};
1.1030    www      10120: // END LON-CAPA Internal -->
                   10121: // ]]>
                   10122: </script>
                   10123: ENDMODAL
                   10124: }
                   10125: 
                   10126: sub modal_link {
1.1140    raeburn  10127:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      10128:     unless ($width) { $width=480; }
                   10129:     unless ($height) { $height=400; }
1.1031    www      10130:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  10131:     unless ($transparency) { $transparency='true'; }
                   10132: 
1.1074    raeburn  10133:     my $target_attr;
                   10134:     if (defined($target)) {
                   10135:         $target_attr = 'target="'.$target.'"';
                   10136:     }
                   10137:     return <<"ENDLINK";
1.1336    raeburn  10138: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
1.1074    raeburn  10139: ENDLINK
1.1030    www      10140: }
                   10141: 
1.1032    www      10142: sub modal_adhoc_script {
1.1365    raeburn  10143:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
                   10144:     my $mathjax;
                   10145:     if ($possmathjax) {
                   10146:         $mathjax = <<'ENDJAX';
                   10147:                if (typeof MathJax == 'object') {
                   10148:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
                   10149:                }
                   10150: ENDJAX
                   10151:     }
1.1032    www      10152:     return (<<ENDADHOC);
1.1046    raeburn  10153: <script type="text/javascript">
1.1032    www      10154: // <![CDATA[
                   10155:         var $funcname = function()
                   10156:         {
                   10157:                 modalWindow.windowId = "myModal";
                   10158:                 modalWindow.width = $width;
                   10159:                 modalWindow.height = $height;
                   10160:                 modalWindow.content = '$content';
                   10161:                 modalWindow.open();
1.1365    raeburn  10162:                 $mathjax
1.1032    www      10163:         };  
                   10164: // ]]>
                   10165: </script>
                   10166: ENDADHOC
                   10167: }
                   10168: 
1.1041    www      10169: sub modal_adhoc_inner {
1.1365    raeburn  10170:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
1.1041    www      10171:     my $innerwidth=$width-20;
                   10172:     $content=&js_ready(
1.1140    raeburn  10173:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   10174:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   10175:                  $content.
1.1041    www      10176:                  &end_scrollbox().
1.1140    raeburn  10177:                  &end_page()
1.1041    www      10178:              );
1.1365    raeburn  10179:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
1.1041    www      10180: }
                   10181: 
                   10182: sub modal_adhoc_window {
1.1365    raeburn  10183:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
                   10184:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
1.1041    www      10185:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   10186: }
                   10187: 
                   10188: sub modal_adhoc_launch {
                   10189:     my ($funcname,$width,$height,$content)=@_;
                   10190:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   10191: <script type="text/javascript">
                   10192: // <![CDATA[
                   10193: $funcname();
                   10194: // ]]>
                   10195: </script>
                   10196: ENDLAUNCH
                   10197: }
                   10198: 
                   10199: sub modal_adhoc_close {
                   10200:     return (<<ENDCLOSE);
                   10201: <script type="text/javascript">
                   10202: // <![CDATA[
                   10203: modalWindow.close();
                   10204: // ]]>
                   10205: </script>
                   10206: ENDCLOSE
                   10207: }
                   10208: 
1.1038    www      10209: sub togglebox_script {
                   10210:    return(<<ENDTOGGLE);
                   10211: <script type="text/javascript"> 
                   10212: // <![CDATA[
                   10213: function LCtoggleDisplay(id,hidetext,showtext) {
                   10214:    link = document.getElementById(id + "link").childNodes[0];
                   10215:    with (document.getElementById(id).style) {
                   10216:       if (display == "none" ) {
                   10217:           display = "inline";
                   10218:           link.nodeValue = hidetext;
                   10219:         } else {
                   10220:           display = "none";
                   10221:           link.nodeValue = showtext;
                   10222:        }
                   10223:    }
                   10224: }
                   10225: // ]]>
                   10226: </script>
                   10227: ENDTOGGLE
                   10228: }
                   10229: 
1.1039    www      10230: sub start_togglebox {
                   10231:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   10232:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   10233:     unless ($showtext) { $showtext=&mt('show'); }
                   10234:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   10235:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   10236:     return &start_data_table().
                   10237:            &start_data_table_header_row().
                   10238:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   10239:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   10240:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   10241:            &end_data_table_header_row().
                   10242:            '<tr id="'.$id.'" style="display:none""><td>';
                   10243: }
                   10244: 
                   10245: sub end_togglebox {
                   10246:     return '</td></tr>'.&end_data_table();
                   10247: }
                   10248: 
1.1041    www      10249: sub LCprogressbar_script {
1.1302    raeburn  10250:    my ($id,$number_to_do)=@_;
                   10251:    if ($number_to_do) {
                   10252:        return(<<ENDPROGRESS);
1.1041    www      10253: <script type="text/javascript">
                   10254: // <![CDATA[
1.1045    www      10255: \$('#progressbar$id').progressbar({
1.1041    www      10256:   value: 0,
                   10257:   change: function(event, ui) {
                   10258:     var newVal = \$(this).progressbar('option', 'value');
                   10259:     \$('.pblabel', this).text(LCprogressTxt);
                   10260:   }
                   10261: });
                   10262: // ]]>
                   10263: </script>
                   10264: ENDPROGRESS
1.1302    raeburn  10265:    } else {
                   10266:        return(<<ENDPROGRESS);
                   10267: <script type="text/javascript">
                   10268: // <![CDATA[
                   10269: \$('#progressbar$id').progressbar({
                   10270:   value: false,
                   10271:   create: function(event, ui) {
                   10272:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   10273:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   10274:   }
                   10275: });
                   10276: // ]]>
                   10277: </script>
                   10278: ENDPROGRESS
                   10279:    }
1.1041    www      10280: }
                   10281: 
                   10282: sub LCprogressbarUpdate_script {
                   10283:    return(<<ENDPROGRESSUPDATE);
                   10284: <style type="text/css">
                   10285: .ui-progressbar { position:relative; }
1.1302    raeburn  10286: .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      10287: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   10288: </style>
                   10289: <script type="text/javascript">
                   10290: // <![CDATA[
1.1045    www      10291: var LCprogressTxt='---';
                   10292: 
1.1302    raeburn  10293: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      10294:    LCprogressTxt=progresstext;
1.1302    raeburn  10295:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   10296:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   10297:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
1.1301    raeburn  10298:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   10299:    } else {
                   10300:        \$('#progressbar'+id).progressbar('value',percent);
                   10301:    }
1.1041    www      10302: }
                   10303: // ]]>
                   10304: </script>
                   10305: ENDPROGRESSUPDATE
                   10306: }
                   10307: 
1.1042    www      10308: my $LClastpercent;
1.1045    www      10309: my $LCidcnt;
                   10310: my $LCcurrentid;
1.1042    www      10311: 
1.1041    www      10312: sub LCprogressbar {
1.1302    raeburn  10313:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      10314:     $LClastpercent=0;
1.1045    www      10315:     $LCidcnt++;
                   10316:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1302    raeburn  10317:     my ($starting,$content);
                   10318:     if ($number_to_do) {
                   10319:         $starting=&mt('Starting');
                   10320:         $content=(<<ENDPROGBAR);
                   10321: $preamble
1.1045    www      10322:   <div id="progressbar$LCcurrentid">
1.1041    www      10323:     <span class="pblabel">$starting</span>
                   10324:   </div>
                   10325: ENDPROGBAR
1.1302    raeburn  10326:     } else {
                   10327:         $starting=&mt('Loading...');
                   10328:         $LClastpercent='false';
                   10329:         $content=(<<ENDPROGBAR);
                   10330: $preamble
                   10331:   <div id="progressbar$LCcurrentid">
                   10332:       <div class="progress-label">$starting</div>
                   10333:   </div>
                   10334: ENDPROGBAR
                   10335:     }
                   10336:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      10337: }
                   10338: 
                   10339: sub LCprogressbarUpdate {
1.1302    raeburn  10340:     my ($r,$val,$text,$number_to_do)=@_;
                   10341:     if ($number_to_do) {
                   10342:         unless ($val) { 
                   10343:             if ($LClastpercent) {
                   10344:                 $val=$LClastpercent;
                   10345:             } else {
                   10346:                 $val=0;
                   10347:             }
                   10348:         }
                   10349:         if ($val<0) { $val=0; }
                   10350:         if ($val>100) { $val=0; }
                   10351:         $LClastpercent=$val;
                   10352:         unless ($text) { $text=$val.'%'; }
                   10353:     } else {
                   10354:         $val = 'false';
1.1042    www      10355:     }
1.1041    www      10356:     $text=&js_ready($text);
1.1044    www      10357:     &r_print($r,<<ENDUPDATE);
1.1041    www      10358: <script type="text/javascript">
                   10359: // <![CDATA[
1.1302    raeburn  10360: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      10361: // ]]>
                   10362: </script>
                   10363: ENDUPDATE
1.1035    www      10364: }
                   10365: 
1.1042    www      10366: sub LCprogressbarClose {
                   10367:     my ($r)=@_;
                   10368:     $LClastpercent=0;
1.1044    www      10369:     &r_print($r,<<ENDCLOSE);
1.1042    www      10370: <script type="text/javascript">
                   10371: // <![CDATA[
1.1045    www      10372: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      10373: // ]]>
                   10374: </script>
                   10375: ENDCLOSE
1.1044    www      10376: }
                   10377: 
                   10378: sub r_print {
                   10379:     my ($r,$to_print)=@_;
                   10380:     if ($r) {
                   10381:       $r->print($to_print);
                   10382:       $r->rflush();
                   10383:     } else {
                   10384:       print($to_print);
                   10385:     }
1.1042    www      10386: }
                   10387: 
1.320     albertel 10388: sub html_encode {
                   10389:     my ($result) = @_;
                   10390: 
1.322     albertel 10391:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 10392:     
                   10393:     return $result;
                   10394: }
1.1044    www      10395: 
1.317     albertel 10396: sub js_ready {
                   10397:     my ($result) = @_;
                   10398: 
1.323     albertel 10399:     $result =~ s/[\n\r]/ /xmsg;
                   10400:     $result =~ s/\\/\\\\/xmsg;
                   10401:     $result =~ s/'/\\'/xmsg;
1.372     albertel 10402:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 10403:     
                   10404:     return $result;
                   10405: }
                   10406: 
1.315     albertel 10407: sub validate_page {
                   10408:     if (  exists($env{'internal.start_page'})
1.316     albertel 10409: 	  &&     $env{'internal.start_page'} > 1) {
                   10410: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 10411: 				 $env{'internal.start_page'}.' '.
1.316     albertel 10412: 				 $ENV{'request.filename'});
1.315     albertel 10413:     }
                   10414:     if (  exists($env{'internal.end_page'})
1.316     albertel 10415: 	  &&     $env{'internal.end_page'} > 1) {
                   10416: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 10417: 				 $env{'internal.end_page'}.' '.
1.316     albertel 10418: 				 $env{'request.filename'});
1.315     albertel 10419:     }
                   10420:     if (     exists($env{'internal.start_page'})
                   10421: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 10422: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   10423: 				 $env{'request.filename'});
1.315     albertel 10424:     }
                   10425:     if (   ! exists($env{'internal.start_page'})
                   10426: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 10427: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   10428: 				 $env{'request.filename'});
1.315     albertel 10429:     }
1.306     albertel 10430: }
1.315     albertel 10431: 
1.996     www      10432: 
                   10433: sub start_scrollbox {
1.1140    raeburn  10434:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  10435:     unless ($outerwidth) { $outerwidth='520px'; }
                   10436:     unless ($width) { $width='500px'; }
                   10437:     unless ($height) { $height='200px'; }
1.1075    raeburn  10438:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  10439:     if ($id ne '') {
1.1140    raeburn  10440:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  10441:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  10442:     }
1.1075    raeburn  10443:     if ($bgcolor ne '') {
                   10444:         $tdcol = "background-color: $bgcolor;";
                   10445:     }
1.1137    raeburn  10446:     my $nicescroll_js;
                   10447:     if ($env{'browser.mobile'}) {
1.1140    raeburn  10448:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   10449:     }
                   10450:     return <<"END";
                   10451: $nicescroll_js
                   10452: 
                   10453: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   10454: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   10455: END
                   10456: }
                   10457: 
                   10458: sub end_scrollbox {
                   10459:     return '</div></td></tr></table>';
                   10460: }
                   10461: 
                   10462: sub nicescroll_javascript {
                   10463:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   10464:     my %options;
                   10465:     if (ref($cursor) eq 'HASH') {
                   10466:         %options = %{$cursor};
                   10467:     }
                   10468:     unless ($options{'railalign'} =~ /^left|right$/) {
                   10469:         $options{'railalign'} = 'left';
                   10470:     }
                   10471:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   10472:         my $function  = &get_users_function();
                   10473:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  10474:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  10475:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  10476:         }
1.1140    raeburn  10477:     }
                   10478:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   10479:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  10480:             $options{'cursoropacity'}='1.0';
                   10481:         }
1.1140    raeburn  10482:     } else {
                   10483:         $options{'cursoropacity'}='1.0';
                   10484:     }
                   10485:     if ($options{'cursorfixedheight'} eq 'none') {
                   10486:         delete($options{'cursorfixedheight'});
                   10487:     } else {
                   10488:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   10489:     }
                   10490:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   10491:         delete($options{'railoffset'});
                   10492:     }
                   10493:     my @niceoptions;
                   10494:     while (my($key,$value) = each(%options)) {
                   10495:         if ($value =~ /^\{.+\}$/) {
                   10496:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  10497:         } else {
1.1140    raeburn  10498:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  10499:         }
1.1140    raeburn  10500:     }
                   10501:     my $nicescroll_js = '
1.1137    raeburn  10502: $(document).ready(
1.1140    raeburn  10503:       function() {
                   10504:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   10505:       }
1.1137    raeburn  10506: );
                   10507: ';
1.1140    raeburn  10508:     if ($framecheck) {
                   10509:         $nicescroll_js .= '
                   10510: function expand_div(caller) {
                   10511:     if (top === self) {
                   10512:         document.getElementById("'.$id.'").style.width = "auto";
                   10513:         document.getElementById("'.$id.'").style.height = "auto";
                   10514:     } else {
                   10515:         try {
                   10516:             if (parent.frames) {
                   10517:                 if (parent.frames.length > 1) {
                   10518:                     var framesrc = parent.frames[1].location.href;
                   10519:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   10520:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   10521:                         document.getElementById("'.$id.'").style.width = "auto";
                   10522:                         document.getElementById("'.$id.'").style.height = "auto";
                   10523:                     }
                   10524:                 }
                   10525:             }
                   10526:         } catch (e) {
                   10527:             return;
                   10528:         }
1.1137    raeburn  10529:     }
1.1140    raeburn  10530:     return;
1.996     www      10531: }
1.1140    raeburn  10532: ';
                   10533:     }
                   10534:     if ($needjsready) {
                   10535:         $nicescroll_js = '
                   10536: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   10537:     } else {
                   10538:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   10539:     }
                   10540:     return $nicescroll_js;
1.996     www      10541: }
                   10542: 
1.318     albertel 10543: sub simple_error_page {
1.1150    bisitz   10544:     my ($r,$title,$msg,$args) = @_;
1.1304    raeburn  10545:     my %displayargs;
1.1151    raeburn  10546:     if (ref($args) eq 'HASH') {
                   10547:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
1.1304    raeburn  10548:         if ($args->{'only_body'}) {
                   10549:             $displayargs{'only_body'} = 1;
                   10550:         }
                   10551:         if ($args->{'no_nav_bar'}) {
                   10552:             $displayargs{'no_nav_bar'} = 1;
                   10553:         }
1.1151    raeburn  10554:     } else {
                   10555:         $msg = &mt($msg);
                   10556:     }
1.1150    bisitz   10557: 
1.318     albertel 10558:     my $page =
1.1304    raeburn  10559: 	&Apache::loncommon::start_page($title,'',\%displayargs).
1.1150    bisitz   10560: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 10561: 	&Apache::loncommon::end_page();
                   10562:     if (ref($r)) {
                   10563: 	$r->print($page);
1.327     albertel 10564: 	return;
1.318     albertel 10565:     }
                   10566:     return $page;
                   10567: }
1.347     albertel 10568: 
                   10569: {
1.610     albertel 10570:     my @row_count;
1.961     onken    10571: 
                   10572:     sub start_data_table_count {
                   10573:         unshift(@row_count, 0);
                   10574:         return;
                   10575:     }
                   10576: 
                   10577:     sub end_data_table_count {
                   10578:         shift(@row_count);
                   10579:         return;
                   10580:     }
                   10581: 
1.347     albertel 10582:     sub start_data_table {
1.1018    raeburn  10583: 	my ($add_class,$id) = @_;
1.422     albertel 10584: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  10585:         my $table_id;
                   10586:         if (defined($id)) {
                   10587:             $table_id = ' id="'.$id.'"';
                   10588:         }
1.961     onken    10589: 	&start_data_table_count();
1.1018    raeburn  10590: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 10591:     }
                   10592: 
                   10593:     sub end_data_table {
1.961     onken    10594: 	&end_data_table_count();
1.389     albertel 10595: 	return '</table>'."\n";;
1.347     albertel 10596:     }
                   10597: 
                   10598:     sub start_data_table_row {
1.974     wenzelju 10599: 	my ($add_class, $id) = @_;
1.610     albertel 10600: 	$row_count[0]++;
                   10601: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   10602: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 10603:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10604:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 10605:     }
1.471     banghart 10606:     
                   10607:     sub continue_data_table_row {
1.974     wenzelju 10608: 	my ($add_class, $id) = @_;
1.610     albertel 10609: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 10610: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   10611:         $id = (' id="'.$id.'"') unless ($id eq '');
                   10612:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 10613:     }
1.347     albertel 10614: 
                   10615:     sub end_data_table_row {
1.389     albertel 10616: 	return '</tr>'."\n";;
1.347     albertel 10617:     }
1.367     www      10618: 
1.421     albertel 10619:     sub start_data_table_empty_row {
1.707     bisitz   10620: #	$row_count[0]++;
1.421     albertel 10621: 	return  '<tr class="LC_empty_row" >'."\n";;
                   10622:     }
                   10623: 
                   10624:     sub end_data_table_empty_row {
                   10625: 	return '</tr>'."\n";;
                   10626:     }
                   10627: 
1.367     www      10628:     sub start_data_table_header_row {
1.389     albertel 10629: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      10630:     }
                   10631: 
                   10632:     sub end_data_table_header_row {
1.389     albertel 10633: 	return '</tr>'."\n";;
1.367     www      10634:     }
1.890     droeschl 10635: 
                   10636:     sub data_table_caption {
                   10637:         my $caption = shift;
                   10638:         return "<caption class=\"LC_caption\">$caption</caption>";
                   10639:     }
1.347     albertel 10640: }
                   10641: 
1.548     albertel 10642: =pod
                   10643: 
                   10644: =item * &inhibit_menu_check($arg)
                   10645: 
                   10646: Checks for a inhibitmenu state and generates output to preserve it
                   10647: 
                   10648: Inputs:         $arg - can be any of
                   10649:                      - undef - in which case the return value is a string 
                   10650:                                to add  into arguments list of a uri
                   10651:                      - 'input' - in which case the return value is a HTML
                   10652:                                  <form> <input> field of type hidden to
                   10653:                                  preserve the value
                   10654:                      - a url - in which case the return value is the url with
                   10655:                                the neccesary cgi args added to preserve the
                   10656:                                inhibitmenu state
                   10657:                      - a ref to a url - no return value, but the string is
                   10658:                                         updated to include the neccessary cgi
                   10659:                                         args to preserve the inhibitmenu state
                   10660: 
                   10661: =cut
                   10662: 
                   10663: sub inhibit_menu_check {
                   10664:     my ($arg) = @_;
                   10665:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   10666:     if ($arg eq 'input') {
                   10667: 	if ($env{'form.inhibitmenu'}) {
                   10668: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   10669: 	} else {
                   10670: 	    return
                   10671: 	}
                   10672:     }
                   10673:     if ($env{'form.inhibitmenu'}) {
                   10674: 	if (ref($arg)) {
                   10675: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10676: 	} elsif ($arg eq '') {
                   10677: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   10678: 	} else {
                   10679: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   10680: 	}
                   10681:     }
                   10682:     if (!ref($arg)) {
                   10683: 	return $arg;
                   10684:     }
                   10685: }
                   10686: 
1.251     albertel 10687: ###############################################
1.182     matthew  10688: 
                   10689: =pod
                   10690: 
1.549     albertel 10691: =back
                   10692: 
                   10693: =head1 User Information Routines
                   10694: 
                   10695: =over 4
                   10696: 
1.405     albertel 10697: =item * &get_users_function()
1.182     matthew  10698: 
                   10699: Used by &bodytag to determine the current users primary role.
                   10700: Returns either 'student','coordinator','admin', or 'author'.
                   10701: 
                   10702: =cut
                   10703: 
                   10704: ###############################################
                   10705: sub get_users_function {
1.815     tempelho 10706:     my $function = 'norole';
1.818     tempelho 10707:     if ($env{'request.role'}=~/^(st)/) {
                   10708:         $function='student';
                   10709:     }
1.907     raeburn  10710:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  10711:         $function='coordinator';
                   10712:     }
1.258     albertel 10713:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  10714:         $function='admin';
                   10715:     }
1.826     bisitz   10716:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  10717:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  10718:         $function='author';
                   10719:     }
                   10720:     return $function;
1.54      www      10721: }
1.99      www      10722: 
                   10723: ###############################################
                   10724: 
1.233     raeburn  10725: =pod
                   10726: 
1.821     raeburn  10727: =item * &show_course()
                   10728: 
                   10729: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   10730: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   10731: 
                   10732: Inputs:
                   10733: None
                   10734: 
                   10735: Outputs:
                   10736: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   10737: 
                   10738: =cut
                   10739: 
                   10740: ###############################################
                   10741: sub show_course {
1.1408    raeburn  10742:     my ($udom,$uname) = @_;
                   10743:     if (($udom ne '') && ($uname ne '')) {
                   10744:         if (($udom ne $env{'user.domain'}) || ($uname ne $env{'user.name'})) {
1.1410    raeburn  10745:             if (&Apache::lonnet::is_advanced_user($udom,$uname)) {
1.1408    raeburn  10746:                 return 0;
                   10747:             } else {
                   10748:                 return 1;
                   10749:             }
                   10750:         }
                   10751:     }
1.821     raeburn  10752:     my $course = !$env{'user.adv'};
                   10753:     if (!$env{'user.adv'}) {
                   10754:         foreach my $env (keys(%env)) {
                   10755:             next if ($env !~ m/^user\.priv\./);
                   10756:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   10757:                 $course = 0;
                   10758:                 last;
                   10759:             }
                   10760:         }
                   10761:     }
                   10762:     return $course;
                   10763: }
                   10764: 
                   10765: ###############################################
                   10766: 
                   10767: =pod
                   10768: 
1.542     raeburn  10769: =item * &check_user_status()
1.274     raeburn  10770: 
                   10771: Determines current status of supplied role for a
                   10772: specific user. Roles can be active, previous or future.
                   10773: 
                   10774: Inputs: 
                   10775: user's domain, user's username, course's domain,
1.375     raeburn  10776: course's number, optional section ID.
1.274     raeburn  10777: 
                   10778: Outputs:
                   10779: role status: active, previous or future. 
                   10780: 
                   10781: =cut
                   10782: 
                   10783: sub check_user_status {
1.412     raeburn  10784:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  10785:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  10786:     my @uroles = keys(%userinfo);
1.274     raeburn  10787:     my $srchstr;
                   10788:     my $active_chk = 'none';
1.412     raeburn  10789:     my $now = time;
1.274     raeburn  10790:     if (@uroles > 0) {
1.908     raeburn  10791:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  10792:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   10793:         } else {
1.412     raeburn  10794:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   10795:         }
                   10796:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  10797:             my $role_end = 0;
                   10798:             my $role_start = 0;
                   10799:             $active_chk = 'active';
1.412     raeburn  10800:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   10801:                 $role_end = $1;
                   10802:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   10803:                     $role_start = $1;
1.274     raeburn  10804:                 }
                   10805:             }
                   10806:             if ($role_start > 0) {
1.412     raeburn  10807:                 if ($now < $role_start) {
1.274     raeburn  10808:                     $active_chk = 'future';
                   10809:                 }
                   10810:             }
                   10811:             if ($role_end > 0) {
1.412     raeburn  10812:                 if ($now > $role_end) {
1.274     raeburn  10813:                     $active_chk = 'previous';
                   10814:                 }
                   10815:             }
                   10816:         }
                   10817:     }
                   10818:     return $active_chk;
                   10819: }
                   10820: 
                   10821: ###############################################
                   10822: 
                   10823: =pod
                   10824: 
1.405     albertel 10825: =item * &get_sections()
1.233     raeburn  10826: 
                   10827: Determines all the sections for a course including
                   10828: sections with students and sections containing other roles.
1.419     raeburn  10829: Incoming parameters: 
                   10830: 
                   10831: 1. domain
                   10832: 2. course number 
                   10833: 3. reference to array containing roles for which sections should 
                   10834: be gathered (optional).
                   10835: 4. reference to array containing status types for which sections 
                   10836: should be gathered (optional).
                   10837: 
                   10838: If the third argument is undefined, sections are gathered for any role. 
                   10839: If the fourth argument is undefined, sections are gathered for any status.
                   10840: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  10841:  
1.374     raeburn  10842: Returns section hash (keys are section IDs, values are
                   10843: number of users in each section), subject to the
1.419     raeburn  10844: optional roles filter, optional status filter 
1.233     raeburn  10845: 
                   10846: =cut
                   10847: 
                   10848: ###############################################
                   10849: sub get_sections {
1.419     raeburn  10850:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 10851:     if (!defined($cdom) || !defined($cnum)) {
                   10852:         my $cid =  $env{'request.course.id'};
                   10853: 
                   10854: 	return if (!defined($cid));
                   10855: 
                   10856:         $cdom = $env{'course.'.$cid.'.domain'};
                   10857:         $cnum = $env{'course.'.$cid.'.num'};
                   10858:     }
                   10859: 
                   10860:     my %sectioncount;
1.419     raeburn  10861:     my $now = time;
1.240     albertel 10862: 
1.1118    raeburn  10863:     my $check_students = 1;
                   10864:     my $only_students = 0;
                   10865:     if (ref($possible_roles) eq 'ARRAY') {
                   10866:         if (grep(/^st$/,@{$possible_roles})) {
                   10867:             if (@{$possible_roles} == 1) {
                   10868:                 $only_students = 1;
                   10869:             }
                   10870:         } else {
                   10871:             $check_students = 0;
                   10872:         }
                   10873:     }
                   10874: 
                   10875:     if ($check_students) { 
1.276     albertel 10876: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 10877: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   10878: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  10879:         my $start_index = &Apache::loncoursedata::CL_START();
                   10880:         my $end_index = &Apache::loncoursedata::CL_END();
                   10881:         my $status;
1.366     albertel 10882: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  10883: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   10884: 				                     $data->[$status_index],
                   10885:                                                      $data->[$start_index],
                   10886:                                                      $data->[$end_index]);
                   10887:             if ($stu_status eq 'Active') {
                   10888:                 $status = 'active';
                   10889:             } elsif ($end < $now) {
                   10890:                 $status = 'previous';
                   10891:             } elsif ($start > $now) {
                   10892:                 $status = 'future';
                   10893:             } 
                   10894: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   10895:                 if ((!defined($possible_status)) || (($status ne '') && 
                   10896:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   10897: 		    $sectioncount{$section}++;
                   10898:                 }
1.240     albertel 10899: 	    }
                   10900: 	}
                   10901:     }
1.1118    raeburn  10902:     if ($only_students) {
                   10903:         return %sectioncount;
                   10904:     }
1.240     albertel 10905:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   10906:     foreach my $user (sort(keys(%courseroles))) {
                   10907: 	if ($user !~ /^(\w{2})/) { next; }
                   10908: 	my ($role) = ($user =~ /^(\w{2})/);
                   10909: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  10910: 	my ($section,$status);
1.240     albertel 10911: 	if ($role eq 'cr' &&
                   10912: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   10913: 	    $section=$1;
                   10914: 	}
                   10915: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   10916: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  10917:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   10918:         if ($end == -1 && $start == -1) {
                   10919:             next; #deleted role
                   10920:         }
                   10921:         if (!defined($possible_status)) { 
                   10922:             $sectioncount{$section}++;
                   10923:         } else {
                   10924:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   10925:                 $status = 'active';
                   10926:             } elsif ($end < $now) {
                   10927:                 $status = 'future';
                   10928:             } elsif ($start > $now) {
                   10929:                 $status = 'previous';
                   10930:             }
                   10931:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   10932:                 $sectioncount{$section}++;
                   10933:             }
                   10934:         }
1.233     raeburn  10935:     }
1.366     albertel 10936:     return %sectioncount;
1.233     raeburn  10937: }
                   10938: 
1.274     raeburn  10939: ###############################################
1.294     raeburn  10940: 
                   10941: =pod
1.405     albertel 10942: 
                   10943: =item * &get_course_users()
                   10944: 
1.275     raeburn  10945: Retrieves usernames:domains for users in the specified course
                   10946: with specific role(s), and access status. 
                   10947: 
                   10948: Incoming parameters:
1.277     albertel 10949: 1. course domain
                   10950: 2. course number
                   10951: 3. access status: users must have - either active, 
1.275     raeburn  10952: previous, future, or all.
1.277     albertel 10953: 4. reference to array of permissible roles
1.288     raeburn  10954: 5. reference to array of section restrictions (optional)
                   10955: 6. reference to results object (hash of hashes).
                   10956: 7. reference to optional userdata hash
1.609     raeburn  10957: 8. reference to optional statushash
1.630     raeburn  10958: 9. flag if privileged users (except those set to unhide in
                   10959:    course settings) should be excluded    
1.609     raeburn  10960: Keys of top level results hash are roles.
1.275     raeburn  10961: Keys of inner hashes are username:domain, with 
                   10962: values set to access type.
1.288     raeburn  10963: Optional userdata hash returns an array with arguments in the 
                   10964: same order as loncoursedata::get_classlist() for student data.
                   10965: 
1.609     raeburn  10966: Optional statushash returns
                   10967: 
1.288     raeburn  10968: Entries for end, start, section and status are blank because
                   10969: of the possibility of multiple values for non-student roles.
                   10970: 
1.275     raeburn  10971: =cut
1.405     albertel 10972: 
1.275     raeburn  10973: ###############################################
1.405     albertel 10974: 
1.275     raeburn  10975: sub get_course_users {
1.630     raeburn  10976:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  10977:     my %idx = ();
1.419     raeburn  10978:     my %seclists;
1.288     raeburn  10979: 
                   10980:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   10981:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   10982:     $idx{end} = &Apache::loncoursedata::CL_END();
                   10983:     $idx{start} = &Apache::loncoursedata::CL_START();
                   10984:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   10985:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   10986:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   10987:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   10988: 
1.290     albertel 10989:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 10990:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  10991:         my $now = time;
1.277     albertel 10992:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  10993:             my $match = 0;
1.412     raeburn  10994:             my $secmatch = 0;
1.419     raeburn  10995:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  10996:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  10997:             if ($section eq '') {
                   10998:                 $section = 'none';
                   10999:             }
1.291     albertel 11000:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11001:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11002:                     $secmatch = 1;
                   11003:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 11004:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11005:                         $secmatch = 1;
                   11006:                     }
                   11007:                 } else {  
1.419     raeburn  11008: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  11009: 		        $secmatch = 1;
                   11010:                     }
1.290     albertel 11011: 		}
1.412     raeburn  11012:                 if (!$secmatch) {
                   11013:                     next;
                   11014:                 }
1.419     raeburn  11015:             }
1.275     raeburn  11016:             if (defined($$types{'active'})) {
1.288     raeburn  11017:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  11018:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  11019:                     $match = 1;
1.275     raeburn  11020:                 }
                   11021:             }
                   11022:             if (defined($$types{'previous'})) {
1.609     raeburn  11023:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  11024:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  11025:                     $match = 1;
1.275     raeburn  11026:                 }
                   11027:             }
                   11028:             if (defined($$types{'future'})) {
1.609     raeburn  11029:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  11030:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  11031:                     $match = 1;
1.275     raeburn  11032:                 }
                   11033:             }
1.609     raeburn  11034:             if ($match) {
                   11035:                 push(@{$seclists{$student}},$section);
                   11036:                 if (ref($userdata) eq 'HASH') {
                   11037:                     $$userdata{$student} = $$classlist{$student};
                   11038:                 }
                   11039:                 if (ref($statushash) eq 'HASH') {
                   11040:                     $statushash->{$student}{'st'}{$section} = $status;
                   11041:                 }
1.288     raeburn  11042:             }
1.275     raeburn  11043:         }
                   11044:     }
1.412     raeburn  11045:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  11046:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11047:         my $now = time;
1.609     raeburn  11048:         my %displaystatus = ( previous => 'Expired',
                   11049:                               active   => 'Active',
                   11050:                               future   => 'Future',
                   11051:                             );
1.1121    raeburn  11052:         my (%nothide,@possdoms);
1.630     raeburn  11053:         if ($hidepriv) {
                   11054:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   11055:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   11056:                 if ($user !~ /:/) {
                   11057:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   11058:                 } else {
                   11059:                     $nothide{$user} = 1;
                   11060:                 }
                   11061:             }
1.1121    raeburn  11062:             my @possdoms = ($cdom);
                   11063:             if ($coursehash{'checkforpriv'}) {
                   11064:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   11065:             }
1.630     raeburn  11066:         }
1.439     raeburn  11067:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  11068:             my $match = 0;
1.412     raeburn  11069:             my $secmatch = 0;
1.439     raeburn  11070:             my $status;
1.412     raeburn  11071:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  11072:             $user =~ s/:$//;
1.439     raeburn  11073:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   11074:             if ($end == -1 || $start == -1) {
                   11075:                 next;
                   11076:             }
                   11077:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   11078:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  11079:                 my ($uname,$udom) = split(/:/,$user);
                   11080:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 11081:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  11082:                         $secmatch = 1;
                   11083:                     } elsif ($usec eq '') {
1.420     albertel 11084:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  11085:                             $secmatch = 1;
                   11086:                         }
                   11087:                     } else {
                   11088:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   11089:                             $secmatch = 1;
                   11090:                         }
                   11091:                     }
                   11092:                     if (!$secmatch) {
                   11093:                         next;
                   11094:                     }
1.288     raeburn  11095:                 }
1.419     raeburn  11096:                 if ($usec eq '') {
                   11097:                     $usec = 'none';
                   11098:                 }
1.275     raeburn  11099:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  11100:                     if ($hidepriv) {
1.1121    raeburn  11101:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  11102:                             (!$nothide{$uname.':'.$udom})) {
                   11103:                             next;
                   11104:                         }
                   11105:                     }
1.503     raeburn  11106:                     if ($end > 0 && $end < $now) {
1.439     raeburn  11107:                         $status = 'previous';
                   11108:                     } elsif ($start > $now) {
                   11109:                         $status = 'future';
                   11110:                     } else {
                   11111:                         $status = 'active';
                   11112:                     }
1.277     albertel 11113:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  11114:                         if ($status eq $type) {
1.420     albertel 11115:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  11116:                                 push(@{$$users{$role}{$user}},$type);
                   11117:                             }
1.288     raeburn  11118:                             $match = 1;
                   11119:                         }
                   11120:                     }
1.419     raeburn  11121:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   11122:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   11123: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   11124:                         }
1.420     albertel 11125:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  11126:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   11127:                         }
1.609     raeburn  11128:                         if (ref($statushash) eq 'HASH') {
                   11129:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   11130:                         }
1.275     raeburn  11131:                     }
                   11132:                 }
                   11133:             }
                   11134:         }
1.290     albertel 11135:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  11136:             if ((defined($cdom)) && (defined($cnum))) {
                   11137:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   11138:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   11139:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  11140:                     next if ($owner eq '');
                   11141:                     my ($ownername,$ownerdom);
                   11142:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   11143:                         $ownername = $1;
                   11144:                         $ownerdom = $2;
                   11145:                     } else {
                   11146:                         $ownername = $owner;
                   11147:                         $ownerdom = $cdom;
                   11148:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  11149:                     }
                   11150:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 11151:                     if (defined($userdata) && 
1.609     raeburn  11152: 			!exists($$userdata{$owner})) {
                   11153: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   11154:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   11155:                             push(@{$seclists{$owner}},'none');
                   11156:                         }
                   11157:                         if (ref($statushash) eq 'HASH') {
                   11158:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  11159:                         }
1.290     albertel 11160: 		    }
1.279     raeburn  11161:                 }
                   11162:             }
                   11163:         }
1.419     raeburn  11164:         foreach my $user (keys(%seclists)) {
                   11165:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   11166:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   11167:         }
1.275     raeburn  11168:     }
                   11169:     return;
                   11170: }
                   11171: 
1.288     raeburn  11172: sub get_user_info {
                   11173:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 11174:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   11175: 	&plainname($uname,$udom,'lastname');
1.291     albertel 11176:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  11177:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  11178:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   11179:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  11180:     return;
                   11181: }
1.275     raeburn  11182: 
1.472     raeburn  11183: ###############################################
                   11184: 
                   11185: =pod
                   11186: 
                   11187: =item * &get_user_quota()
                   11188: 
1.1134    raeburn  11189: Retrieves quota assigned for storage of user files.
                   11190: Default is to report quota for portfolio files.
1.472     raeburn  11191: 
                   11192: Incoming parameters:
                   11193: 1. user's username
                   11194: 2. user's domain
1.1134    raeburn  11195: 3. quota name - portfolio, author, or course
1.1136    raeburn  11196:    (if no quota name provided, defaults to portfolio).
1.1237    raeburn  11197: 4. crstype - official, unofficial, textbook, placement or community, 
                   11198:    if quota name is course
1.472     raeburn  11199: 
                   11200: Returns:
1.1163    raeburn  11201: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  11202: 2. (Optional) Type of setting: custom or default
                   11203:    (individually assigned or default for user's 
                   11204:    institutional status).
                   11205: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   11206:    or student - types as defined in localenroll::inst_usertypes 
                   11207:    for user's domain, which determines default quota for user.
                   11208: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  11209: 
                   11210: If a value has been stored in the user's environment, 
1.536     raeburn  11211: it will return that, otherwise it returns the maximal default
1.1134    raeburn  11212: defined for the user's institutional status(es) in the domain.
1.472     raeburn  11213: 
                   11214: =cut
                   11215: 
                   11216: ###############################################
                   11217: 
                   11218: 
                   11219: sub get_user_quota {
1.1136    raeburn  11220:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  11221:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  11222:     if (!defined($udom)) {
                   11223:         $udom = $env{'user.domain'};
                   11224:     }
                   11225:     if (!defined($uname)) {
                   11226:         $uname = $env{'user.name'};
                   11227:     }
                   11228:     if (($udom eq '' || $uname eq '') ||
                   11229:         ($udom eq 'public') && ($uname eq 'public')) {
                   11230:         $quota = 0;
1.536     raeburn  11231:         $quotatype = 'default';
                   11232:         $defquota = 0; 
1.472     raeburn  11233:     } else {
1.536     raeburn  11234:         my $inststatus;
1.1134    raeburn  11235:         if ($quotaname eq 'course') {
                   11236:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   11237:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   11238:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   11239:             } else {
                   11240:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   11241:                 $quota = $cenv{'internal.uploadquota'};
                   11242:             }
1.536     raeburn  11243:         } else {
1.1134    raeburn  11244:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   11245:                 if ($quotaname eq 'author') {
                   11246:                     $quota = $env{'environment.authorquota'};
                   11247:                 } else {
                   11248:                     $quota = $env{'environment.portfolioquota'};
                   11249:                 }
                   11250:                 $inststatus = $env{'environment.inststatus'};
                   11251:             } else {
                   11252:                 my %userenv = 
                   11253:                     &Apache::lonnet::get('environment',['portfolioquota',
                   11254:                                          'authorquota','inststatus'],$udom,$uname);
                   11255:                 my ($tmp) = keys(%userenv);
                   11256:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   11257:                     if ($quotaname eq 'author') {
                   11258:                         $quota = $userenv{'authorquota'};
                   11259:                     } else {
                   11260:                         $quota = $userenv{'portfolioquota'};
                   11261:                     }
                   11262:                     $inststatus = $userenv{'inststatus'};
                   11263:                 } else {
                   11264:                     undef(%userenv);
                   11265:                 }
                   11266:             }
                   11267:         }
                   11268:         if ($quota eq '' || wantarray) {
                   11269:             if ($quotaname eq 'course') {
                   11270:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  11271:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
1.1237    raeburn  11272:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
                   11273:                     ($crstype eq 'placement')) { 
1.1136    raeburn  11274:                     $defquota = $domdefs{$crstype.'quota'};
                   11275:                 }
                   11276:                 if ($defquota eq '') {
                   11277:                     $defquota = 500;
                   11278:                 }
1.1134    raeburn  11279:             } else {
                   11280:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   11281:             }
                   11282:             if ($quota eq '') {
                   11283:                 $quota = $defquota;
                   11284:                 $quotatype = 'default';
                   11285:             } else {
                   11286:                 $quotatype = 'custom';
                   11287:             }
1.472     raeburn  11288:         }
                   11289:     }
1.536     raeburn  11290:     if (wantarray) {
                   11291:         return ($quota,$quotatype,$settingstatus,$defquota);
                   11292:     } else {
                   11293:         return $quota;
                   11294:     }
1.472     raeburn  11295: }
                   11296: 
                   11297: ###############################################
                   11298: 
                   11299: =pod
                   11300: 
                   11301: =item * &default_quota()
                   11302: 
1.536     raeburn  11303: Retrieves default quota assigned for storage of user portfolio files,
                   11304: given an (optional) user's institutional status.
1.472     raeburn  11305: 
                   11306: Incoming parameters:
1.1142    raeburn  11307: 
1.472     raeburn  11308: 1. domain
1.536     raeburn  11309: 2. (Optional) institutional status(es).  This is a : separated list of 
                   11310:    status types (e.g., faculty, staff, student etc.)
                   11311:    which apply to the user for whom the default is being retrieved.
                   11312:    If the institutional status string in undefined, the domain
1.1134    raeburn  11313:    default quota will be returned.
                   11314: 3.  quota name - portfolio, author, or course
                   11315:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  11316: 
                   11317: Returns:
1.1142    raeburn  11318: 
1.1163    raeburn  11319: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  11320: 2. (Optional) institutional type which determined the value of the
                   11321:    default quota.
1.472     raeburn  11322: 
                   11323: If a value has been stored in the domain's configuration db,
                   11324: it will return that, otherwise it returns 20 (for backwards 
                   11325: compatibility with domains which have not set up a configuration
1.1163    raeburn  11326: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  11327: 
1.536     raeburn  11328: If the user's status includes multiple types (e.g., staff and student),
                   11329: the largest default quota which applies to the user determines the
                   11330: default quota returned.
                   11331: 
1.472     raeburn  11332: =cut
                   11333: 
                   11334: ###############################################
                   11335: 
                   11336: 
                   11337: sub default_quota {
1.1134    raeburn  11338:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  11339:     my ($defquota,$settingstatus);
                   11340:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  11341:                                             ['quotas'],$udom);
1.1134    raeburn  11342:     my $key = 'defaultquota';
                   11343:     if ($quotaname eq 'author') {
                   11344:         $key = 'authorquota';
                   11345:     }
1.622     raeburn  11346:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  11347:         if ($inststatus ne '') {
1.765     raeburn  11348:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  11349:             foreach my $item (@statuses) {
1.1134    raeburn  11350:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11351:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  11352:                         if ($defquota eq '') {
1.1134    raeburn  11353:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11354:                             $settingstatus = $item;
1.1134    raeburn  11355:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   11356:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  11357:                             $settingstatus = $item;
                   11358:                         }
                   11359:                     }
1.1134    raeburn  11360:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  11361:                     if ($quotahash{'quotas'}{$item} ne '') {
                   11362:                         if ($defquota eq '') {
                   11363:                             $defquota = $quotahash{'quotas'}{$item};
                   11364:                             $settingstatus = $item;
                   11365:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   11366:                             $defquota = $quotahash{'quotas'}{$item};
                   11367:                             $settingstatus = $item;
                   11368:                         }
1.536     raeburn  11369:                     }
                   11370:                 }
                   11371:             }
                   11372:         }
                   11373:         if ($defquota eq '') {
1.1134    raeburn  11374:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   11375:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   11376:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  11377:                 $defquota = $quotahash{'quotas'}{'default'};
                   11378:             }
1.536     raeburn  11379:             $settingstatus = 'default';
1.1139    raeburn  11380:             if ($defquota eq '') {
                   11381:                 if ($quotaname eq 'author') {
                   11382:                     $defquota = 500;
                   11383:                 }
                   11384:             }
1.536     raeburn  11385:         }
                   11386:     } else {
                   11387:         $settingstatus = 'default';
1.1134    raeburn  11388:         if ($quotaname eq 'author') {
                   11389:             $defquota = 500;
                   11390:         } else {
                   11391:             $defquota = 20;
                   11392:         }
1.536     raeburn  11393:     }
                   11394:     if (wantarray) {
                   11395:         return ($defquota,$settingstatus);
1.472     raeburn  11396:     } else {
1.536     raeburn  11397:         return $defquota;
1.472     raeburn  11398:     }
                   11399: }
                   11400: 
1.1135    raeburn  11401: ###############################################
                   11402: 
                   11403: =pod
                   11404: 
1.1136    raeburn  11405: =item * &excess_filesize_warning()
1.1135    raeburn  11406: 
                   11407: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  11408: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  11409: space to be exceeded.
1.1136    raeburn  11410: 
                   11411: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  11412: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  11413: 
1.1165    raeburn  11414: Inputs: 7 
1.1136    raeburn  11415: 1. username or coursenum
1.1135    raeburn  11416: 2. domain
1.1136    raeburn  11417: 3. context ('author' or 'course')
1.1135    raeburn  11418: 4. filename of file for which action is being requested
                   11419: 5. filesize (kB) of file
                   11420: 6. action being taken: copy or upload.
1.1237    raeburn  11421: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
1.1135    raeburn  11422: 
                   11423: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  11424:          otherwise return null.
                   11425: 
                   11426: =back
1.1135    raeburn  11427: 
                   11428: =cut
                   11429: 
1.1136    raeburn  11430: sub excess_filesize_warning {
1.1165    raeburn  11431:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  11432:     my $current_disk_usage = 0;
1.1165    raeburn  11433:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  11434:     if ($context eq 'author') {
                   11435:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   11436:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   11437:     } else {
                   11438:         foreach my $subdir ('docs','supplemental') {
                   11439:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   11440:         }
                   11441:     }
1.1135    raeburn  11442:     $disk_quota = int($disk_quota * 1000);
                   11443:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   11444:         return '<p class="LC_warning">'.
1.1135    raeburn  11445:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   11446:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   11447:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  11448:                             $disk_quota,$current_disk_usage).
                   11449:                '</p>';
                   11450:     }
                   11451:     return;
                   11452: }
                   11453: 
                   11454: ###############################################
                   11455: 
                   11456: 
1.1136    raeburn  11457: 
                   11458: 
1.384     raeburn  11459: sub get_secgrprole_info {
                   11460:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   11461:     my %sections_count = &get_sections($cdom,$cnum);
                   11462:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   11463:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   11464:     my @groups = sort(keys(%curr_groups));
                   11465:     my $allroles = [];
                   11466:     my $rolehash;
                   11467:     my $accesshash = {
                   11468:                      active => 'Currently has access',
                   11469:                      future => 'Will have future access',
                   11470:                      previous => 'Previously had access',
                   11471:                   };
                   11472:     if ($needroles) {
                   11473:         $rolehash = {'all' => 'all'};
1.385     albertel 11474:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   11475: 	if (&Apache::lonnet::error(%user_roles)) {
                   11476: 	    undef(%user_roles);
                   11477: 	}
                   11478:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  11479:             my ($role)=split(/\:/,$item,2);
                   11480:             if ($role eq 'cr') { next; }
                   11481:             if ($role =~ /^cr/) {
                   11482:                 $$rolehash{$role} = (split('/',$role))[3];
                   11483:             } else {
                   11484:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   11485:             }
                   11486:         }
                   11487:         foreach my $key (sort(keys(%{$rolehash}))) {
                   11488:             push(@{$allroles},$key);
                   11489:         }
                   11490:         push (@{$allroles},'st');
                   11491:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   11492:     }
                   11493:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   11494: }
                   11495: 
1.555     raeburn  11496: sub user_picker {
1.1279    raeburn  11497:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  11498:     my $currdom = $dom;
1.1253    raeburn  11499:     my @alldoms = &Apache::lonnet::all_domains();
                   11500:     if (@alldoms == 1) {
                   11501:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   11502:                                                ['directorysrch'],$alldoms[0]);
                   11503:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   11504:         my $showdom = $domdesc;
                   11505:         if ($showdom eq '') {
                   11506:             $showdom = $dom;
                   11507:         }
                   11508:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   11509:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   11510:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   11511:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   11512:             }
                   11513:         }
                   11514:     }
1.555     raeburn  11515:     my %curr_selected = (
                   11516:                         srchin => 'dom',
1.580     raeburn  11517:                         srchby => 'lastname',
1.555     raeburn  11518:                       );
                   11519:     my $srchterm;
1.625     raeburn  11520:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  11521:         if ($srch->{'srchby'} ne '') {
                   11522:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   11523:         }
                   11524:         if ($srch->{'srchin'} ne '') {
                   11525:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   11526:         }
                   11527:         if ($srch->{'srchtype'} ne '') {
                   11528:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   11529:         }
                   11530:         if ($srch->{'srchdomain'} ne '') {
                   11531:             $currdom = $srch->{'srchdomain'};
                   11532:         }
                   11533:         $srchterm = $srch->{'srchterm'};
                   11534:     }
1.1222    damieng  11535:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  11536:                     'usr'       => 'Search criteria',
1.563     raeburn  11537:                     'doma'      => 'Domain/institution to search',
1.558     albertel 11538:                     'uname'     => 'username',
                   11539:                     'lastname'  => 'last name',
1.555     raeburn  11540:                     'lastfirst' => 'last name, first name',
1.558     albertel 11541:                     'crs'       => 'in this course',
1.576     raeburn  11542:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 11543:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  11544:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 11545:                     'exact'     => 'is',
                   11546:                     'contains'  => 'contains',
1.569     raeburn  11547:                     'begins'    => 'begins with',
1.1222    damieng  11548:                                        );
                   11549:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  11550:                     'youm'      => "You must include some text to search for.",
                   11551:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   11552:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   11553:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   11554:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   11555:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   11556:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   11557:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  11558:                                        );
1.1222    damieng  11559:     &html_escape(\%html_lt);
                   11560:     &js_escape(\%js_lt);
1.1255    raeburn  11561:     my $domform;
1.1277    raeburn  11562:     my $allow_blank = 1;
1.1255    raeburn  11563:     if ($fixeddom) {
1.1277    raeburn  11564:         $allow_blank = 0;
                   11565:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1255    raeburn  11566:     } else {
1.1287    raeburn  11567:         my $defdom = $env{'request.role.domain'};
1.1288    raeburn  11568:         my ($trusted,$untrusted);
1.1287    raeburn  11569:         if (($context eq 'requestcrs') || ($context eq 'course')) {
1.1288    raeburn  11570:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
1.1287    raeburn  11571:         } elsif ($context eq 'author') {
1.1288    raeburn  11572:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
1.1287    raeburn  11573:         } elsif ($context eq 'domain') {
1.1288    raeburn  11574:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
1.1287    raeburn  11575:         }
1.1288    raeburn  11576:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
1.1255    raeburn  11577:     }
1.563     raeburn  11578:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  11579: 
                   11580:     my @srchins = ('crs','dom','alc','instd');
                   11581: 
                   11582:     foreach my $option (@srchins) {
                   11583:         # FIXME 'alc' option unavailable until 
                   11584:         #       loncreateuser::print_user_query_page()
                   11585:         #       has been completed.
                   11586:         next if ($option eq 'alc');
1.880     raeburn  11587:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  11588:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1279    raeburn  11589:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  11590:         if ($curr_selected{'srchin'} eq $option) {
                   11591:             $srchinsel .= ' 
1.1222    damieng  11592:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  11593:         } else {
                   11594:             $srchinsel .= '
1.1222    damieng  11595:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  11596:         }
1.555     raeburn  11597:     }
1.563     raeburn  11598:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  11599: 
                   11600:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  11601:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  11602:         if ($curr_selected{'srchby'} eq $option) {
                   11603:             $srchbysel .= '
1.1222    damieng  11604:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11605:         } else {
                   11606:             $srchbysel .= '
1.1222    damieng  11607:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11608:          }
                   11609:     }
                   11610:     $srchbysel .= "\n  </select>\n";
                   11611: 
                   11612:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  11613:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  11614:         if ($curr_selected{'srchtype'} eq $option) {
                   11615:             $srchtypesel .= '
1.1222    damieng  11616:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  11617:         } else {
                   11618:             $srchtypesel .= '
1.1222    damieng  11619:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  11620:         }
                   11621:     }
                   11622:     $srchtypesel .= "\n  </select>\n";
                   11623: 
1.558     albertel 11624:     my ($newuserscript,$new_user_create);
1.994     raeburn  11625:     my $context_dom = $env{'request.role.domain'};
                   11626:     if ($context eq 'requestcrs') {
                   11627:         if ($env{'form.coursedom'} ne '') { 
                   11628:             $context_dom = $env{'form.coursedom'};
                   11629:         }
                   11630:     }
1.556     raeburn  11631:     if ($forcenewuser) {
1.576     raeburn  11632:         if (ref($srch) eq 'HASH') {
1.994     raeburn  11633:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  11634:                 if ($cancreate) {
                   11635:                     $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>';
                   11636:                 } else {
1.799     bisitz   11637:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  11638:                     my %usertypetext = (
                   11639:                         official   => 'institutional',
                   11640:                         unofficial => 'non-institutional',
                   11641:                     );
1.799     bisitz   11642:                     $new_user_create = '<p class="LC_warning">'
                   11643:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   11644:                                       .' '
                   11645:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   11646:                                           ,'<a href="'.$helplink.'">','</a>')
                   11647:                                       .'</p><br />';
1.627     raeburn  11648:                 }
1.576     raeburn  11649:             }
                   11650:         }
                   11651: 
1.556     raeburn  11652:         $newuserscript = <<"ENDSCRIPT";
                   11653: 
1.570     raeburn  11654: function setSearch(createnew,callingForm) {
1.556     raeburn  11655:     if (createnew == 1) {
1.570     raeburn  11656:         for (var i=0; i<callingForm.srchby.length; i++) {
                   11657:             if (callingForm.srchby.options[i].value == 'uname') {
                   11658:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  11659:             }
                   11660:         }
1.570     raeburn  11661:         for (var i=0; i<callingForm.srchin.length; i++) {
                   11662:             if ( callingForm.srchin.options[i].value == 'dom') {
                   11663: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  11664:             }
                   11665:         }
1.570     raeburn  11666:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   11667:             if (callingForm.srchtype.options[i].value == 'exact') {
                   11668:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  11669:             }
                   11670:         }
1.570     raeburn  11671:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  11672:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  11673:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  11674:             }
                   11675:         }
                   11676:     }
                   11677: }
                   11678: ENDSCRIPT
1.558     albertel 11679: 
1.556     raeburn  11680:     }
                   11681: 
1.555     raeburn  11682:     my $output = <<"END_BLOCK";
1.556     raeburn  11683: <script type="text/javascript">
1.824     bisitz   11684: // <![CDATA[
1.570     raeburn  11685: function validateEntry(callingForm) {
1.558     albertel 11686: 
1.556     raeburn  11687:     var checkok = 1;
1.558     albertel 11688:     var srchin;
1.570     raeburn  11689:     for (var i=0; i<callingForm.srchin.length; i++) {
                   11690: 	if ( callingForm.srchin[i].checked ) {
                   11691: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 11692: 	}
                   11693:     }
                   11694: 
1.570     raeburn  11695:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   11696:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   11697:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   11698:     var srchterm =  callingForm.srchterm.value;
                   11699:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  11700:     var msg = "";
                   11701: 
                   11702:     if (srchterm == "") {
                   11703:         checkok = 0;
1.1222    damieng  11704:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  11705:     }
                   11706: 
1.569     raeburn  11707:     if (srchtype== 'begins') {
                   11708:         if (srchterm.length < 2) {
                   11709:             checkok = 0;
1.1222    damieng  11710:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  11711:         }
                   11712:     }
                   11713: 
1.556     raeburn  11714:     if (srchtype== 'contains') {
                   11715:         if (srchterm.length < 3) {
                   11716:             checkok = 0;
1.1222    damieng  11717:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  11718:         }
                   11719:     }
                   11720:     if (srchin == 'instd') {
                   11721:         if (srchdomain == '') {
                   11722:             checkok = 0;
1.1222    damieng  11723:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  11724:         }
                   11725:     }
                   11726:     if (srchin == 'dom') {
                   11727:         if (srchdomain == '') {
                   11728:             checkok = 0;
1.1222    damieng  11729:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  11730:         }
                   11731:     }
                   11732:     if (srchby == 'lastfirst') {
                   11733:         if (srchterm.indexOf(",") == -1) {
                   11734:             checkok = 0;
1.1222    damieng  11735:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  11736:         }
                   11737:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   11738:             checkok = 0;
1.1222    damieng  11739:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  11740:         }
                   11741:     }
                   11742:     if (checkok == 0) {
1.1222    damieng  11743:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  11744:         return;
                   11745:     }
                   11746:     if (checkok == 1) {
1.570     raeburn  11747:         callingForm.submit();
1.556     raeburn  11748:     }
                   11749: }
                   11750: 
                   11751: $newuserscript
                   11752: 
1.824     bisitz   11753: // ]]>
1.556     raeburn  11754: </script>
1.558     albertel 11755: 
                   11756: $new_user_create
                   11757: 
1.555     raeburn  11758: END_BLOCK
1.558     albertel 11759: 
1.876     raeburn  11760:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1222    damieng  11761:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  11762:                $domform.
                   11763:                &Apache::lonhtmlcommon::row_closure().
1.1222    damieng  11764:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  11765:                $srchbysel.
                   11766:                $srchtypesel. 
                   11767:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   11768:                $srchinsel.
                   11769:                &Apache::lonhtmlcommon::row_closure(1). 
                   11770:                &Apache::lonhtmlcommon::end_pick_box().
                   11771:                '<br />';
1.1253    raeburn  11772:     return ($output,1);
1.555     raeburn  11773: }
                   11774: 
1.612     raeburn  11775: sub user_rule_check {
1.615     raeburn  11776:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1226    raeburn  11777:     my ($response,%inst_response);
1.612     raeburn  11778:     if (ref($usershash) eq 'HASH') {
1.1226    raeburn  11779:         if (keys(%{$usershash}) > 1) {
                   11780:             my (%by_username,%by_id,%userdoms);
                   11781:             my $checkid; 
                   11782:             if (ref($checks) eq 'HASH') {
                   11783:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   11784:                     $checkid = 1;
                   11785:                 }
                   11786:             }
                   11787:             foreach my $user (keys(%{$usershash})) {
                   11788:                 my ($uname,$udom) = split(/:/,$user);
                   11789:                 if ($checkid) {
                   11790:                     if (ref($usershash->{$user}) eq 'HASH') {
                   11791:                         if ($usershash->{$user}->{'id'} ne '') {
1.1227    raeburn  11792:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
1.1226    raeburn  11793:                             $userdoms{$udom} = 1;
1.1227    raeburn  11794:                             if (ref($inst_results) eq 'HASH') {
                   11795:                                 $inst_results->{$uname.':'.$udom} = {};
                   11796:                             }
1.1226    raeburn  11797:                         }
                   11798:                     }
                   11799:                 } else {
                   11800:                     $by_username{$udom}{$uname} = 1;
                   11801:                     $userdoms{$udom} = 1;
1.1227    raeburn  11802:                     if (ref($inst_results) eq 'HASH') {
                   11803:                         $inst_results->{$uname.':'.$udom} = {};
                   11804:                     }
1.1226    raeburn  11805:                 }
                   11806:             }
                   11807:             foreach my $udom (keys(%userdoms)) {
                   11808:                 if (!$got_rules->{$udom}) {
                   11809:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11810:                                                              ['usercreation'],$udom);
                   11811:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11812:                         foreach my $item ('username','id') {
                   11813:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
1.1227    raeburn  11814:                                 $$curr_rules{$udom}{$item} =
                   11815:                                     $domconfig{'usercreation'}{$item.'_rule'};
1.1226    raeburn  11816:                             }
                   11817:                         }
                   11818:                     }
                   11819:                     $got_rules->{$udom} = 1;
                   11820:                 }
1.612     raeburn  11821:             }
1.1226    raeburn  11822:             if ($checkid) {
                   11823:                 foreach my $udom (keys(%by_id)) {
                   11824:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   11825:                     if ($outcome eq 'ok') {
1.1227    raeburn  11826:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   11827:                             my $uname = $by_id{$udom}{$id};
                   11828:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11829:                         }
1.1226    raeburn  11830:                         if (ref($results) eq 'HASH') {
                   11831:                             foreach my $uname (keys(%{$results})) {
1.1227    raeburn  11832:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   11833:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   11834:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11835:                                 }
1.1226    raeburn  11836:                             }
                   11837:                         }
                   11838:                     }
1.612     raeburn  11839:                 }
1.615     raeburn  11840:             } else {
1.1226    raeburn  11841:                 foreach my $udom (keys(%by_username)) {
                   11842:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   11843:                     if ($outcome eq 'ok') {
1.1227    raeburn  11844:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   11845:                             $inst_response{$uname.':'.$udom} = $outcome;
                   11846:                         }
1.1226    raeburn  11847:                         if (ref($results) eq 'HASH') {
                   11848:                             foreach my $uname (keys(%{$results})) {
                   11849:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   11850:                             }
                   11851:                         }
                   11852:                     }
                   11853:                 }
1.612     raeburn  11854:             }
1.1226    raeburn  11855:         } elsif (keys(%{$usershash}) == 1) {
                   11856:             my $user = (keys(%{$usershash}))[0];
                   11857:             my ($uname,$udom) = split(/:/,$user);
                   11858:             if (($udom ne '') && ($uname ne '')) {
                   11859:                 if (ref($usershash->{$user}) eq 'HASH') {
                   11860:                     if (ref($checks) eq 'HASH') {
                   11861:                         if (defined($checks->{'username'})) {
                   11862:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
                   11863:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   11864:                         } elsif (defined($checks->{'id'})) {
                   11865:                             if ($usershash->{$user}->{'id'} ne '') {
                   11866:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11867:                                     &Apache::lonnet::get_instuser($udom,undef,
                   11868:                                                                   $usershash->{$user}->{'id'});
                   11869:                             } else {
                   11870:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   11871:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   11872:                             }
1.585     raeburn  11873:                         }
1.1226    raeburn  11874:                     } else {
                   11875:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   11876:                             &Apache::lonnet::get_instuser($udom,$uname);
                   11877:                        return;
                   11878:                     }
                   11879:                     if (!$got_rules->{$udom}) {
                   11880:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   11881:                                                                  ['usercreation'],$udom);
                   11882:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   11883:                             foreach my $item ('username','id') {
                   11884:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   11885:                                    $$curr_rules{$udom}{$item} = 
                   11886:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   11887:                                 }
                   11888:                             }
                   11889:                         }
                   11890:                         $got_rules->{$udom} = 1;
1.585     raeburn  11891:                     }
                   11892:                 }
1.1226    raeburn  11893:             } else {
                   11894:                 return;
                   11895:             }
                   11896:         } else {
                   11897:             return;
                   11898:         }
                   11899:         foreach my $user (keys(%{$usershash})) {
                   11900:             my ($uname,$udom) = split(/:/,$user);
                   11901:             next if (($udom eq '') || ($uname eq ''));
                   11902:             my $id;
1.1227    raeburn  11903:             if (ref($inst_results) eq 'HASH') {
                   11904:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   11905:                     $id = $inst_results->{$user}->{'id'};
                   11906:                 }
                   11907:             }
                   11908:             if ($id eq '') { 
                   11909:                 if (ref($usershash->{$user})) {
                   11910:                     $id = $usershash->{$user}->{'id'};
                   11911:                 }
1.585     raeburn  11912:             }
1.612     raeburn  11913:             foreach my $item (keys(%{$checks})) {
                   11914:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   11915:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   11916:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1226    raeburn  11917:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   11918:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  11919:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   11920:                                 if ($rule_check{$rule}) {
                   11921:                                     $$rulematch{$user}{$item} = $rule;
1.1226    raeburn  11922:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  11923:                                         if (ref($inst_results) eq 'HASH') {
                   11924:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   11925:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   11926:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1227    raeburn  11927:                                                 } elsif ($item eq 'id') {
                   11928:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   11929:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   11930:                                                     }
1.615     raeburn  11931:                                                 }
1.612     raeburn  11932:                                             }
                   11933:                                         }
1.615     raeburn  11934:                                     }
                   11935:                                     last;
1.585     raeburn  11936:                                 }
                   11937:                             }
                   11938:                         }
                   11939:                     }
                   11940:                 }
                   11941:             }
                   11942:         }
                   11943:     }
1.612     raeburn  11944:     return;
                   11945: }
                   11946: 
                   11947: sub user_rule_formats {
                   11948:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   11949:     my %text = ( 
                   11950:                  'username' => 'Usernames',
                   11951:                  'id'       => 'IDs',
                   11952:                );
                   11953:     my $output;
                   11954:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   11955:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   11956:         if (@{$ruleorder} > 0) {
1.1102    raeburn  11957:             $output = '<br />'.
                   11958:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   11959:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   11960:                       ' <ul>';
1.612     raeburn  11961:             foreach my $rule (@{$ruleorder}) {
                   11962:                 if (ref($curr_rules) eq 'ARRAY') {
                   11963:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   11964:                         if (ref($rules->{$rule}) eq 'HASH') {
                   11965:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   11966:                                         $rules->{$rule}{'desc'}.'</li>';
                   11967:                         }
                   11968:                     }
                   11969:                 }
                   11970:             }
                   11971:             $output .= '</ul>';
                   11972:         }
                   11973:     }
                   11974:     return $output;
                   11975: }
                   11976: 
                   11977: sub instrule_disallow_msg {
1.615     raeburn  11978:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  11979:     my $response;
                   11980:     my %text = (
                   11981:                   item   => 'username',
                   11982:                   items  => 'usernames',
                   11983:                   match  => 'matches',
                   11984:                   do     => 'does',
                   11985:                   action => 'a username',
                   11986:                   one    => 'one',
                   11987:                );
                   11988:     if ($count > 1) {
                   11989:         $text{'item'} = 'usernames';
                   11990:         $text{'match'} ='match';
                   11991:         $text{'do'} = 'do';
                   11992:         $text{'action'} = 'usernames',
                   11993:         $text{'one'} = 'ones';
                   11994:     }
                   11995:     if ($checkitem eq 'id') {
                   11996:         $text{'items'} = 'IDs';
                   11997:         $text{'item'} = 'ID';
                   11998:         $text{'action'} = 'an ID';
1.615     raeburn  11999:         if ($count > 1) {
                   12000:             $text{'item'} = 'IDs';
                   12001:             $text{'action'} = 'IDs';
                   12002:         }
1.612     raeburn  12003:     }
1.674     bisitz   12004:     $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  12005:     if ($mode eq 'upload') {
                   12006:         if ($checkitem eq 'username') {
                   12007:             $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'}.");
                   12008:         } elsif ($checkitem eq 'id') {
1.674     bisitz   12009:             $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  12010:         }
1.669     raeburn  12011:     } elsif ($mode eq 'selfcreate') {
                   12012:         if ($checkitem eq 'id') {
                   12013:             $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.");
                   12014:         }
1.615     raeburn  12015:     } else {
                   12016:         if ($checkitem eq 'username') {
                   12017:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   12018:         } elsif ($checkitem eq 'id') {
                   12019:             $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.");
                   12020:         }
1.612     raeburn  12021:     }
                   12022:     return $response;
1.585     raeburn  12023: }
                   12024: 
1.624     raeburn  12025: sub personal_data_fieldtitles {
                   12026:     my %fieldtitles = &Apache::lonlocal::texthash (
                   12027:                         id => 'Student/Employee ID',
                   12028:                         permanentemail => 'E-mail address',
                   12029:                         lastname => 'Last Name',
                   12030:                         firstname => 'First Name',
                   12031:                         middlename => 'Middle Name',
                   12032:                         generation => 'Generation',
                   12033:                         gen => 'Generation',
1.765     raeburn  12034:                         inststatus => 'Affiliation',
1.624     raeburn  12035:                    );
                   12036:     return %fieldtitles;
                   12037: }
                   12038: 
1.642     raeburn  12039: sub sorted_inst_types {
                   12040:     my ($dom) = @_;
1.1185    raeburn  12041:     my ($usertypes,$order);
                   12042:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   12043:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   12044:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   12045:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   12046:     } else {
                   12047:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   12048:     }
1.642     raeburn  12049:     my $othertitle = &mt('All users');
                   12050:     if ($env{'request.course.id'}) {
1.668     raeburn  12051:         $othertitle  = &mt('Any users');
1.642     raeburn  12052:     }
                   12053:     my @types;
                   12054:     if (ref($order) eq 'ARRAY') {
                   12055:         @types = @{$order};
                   12056:     }
                   12057:     if (@types == 0) {
                   12058:         if (ref($usertypes) eq 'HASH') {
                   12059:             @types = sort(keys(%{$usertypes}));
                   12060:         }
                   12061:     }
                   12062:     if (keys(%{$usertypes}) > 0) {
                   12063:         $othertitle = &mt('Other users');
                   12064:     }
                   12065:     return ($othertitle,$usertypes,\@types);
                   12066: }
                   12067: 
1.645     raeburn  12068: sub get_institutional_codes {
1.1361    raeburn  12069:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
1.645     raeburn  12070: # Get complete list of course sections to update
                   12071:     my @currsections = ();
                   12072:     my @currxlists = ();
1.1361    raeburn  12073:     my (%unclutteredsec,%unclutteredlcsec);
1.645     raeburn  12074:     my $coursecode = $$settings{'internal.coursecode'};
1.1361    raeburn  12075:     my $crskey = $crs.':'.$coursecode;
                   12076:     @{$unclutteredsec{$crskey}} = ();
                   12077:     @{$unclutteredlcsec{$crskey}} = ();
1.645     raeburn  12078: 
                   12079:     if ($$settings{'internal.sectionnums'} ne '') {
                   12080:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   12081:     }
                   12082: 
                   12083:     if ($$settings{'internal.crosslistings'} ne '') {
                   12084:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   12085:     }
                   12086: 
                   12087:     if (@currxlists > 0) {
1.1361    raeburn  12088:         foreach my $xl (@currxlists) {
                   12089:             if ($xl =~ /^([^:]+):(\w*)$/) {
1.645     raeburn  12090:                 unless (grep/^$1$/,@{$allcourses}) {
1.1263    raeburn  12091:                     push(@{$allcourses},$1);
1.645     raeburn  12092:                     $$LC_code{$1} = $2;
                   12093:                 }
                   12094:             }
                   12095:         }
                   12096:     }
1.1361    raeburn  12097: 
1.645     raeburn  12098:     if (@currsections > 0) {
1.1361    raeburn  12099:         foreach my $sec (@currsections) {
                   12100:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
                   12101:                 my $instsec = $1;
1.645     raeburn  12102:                 my $lc_sec = $2;
1.1361    raeburn  12103:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
                   12104:                     push(@{$unclutteredsec{$crskey}},$instsec);
                   12105:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
                   12106:                 }
                   12107:             }
                   12108:         }
                   12109:     }
                   12110: 
                   12111:     if (@{$unclutteredsec{$crskey}} > 0) {
                   12112:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
                   12113:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
                   12114:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
                   12115:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
                   12116:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
1.1263    raeburn  12117:                     push(@{$allcourses},$sec);
1.1361    raeburn  12118:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
1.645     raeburn  12119:                 }
                   12120:             }
                   12121:         }
                   12122:     }
                   12123:     return;
                   12124: }
                   12125: 
1.971     raeburn  12126: sub get_standard_codeitems {
                   12127:     return ('Year','Semester','Department','Number','Section');
                   12128: }
                   12129: 
1.112     bowersj2 12130: =pod
                   12131: 
1.780     raeburn  12132: =head1 Slot Helpers
                   12133: 
                   12134: =over 4
                   12135: 
                   12136: =item * sorted_slots()
                   12137: 
1.1040    raeburn  12138: Sorts an array of slot names in order of an optional sort key,
                   12139: default sort is by slot start time (earliest first). 
1.780     raeburn  12140: 
                   12141: Inputs:
                   12142: 
                   12143: =over 4
                   12144: 
                   12145: slotsarr  - Reference to array of unsorted slot names.
                   12146: 
                   12147: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   12148: 
1.1040    raeburn  12149: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   12150: 
1.549     albertel 12151: =back
                   12152: 
1.780     raeburn  12153: Returns:
                   12154: 
                   12155: =over 4
                   12156: 
1.1040    raeburn  12157: sorted   - An array of slot names sorted by a specified sort key 
                   12158:            (default sort key is start time of the slot).
1.780     raeburn  12159: 
                   12160: =back
                   12161: 
                   12162: =cut
                   12163: 
                   12164: 
                   12165: sub sorted_slots {
1.1040    raeburn  12166:     my ($slotsarr,$slots,$sortkey) = @_;
                   12167:     if ($sortkey eq '') {
                   12168:         $sortkey = 'starttime';
                   12169:     }
1.780     raeburn  12170:     my @sorted;
                   12171:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   12172:         @sorted =
                   12173:             sort {
                   12174:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  12175:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  12176:                      }
                   12177:                      if (ref($slots->{$a})) { return -1;}
                   12178:                      if (ref($slots->{$b})) { return 1;}
                   12179:                      return 0;
                   12180:                  } @{$slotsarr};
                   12181:     }
                   12182:     return @sorted;
                   12183: }
                   12184: 
1.1040    raeburn  12185: =pod
                   12186: 
                   12187: =item * get_future_slots()
                   12188: 
                   12189: Inputs:
                   12190: 
                   12191: =over 4
                   12192: 
                   12193: cnum - course number
                   12194: 
                   12195: cdom - course domain
                   12196: 
                   12197: now - current UNIX time
                   12198: 
                   12199: symb - optional symb
                   12200: 
                   12201: =back
                   12202: 
                   12203: Returns:
                   12204: 
                   12205: =over 4
                   12206: 
                   12207: sorted_reservable - ref to array of student_schedulable slots currently 
                   12208:                     reservable, ordered by end date of reservation period.
                   12209: 
                   12210: reservable_now - ref to hash of student_schedulable slots currently
                   12211:                  reservable.
                   12212: 
                   12213:     Keys in inner hash are:
                   12214:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12215:     (b) endreserve: end date of reservation period.
                   12216:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12217:         selected.
1.1040    raeburn  12218: 
                   12219: sorted_future - ref to array of student_schedulable slots reservable in
                   12220:                 the future, ordered by start date of reservation period.
                   12221: 
                   12222: future_reservable - ref to hash of student_schedulable slots reservable
                   12223:                     in the future.
                   12224: 
                   12225:     Keys in inner hash are:
                   12226:     (a) symb: either blank or symb to which slot use is restricted.
1.1250    raeburn  12227:     (b) startreserve: start date of reservation period.
                   12228:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   12229:         selected.
1.1040    raeburn  12230: 
                   12231: =back
                   12232: 
                   12233: =cut
                   12234: 
                   12235: sub get_future_slots {
                   12236:     my ($cnum,$cdom,$now,$symb) = @_;
1.1229    raeburn  12237:     my $map;
                   12238:     if ($symb) {
                   12239:         ($map) = &Apache::lonnet::decode_symb($symb);
                   12240:     }
1.1040    raeburn  12241:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   12242:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   12243:     foreach my $slot (keys(%slots)) {
                   12244:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   12245:         if ($symb) {
1.1229    raeburn  12246:             if ($slots{$slot}->{'symb'} ne '') {
                   12247:                 my $canuse;
                   12248:                 my %oksymbs;
                   12249:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
                   12250:                 map { $oksymbs{$_} = 1; } @slotsymbs;
                   12251:                 if ($oksymbs{$symb}) {
                   12252:                     $canuse = 1;
                   12253:                 } else {
                   12254:                     foreach my $item (@slotsymbs) {
                   12255:                         if ($item =~ /\.(page|sequence)$/) {
                   12256:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
                   12257:                             if (($map ne '') && ($map eq $sloturl)) {
                   12258:                                 $canuse = 1;
                   12259:                                 last;
                   12260:                             }
                   12261:                         }
                   12262:                     }
                   12263:                 }
                   12264:                 next unless ($canuse);
                   12265:             }
1.1040    raeburn  12266:         }
                   12267:         if (($slots{$slot}->{'starttime'} > $now) &&
                   12268:             ($slots{$slot}->{'endtime'} > $now)) {
                   12269:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   12270:                 my $userallowed = 0;
                   12271:                 if ($slots{$slot}->{'allowedsections'}) {
                   12272:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   12273:                     if (!defined($env{'request.role.sec'})
                   12274:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   12275:                         $userallowed=1;
                   12276:                     } else {
                   12277:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   12278:                             $userallowed=1;
                   12279:                         }
                   12280:                     }
                   12281:                     unless ($userallowed) {
                   12282:                         if (defined($env{'request.course.groups'})) {
                   12283:                             my @groups = split(/:/,$env{'request.course.groups'});
                   12284:                             foreach my $group (@groups) {
                   12285:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   12286:                                     $userallowed=1;
                   12287:                                     last;
                   12288:                                 }
                   12289:                             }
                   12290:                         }
                   12291:                     }
                   12292:                 }
                   12293:                 if ($slots{$slot}->{'allowedusers'}) {
                   12294:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   12295:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   12296:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   12297:                         $userallowed = 1;
                   12298:                     }
                   12299:                 }
                   12300:                 next unless($userallowed);
                   12301:             }
                   12302:             my $startreserve = $slots{$slot}->{'startreserve'};
                   12303:             my $endreserve = $slots{$slot}->{'endreserve'};
                   12304:             my $symb = $slots{$slot}->{'symb'};
1.1250    raeburn  12305:             my $uniqueperiod;
                   12306:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   12307:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   12308:             }
1.1040    raeburn  12309:             if (($startreserve < $now) &&
                   12310:                 (!$endreserve || $endreserve > $now)) {
                   12311:                 my $lastres = $endreserve;
                   12312:                 if (!$lastres) {
                   12313:                     $lastres = $slots{$slot}->{'starttime'};
                   12314:                 }
                   12315:                 $reservable_now{$slot} = {
                   12316:                                            symb       => $symb,
1.1250    raeburn  12317:                                            endreserve => $lastres,
                   12318:                                            uniqueperiod => $uniqueperiod,
1.1040    raeburn  12319:                                          };
                   12320:             } elsif (($startreserve > $now) &&
                   12321:                      (!$endreserve || $endreserve > $startreserve)) {
                   12322:                 $future_reservable{$slot} = {
                   12323:                                               symb         => $symb,
1.1250    raeburn  12324:                                               startreserve => $startreserve,
                   12325:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  12326:                                             };
                   12327:             }
                   12328:         }
                   12329:     }
                   12330:     my @unsorted_reservable = keys(%reservable_now);
                   12331:     if (@unsorted_reservable > 0) {
                   12332:         @sorted_reservable = 
                   12333:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   12334:     }
                   12335:     my @unsorted_future = keys(%future_reservable);
                   12336:     if (@unsorted_future > 0) {
                   12337:         @sorted_future =
                   12338:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   12339:     }
                   12340:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   12341: }
1.780     raeburn  12342: 
                   12343: =pod
                   12344: 
1.1057    foxr     12345: =back
                   12346: 
1.549     albertel 12347: =head1 HTTP Helpers
                   12348: 
                   12349: =over 4
                   12350: 
1.648     raeburn  12351: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 12352: 
1.258     albertel 12353: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 12354: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 12355: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 12356: 
                   12357: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   12358: $possible_names is an ref to an array of form element names.  As an example:
                   12359: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 12360: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 12361: 
                   12362: =cut
1.1       albertel 12363: 
1.6       albertel 12364: sub get_unprocessed_cgi {
1.25      albertel 12365:   my ($query,$possible_names)= @_;
1.26      matthew  12366:   # $Apache::lonxml::debug=1;
1.356     albertel 12367:   foreach my $pair (split(/&/,$query)) {
                   12368:     my ($name, $value) = split(/=/,$pair);
1.369     www      12369:     $name = &unescape($name);
1.25      albertel 12370:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   12371:       $value =~ tr/+/ /;
                   12372:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 12373:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 12374:     }
1.16      harris41 12375:   }
1.6       albertel 12376: }
                   12377: 
1.112     bowersj2 12378: =pod
                   12379: 
1.648     raeburn  12380: =item * &cacheheader() 
1.112     bowersj2 12381: 
                   12382: returns cache-controlling header code
                   12383: 
                   12384: =cut
                   12385: 
1.7       albertel 12386: sub cacheheader {
1.258     albertel 12387:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 12388:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   12389:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 12390:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   12391:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 12392:     return $output;
1.7       albertel 12393: }
                   12394: 
1.112     bowersj2 12395: =pod
                   12396: 
1.648     raeburn  12397: =item * &no_cache($r) 
1.112     bowersj2 12398: 
                   12399: specifies header code to not have cache
                   12400: 
                   12401: =cut
                   12402: 
1.9       albertel 12403: sub no_cache {
1.216     albertel 12404:     my ($r) = @_;
                   12405:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 12406: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 12407:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   12408:     $r->no_cache(1);
                   12409:     $r->header_out("Expires" => $date);
                   12410:     $r->header_out("Pragma" => "no-cache");
1.123     www      12411: }
                   12412: 
                   12413: sub content_type {
1.181     albertel 12414:     my ($r,$type,$charset) = @_;
1.299     foxr     12415:     if ($r) {
                   12416: 	#  Note that printout.pl calls this with undef for $r.
                   12417: 	&no_cache($r);
                   12418:     }
1.258     albertel 12419:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 12420:     unless ($charset) {
                   12421: 	$charset=&Apache::lonlocal::current_encoding;
                   12422:     }
                   12423:     if ($charset) { $type.='; charset='.$charset; }
                   12424:     if ($r) {
                   12425: 	$r->content_type($type);
                   12426:     } else {
                   12427: 	print("Content-type: $type\n\n");
                   12428:     }
1.9       albertel 12429: }
1.25      albertel 12430: 
1.112     bowersj2 12431: =pod
                   12432: 
1.648     raeburn  12433: =item * &add_to_env($name,$value) 
1.112     bowersj2 12434: 
1.258     albertel 12435: adds $name to the %env hash with value
1.112     bowersj2 12436: $value, if $name already exists, the entry is converted to an array
                   12437: reference and $value is added to the array.
                   12438: 
                   12439: =cut
                   12440: 
1.25      albertel 12441: sub add_to_env {
                   12442:   my ($name,$value)=@_;
1.258     albertel 12443:   if (defined($env{$name})) {
                   12444:     if (ref($env{$name})) {
1.25      albertel 12445:       #already have multiple values
1.258     albertel 12446:       push(@{ $env{$name} },$value);
1.25      albertel 12447:     } else {
                   12448:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 12449:       my $first=$env{$name};
                   12450:       undef($env{$name});
                   12451:       push(@{ $env{$name} },$first,$value);
1.25      albertel 12452:     }
                   12453:   } else {
1.258     albertel 12454:     $env{$name}=$value;
1.25      albertel 12455:   }
1.31      albertel 12456: }
1.149     albertel 12457: 
                   12458: =pod
                   12459: 
1.648     raeburn  12460: =item * &get_env_multiple($name) 
1.149     albertel 12461: 
1.258     albertel 12462: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 12463: values may be defined and end up as an array ref.
                   12464: 
                   12465: returns an array of values
                   12466: 
                   12467: =cut
                   12468: 
                   12469: sub get_env_multiple {
                   12470:     my ($name) = @_;
                   12471:     my @values;
1.258     albertel 12472:     if (defined($env{$name})) {
1.149     albertel 12473:         # exists is it an array
1.258     albertel 12474:         if (ref($env{$name})) {
                   12475:             @values=@{ $env{$name} };
1.149     albertel 12476:         } else {
1.258     albertel 12477:             $values[0]=$env{$name};
1.149     albertel 12478:         }
                   12479:     }
                   12480:     return(@values);
                   12481: }
                   12482: 
1.1249    damieng  12483: # Looks at given dependencies, and returns something depending on the context.
                   12484: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
                   12485: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
                   12486: # For all other contexts, returns ($output, $counter, $numpathchg).
                   12487: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
                   12488: # $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.
                   12489: # $numpathchg: integer with the number of cleaned up dependency paths.
                   12490: # \%existing: hash reference clean path -> 1 only for existing dependencies.
                   12491: # \%mapping: hash reference clean path -> original path for all dependencies.
                   12492: # @param {string} actionurl - The path to the handler, indicative of the context.
                   12493: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
                   12494: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
                   12495: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
                   12496: # @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)
                   12497: # @return {Array} - array depending on the context (not a reference)
1.660     raeburn  12498: sub ask_for_embedded_content {
1.1249    damieng  12499:     # NOTE: documentation was added afterwards, it could be wrong
1.660     raeburn  12500:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  12501:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  12502:         %currsubfile,%unused,$rem);
1.1071    raeburn  12503:     my $counter = 0;
                   12504:     my $numnew = 0;
1.987     raeburn  12505:     my $numremref = 0;
                   12506:     my $numinvalid = 0;
                   12507:     my $numpathchg = 0;
                   12508:     my $numexisting = 0;
1.1071    raeburn  12509:     my $numunused = 0;
                   12510:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  12511:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  12512:     my $heading = &mt('Upload embedded files');
                   12513:     my $buttontext = &mt('Upload');
                   12514: 
1.1249    damieng  12515:     # fills these variables based on the context:
                   12516:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
                   12517:     # $path, $fileloc, $title, $rem, $filename
1.1085    raeburn  12518:     if ($env{'request.course.id'}) {
1.1123    raeburn  12519:         if ($actionurl eq '/adm/dependencies') {
                   12520:             $navmap = Apache::lonnavmaps::navmap->new();
                   12521:         }
                   12522:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12523:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  12524:     }
1.1123    raeburn  12525:     if (($actionurl eq '/adm/portfolio') || 
                   12526:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  12527:         my $current_path='/';
                   12528:         if ($env{'form.currentpath'}) {
                   12529:             $current_path = $env{'form.currentpath'};
                   12530:         }
                   12531:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  12532:             $udom = $cdom;
                   12533:             $uname = $cnum;
1.984     raeburn  12534:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   12535:         } else {
                   12536:             $udom = $env{'user.domain'};
                   12537:             $uname = $env{'user.name'};
                   12538:             $url = '/userfiles/portfolio';
                   12539:         }
1.987     raeburn  12540:         $toplevel = $url.'/';
1.984     raeburn  12541:         $url .= $current_path;
                   12542:         $getpropath = 1;
1.987     raeburn  12543:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   12544:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      12545:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  12546:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  12547:         $toplevel = $url;
1.984     raeburn  12548:         if ($rest ne '') {
1.987     raeburn  12549:             $url .= $rest;
                   12550:         }
                   12551:     } elsif ($actionurl eq '/adm/coursedocs') {
                   12552:         if (ref($args) eq 'HASH') {
1.1071    raeburn  12553:             $url = $args->{'docs_url'};
                   12554:             $toplevel = $url;
1.1084    raeburn  12555:             if ($args->{'context'} eq 'paste') {
                   12556:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   12557:                 ($path) = 
                   12558:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12559:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12560:                 $fileloc =~ s{^/}{};
                   12561:             }
1.1071    raeburn  12562:         }
1.1084    raeburn  12563:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  12564:         if ($env{'request.course.id'} ne '') {
                   12565:             if (ref($args) eq 'HASH') {
                   12566:                 $url = $args->{'docs_url'};
                   12567:                 $title = $args->{'docs_title'};
1.1126    raeburn  12568:                 $toplevel = $url; 
                   12569:                 unless ($toplevel =~ m{^/}) {
                   12570:                     $toplevel = "/$url";
                   12571:                 }
1.1085    raeburn  12572:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  12573:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   12574:                     $path = $1;
                   12575:                 } else {
                   12576:                     ($path) =
                   12577:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   12578:                 }
1.1195    raeburn  12579:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   12580:                     $fileloc = $toplevel;
                   12581:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   12582:                     my ($udom,$uname,$fname) =
                   12583:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   12584:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   12585:                 } else {
                   12586:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   12587:                 }
1.1071    raeburn  12588:                 $fileloc =~ s{^/}{};
                   12589:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   12590:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   12591:             }
1.987     raeburn  12592:         }
1.1123    raeburn  12593:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12594:         $udom = $cdom;
                   12595:         $uname = $cnum;
                   12596:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   12597:         $toplevel = $url;
                   12598:         $path = $url;
                   12599:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   12600:         $fileloc =~ s{^/}{};
1.987     raeburn  12601:     }
1.1249    damieng  12602:     
                   12603:     # parses the dependency paths to get some info
                   12604:     # fills $newfiles, $mapping, $subdependencies, $dependencies
                   12605:     # $newfiles: hash URL -> 1 for new files or external URLs
                   12606:     # (will be completed later)
                   12607:     # $mapping:
                   12608:     #   for external URLs: external URL -> external URL
                   12609:     #   for relative paths: clean path -> original path
                   12610:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
                   12611:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
1.1126    raeburn  12612:     foreach my $file (keys(%{$allfiles})) {
                   12613:         my $embed_file;
                   12614:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   12615:             $embed_file = $1;
                   12616:         } else {
                   12617:             $embed_file = $file;
                   12618:         }
1.1158    raeburn  12619:         my ($absolutepath,$cleaned_file);
                   12620:         if ($embed_file =~ m{^\w+://}) {
                   12621:             $cleaned_file = $embed_file;
1.1147    raeburn  12622:             $newfiles{$cleaned_file} = 1;
                   12623:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12624:         } else {
1.1158    raeburn  12625:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  12626:             if ($embed_file =~ m{^/}) {
                   12627:                 $absolutepath = $embed_file;
                   12628:             }
1.1147    raeburn  12629:             if ($cleaned_file =~ m{/}) {
                   12630:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  12631:                 $path = &check_for_traversal($path,$url,$toplevel);
                   12632:                 my $item = $fname;
                   12633:                 if ($path ne '') {
                   12634:                     $item = $path.'/'.$fname;
                   12635:                     $subdependencies{$path}{$fname} = 1;
                   12636:                 } else {
                   12637:                     $dependencies{$item} = 1;
                   12638:                 }
                   12639:                 if ($absolutepath) {
                   12640:                     $mapping{$item} = $absolutepath;
                   12641:                 } else {
                   12642:                     $mapping{$item} = $embed_file;
                   12643:                 }
                   12644:             } else {
                   12645:                 $dependencies{$embed_file} = 1;
                   12646:                 if ($absolutepath) {
1.1147    raeburn  12647:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  12648:                 } else {
1.1147    raeburn  12649:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  12650:                 }
                   12651:             }
1.984     raeburn  12652:         }
                   12653:     }
1.1249    damieng  12654:     
                   12655:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
                   12656:     # and lists
                   12657:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
                   12658:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
                   12659:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
                   12660:     #                                    the path had to be cleaned up
                   12661:     # $existing: hash clean path -> 1 if the file exists
                   12662:     # $numexisting: number of keys in $existing
                   12663:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
                   12664:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
                   12665:     #                                      dependency subdirectories that are
                   12666:     #                                      not listed as dependencies, with some exceptions using $rem
1.1071    raeburn  12667:     my $dirptr = 16384;
1.984     raeburn  12668:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  12669:         $currsubfile{$path} = {};
1.1123    raeburn  12670:         if (($actionurl eq '/adm/portfolio') || 
                   12671:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12672:             my ($sublistref,$listerror) =
                   12673:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   12674:             if (ref($sublistref) eq 'ARRAY') {
                   12675:                 foreach my $line (@{$sublistref}) {
                   12676:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  12677:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  12678:                 }
1.984     raeburn  12679:             }
1.987     raeburn  12680:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12681:             if (opendir(my $dir,$url.'/'.$path)) {
                   12682:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  12683:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   12684:             }
1.1084    raeburn  12685:         } elsif (($actionurl eq '/adm/dependencies') ||
                   12686:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12687:                   ($args->{'context'} eq 'paste')) ||
                   12688:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12689:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  12690:                 my $dir;
                   12691:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   12692:                     $dir = $fileloc;
                   12693:                 } else {
                   12694:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12695:                 }
1.1071    raeburn  12696:                 if ($dir ne '') {
                   12697:                     my ($sublistref,$listerror) =
                   12698:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   12699:                     if (ref($sublistref) eq 'ARRAY') {
                   12700:                         foreach my $line (@{$sublistref}) {
                   12701:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   12702:                                 undef,$mtime)=split(/\&/,$line,12);
                   12703:                             unless (($testdir&$dirptr) ||
                   12704:                                     ($file_name =~ /^\.\.?$/)) {
                   12705:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   12706:                             }
                   12707:                         }
                   12708:                     }
                   12709:                 }
1.984     raeburn  12710:             }
                   12711:         }
                   12712:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  12713:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  12714:                 my $item = $path.'/'.$file;
                   12715:                 unless ($mapping{$item} eq $item) {
                   12716:                     $pathchanges{$item} = 1;
                   12717:                 }
                   12718:                 $existing{$item} = 1;
                   12719:                 $numexisting ++;
                   12720:             } else {
                   12721:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  12722:             }
                   12723:         }
1.1071    raeburn  12724:         if ($actionurl eq '/adm/dependencies') {
                   12725:             foreach my $path (keys(%currsubfile)) {
                   12726:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   12727:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   12728:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  12729:                              next if (($rem ne '') &&
                   12730:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   12731:                                        (ref($navmap) &&
                   12732:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   12733:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12734:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  12735:                              $unused{$path.'/'.$file} = 1; 
                   12736:                          }
                   12737:                     }
                   12738:                 }
                   12739:             }
                   12740:         }
1.984     raeburn  12741:     }
1.1249    damieng  12742:     
                   12743:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
                   12744:     # for files in $url or $fileloc (target directory) in some contexts
1.987     raeburn  12745:     my %currfile;
1.1123    raeburn  12746:     if (($actionurl eq '/adm/portfolio') ||
                   12747:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  12748:         my ($dirlistref,$listerror) =
                   12749:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   12750:         if (ref($dirlistref) eq 'ARRAY') {
                   12751:             foreach my $line (@{$dirlistref}) {
                   12752:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   12753:                 $currfile{$file_name} = 1;
                   12754:             }
1.984     raeburn  12755:         }
1.987     raeburn  12756:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  12757:         if (opendir(my $dir,$url)) {
1.987     raeburn  12758:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  12759:             map {$currfile{$_} = 1;} @dir_list;
                   12760:         }
1.1084    raeburn  12761:     } elsif (($actionurl eq '/adm/dependencies') ||
                   12762:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  12763:               ($args->{'context'} eq 'paste')) ||
                   12764:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  12765:         if ($env{'request.course.id'} ne '') {
                   12766:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   12767:             if ($dir ne '') {
                   12768:                 my ($dirlistref,$listerror) =
                   12769:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   12770:                 if (ref($dirlistref) eq 'ARRAY') {
                   12771:                     foreach my $line (@{$dirlistref}) {
                   12772:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   12773:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   12774:                         unless (($testdir&$dirptr) ||
                   12775:                                 ($file_name =~ /^\.\.?$/)) {
                   12776:                             $currfile{$file_name} = [$size,$mtime];
                   12777:                         }
                   12778:                     }
                   12779:                 }
                   12780:             }
                   12781:         }
1.984     raeburn  12782:     }
1.1249    damieng  12783:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
                   12784:     # are not in subdirectories, using $currfile
1.984     raeburn  12785:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  12786:         if (exists($currfile{$file})) {
1.987     raeburn  12787:             unless ($mapping{$file} eq $file) {
                   12788:                 $pathchanges{$file} = 1;
                   12789:             }
                   12790:             $existing{$file} = 1;
                   12791:             $numexisting ++;
                   12792:         } else {
1.984     raeburn  12793:             $newfiles{$file} = 1;
                   12794:         }
                   12795:     }
1.1071    raeburn  12796:     foreach my $file (keys(%currfile)) {
                   12797:         unless (($file eq $filename) ||
                   12798:                 ($file eq $filename.'.bak') ||
                   12799:                 ($dependencies{$file})) {
1.1085    raeburn  12800:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  12801:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   12802:                     next if (($rem ne '') &&
                   12803:                              (($env{"httpref.$rem".$file} ne '') ||
                   12804:                               (ref($navmap) &&
                   12805:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   12806:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   12807:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   12808:                 }
1.1085    raeburn  12809:             }
1.1071    raeburn  12810:             $unused{$file} = 1;
                   12811:         }
                   12812:     }
1.1249    damieng  12813:     
                   12814:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
1.1084    raeburn  12815:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   12816:         ($args->{'context'} eq 'paste')) {
                   12817:         $counter = scalar(keys(%existing));
                   12818:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  12819:         return ($output,$counter,$numpathchg,\%existing);
                   12820:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   12821:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   12822:         $counter = scalar(keys(%existing));
                   12823:         $numpathchg = scalar(keys(%pathchanges));
                   12824:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  12825:     }
1.1249    damieng  12826:     
                   12827:     # returns HTML otherwise, with dependency results and to ask for more uploads
                   12828:     
                   12829:     # $upload_output: missing dependencies (with upload form)
                   12830:     # $modify_output: uploaded dependencies (in use)
                   12831:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
1.984     raeburn  12832:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  12833:         if ($actionurl eq '/adm/dependencies') {
                   12834:             next if ($embed_file =~ m{^\w+://});
                   12835:         }
1.660     raeburn  12836:         $upload_output .= &start_data_table_row().
1.1123    raeburn  12837:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  12838:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  12839:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  12840:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   12841:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  12842:         }
1.1123    raeburn  12843:         $upload_output .= '</td>';
1.1071    raeburn  12844:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  12845:             $upload_output.='<td align="right">'.
                   12846:                             '<span class="LC_info LC_fontsize_medium">'.
                   12847:                             &mt("URL points to web address").'</span>';
1.987     raeburn  12848:             $numremref++;
1.660     raeburn  12849:         } elsif ($args->{'error_on_invalid_names'}
                   12850:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  12851:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   12852:                             &mt('Invalid characters').'</span>';
1.987     raeburn  12853:             $numinvalid++;
1.660     raeburn  12854:         } else {
1.1123    raeburn  12855:             $upload_output .= '<td>'.
                   12856:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  12857:                                                      $embed_file,\%mapping,
1.1071    raeburn  12858:                                                      $allfiles,$codebase,'upload');
                   12859:             $counter ++;
                   12860:             $numnew ++;
1.987     raeburn  12861:         }
                   12862:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   12863:     }
                   12864:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  12865:         if ($actionurl eq '/adm/dependencies') {
                   12866:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   12867:             $modify_output .= &start_data_table_row().
                   12868:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   12869:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   12870:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   12871:                               '<td>'.$size.'</td>'.
                   12872:                               '<td>'.$mtime.'</td>'.
                   12873:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   12874:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   12875:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   12876:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   12877:                               &embedded_file_element('upload_embedded',$counter,
                   12878:                                                      $embed_file,\%mapping,
                   12879:                                                      $allfiles,$codebase,'modify').
                   12880:                               '</div></td>'.
                   12881:                               &end_data_table_row()."\n";
                   12882:             $counter ++;
                   12883:         } else {
                   12884:             $upload_output .= &start_data_table_row().
1.1123    raeburn  12885:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   12886:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   12887:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  12888:                               &Apache::loncommon::end_data_table_row()."\n";
                   12889:         }
                   12890:     }
                   12891:     my $delidx = $counter;
                   12892:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   12893:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   12894:         $delete_output .= &start_data_table_row().
                   12895:                           '<td><img src="'.&icon($oldfile).'" />'.
                   12896:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   12897:                           '<td>'.$size.'</td>'.
                   12898:                           '<td>'.$mtime.'</td>'.
                   12899:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   12900:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   12901:                           &embedded_file_element('upload_embedded',$delidx,
                   12902:                                                  $oldfile,\%mapping,$allfiles,
                   12903:                                                  $codebase,'delete').'</td>'.
                   12904:                           &end_data_table_row()."\n"; 
                   12905:         $numunused ++;
                   12906:         $delidx ++;
1.987     raeburn  12907:     }
                   12908:     if ($upload_output) {
                   12909:         $upload_output = &start_data_table().
                   12910:                          $upload_output.
                   12911:                          &end_data_table()."\n";
                   12912:     }
1.1071    raeburn  12913:     if ($modify_output) {
                   12914:         $modify_output = &start_data_table().
                   12915:                          &start_data_table_header_row().
                   12916:                          '<th>'.&mt('File').'</th>'.
                   12917:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12918:                          '<th>'.&mt('Modified').'</th>'.
                   12919:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   12920:                          &end_data_table_header_row().
                   12921:                          $modify_output.
                   12922:                          &end_data_table()."\n";
                   12923:     }
                   12924:     if ($delete_output) {
                   12925:         $delete_output = &start_data_table().
                   12926:                          &start_data_table_header_row().
                   12927:                          '<th>'.&mt('File').'</th>'.
                   12928:                          '<th>'.&mt('Size (KB)').'</th>'.
                   12929:                          '<th>'.&mt('Modified').'</th>'.
                   12930:                          '<th>'.&mt('Delete?').'</th>'.
                   12931:                          &end_data_table_header_row().
                   12932:                          $delete_output.
                   12933:                          &end_data_table()."\n";
                   12934:     }
1.987     raeburn  12935:     my $applies = 0;
                   12936:     if ($numremref) {
                   12937:         $applies ++;
                   12938:     }
                   12939:     if ($numinvalid) {
                   12940:         $applies ++;
                   12941:     }
                   12942:     if ($numexisting) {
                   12943:         $applies ++;
                   12944:     }
1.1071    raeburn  12945:     if ($counter || $numunused) {
1.987     raeburn  12946:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   12947:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  12948:                   $state.'<h3>'.$heading.'</h3>'; 
                   12949:         if ($actionurl eq '/adm/dependencies') {
                   12950:             if ($numnew) {
                   12951:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   12952:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   12953:                            $upload_output.'<br />'."\n";
                   12954:             }
                   12955:             if ($numexisting) {
                   12956:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   12957:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   12958:                            $modify_output.'<br />'."\n";
                   12959:                            $buttontext = &mt('Save changes');
                   12960:             }
                   12961:             if ($numunused) {
                   12962:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   12963:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   12964:                            $delete_output.'<br />'."\n";
                   12965:                            $buttontext = &mt('Save changes');
                   12966:             }
                   12967:         } else {
                   12968:             $output .= $upload_output.'<br />'."\n";
                   12969:         }
                   12970:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   12971:                    $counter.'" />'."\n";
                   12972:         if ($actionurl eq '/adm/dependencies') { 
                   12973:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   12974:                        $numnew.'" />'."\n";
                   12975:         } elsif ($actionurl eq '') {
1.987     raeburn  12976:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   12977:         }
                   12978:     } elsif ($applies) {
                   12979:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   12980:         if ($applies > 1) {
                   12981:             $output .=  
1.1123    raeburn  12982:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  12983:             if ($numremref) {
                   12984:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   12985:             }
                   12986:             if ($numinvalid) {
                   12987:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   12988:             }
                   12989:             if ($numexisting) {
                   12990:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   12991:             }
                   12992:             $output .= '</ul><br />';
                   12993:         } elsif ($numremref) {
                   12994:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   12995:         } elsif ($numinvalid) {
                   12996:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   12997:         } elsif ($numexisting) {
                   12998:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   12999:         }
                   13000:         $output .= $upload_output.'<br />';
                   13001:     }
                   13002:     my ($pathchange_output,$chgcount);
1.1071    raeburn  13003:     $chgcount = $counter;
1.987     raeburn  13004:     if (keys(%pathchanges) > 0) {
                   13005:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  13006:             if ($counter) {
1.987     raeburn  13007:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   13008:                                                   $embed_file,\%mapping,
1.1071    raeburn  13009:                                                   $allfiles,$codebase,'change');
1.987     raeburn  13010:             } else {
                   13011:                 $pathchange_output .= 
                   13012:                     &start_data_table_row().
                   13013:                     '<td><input type ="checkbox" name="namechange" value="'.
                   13014:                     $chgcount.'" checked="checked" /></td>'.
                   13015:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   13016:                     '<td>'.$embed_file.
                   13017:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  13018:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  13019:                     '</td>'.&end_data_table_row();
1.660     raeburn  13020:             }
1.987     raeburn  13021:             $numpathchg ++;
                   13022:             $chgcount ++;
1.660     raeburn  13023:         }
                   13024:     }
1.1127    raeburn  13025:     if (($counter) || ($numunused)) {
1.987     raeburn  13026:         if ($numpathchg) {
                   13027:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   13028:                        $numpathchg.'" />'."\n";
                   13029:         }
                   13030:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   13031:             ($actionurl eq '/adm/imsimport')) {
                   13032:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   13033:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   13034:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  13035:         } elsif ($actionurl eq '/adm/dependencies') {
                   13036:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  13037:         }
1.1123    raeburn  13038:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  13039:     } elsif ($numpathchg) {
                   13040:         my %pathchange = ();
                   13041:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   13042:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13043:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  13044:         }
1.987     raeburn  13045:     }
1.1071    raeburn  13046:     return ($output,$counter,$numpathchg);
1.987     raeburn  13047: }
                   13048: 
1.1147    raeburn  13049: =pod
                   13050: 
                   13051: =item * clean_path($name)
                   13052: 
                   13053: Performs clean-up of directories, subdirectories and filename in an
                   13054: embedded object, referenced in an HTML file which is being uploaded
                   13055: to a course or portfolio, where 
                   13056: "Upload embedded images/multimedia files if HTML file" checkbox was
                   13057: checked.
                   13058: 
                   13059: Clean-up is similar to replacements in lonnet::clean_filename()
                   13060: except each / between sub-directory and next level is preserved.
                   13061: 
                   13062: =cut
                   13063: 
                   13064: sub clean_path {
                   13065:     my ($embed_file) = @_;
                   13066:     $embed_file =~s{^/+}{};
                   13067:     my @contents;
                   13068:     if ($embed_file =~ m{/}) {
                   13069:         @contents = split(/\//,$embed_file);
                   13070:     } else {
                   13071:         @contents = ($embed_file);
                   13072:     }
                   13073:     my $lastidx = scalar(@contents)-1;
                   13074:     for (my $i=0; $i<=$lastidx; $i++) { 
                   13075:         $contents[$i]=~s{\\}{/}g;
                   13076:         $contents[$i]=~s/\s+/\_/g;
                   13077:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   13078:         if ($i == $lastidx) {
                   13079:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   13080:         }
                   13081:     }
                   13082:     if ($lastidx > 0) {
                   13083:         return join('/',@contents);
                   13084:     } else {
                   13085:         return $contents[0];
                   13086:     }
                   13087: }
                   13088: 
1.987     raeburn  13089: sub embedded_file_element {
1.1071    raeburn  13090:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  13091:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   13092:                    (ref($codebase) eq 'HASH'));
                   13093:     my $output;
1.1071    raeburn  13094:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  13095:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   13096:     }
                   13097:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   13098:                &escape($embed_file).'" />';
                   13099:     unless (($context eq 'upload_embedded') && 
                   13100:             ($mapping->{$embed_file} eq $embed_file)) {
                   13101:         $output .='
                   13102:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   13103:     }
                   13104:     my $attrib;
                   13105:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   13106:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   13107:     }
                   13108:     $output .=
                   13109:         "\n\t\t".
                   13110:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   13111:         $attrib.'" />';
                   13112:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   13113:         $output .=
                   13114:             "\n\t\t".
                   13115:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   13116:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  13117:     }
1.987     raeburn  13118:     return $output;
1.660     raeburn  13119: }
                   13120: 
1.1071    raeburn  13121: sub get_dependency_details {
                   13122:     my ($currfile,$currsubfile,$embed_file) = @_;
                   13123:     my ($size,$mtime,$showsize,$showmtime);
                   13124:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   13125:         if ($embed_file =~ m{/}) {
                   13126:             my ($path,$fname) = split(/\//,$embed_file);
                   13127:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   13128:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   13129:             }
                   13130:         } else {
                   13131:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   13132:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   13133:             }
                   13134:         }
                   13135:         $showsize = $size/1024.0;
                   13136:         $showsize = sprintf("%.1f",$showsize);
                   13137:         if ($mtime > 0) {
                   13138:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   13139:         }
                   13140:     }
                   13141:     return ($showsize,$showmtime);
                   13142: }
                   13143: 
                   13144: sub ask_embedded_js {
                   13145:     return <<"END";
                   13146: <script type="text/javascript"">
                   13147: // <![CDATA[
                   13148: function toggleBrowse(counter) {
                   13149:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   13150:     var fileid = document.getElementById('embedded_item_'+counter);
                   13151:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   13152:     if (chkboxid.checked == true) {
                   13153:         uploaddivid.style.display='block';
                   13154:     } else {
                   13155:         uploaddivid.style.display='none';
                   13156:         fileid.value = '';
                   13157:     }
                   13158: }
                   13159: // ]]>
                   13160: </script>
                   13161: 
                   13162: END
                   13163: }
                   13164: 
1.661     raeburn  13165: sub upload_embedded {
                   13166:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  13167:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   13168:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  13169:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   13170:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   13171:         my $orig_uploaded_filename =
                   13172:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  13173:         foreach my $type ('orig','ref','attrib','codebase') {
                   13174:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   13175:                 $env{'form.embedded_'.$type.'_'.$i} =
                   13176:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   13177:             }
                   13178:         }
1.661     raeburn  13179:         my ($path,$fname) =
                   13180:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   13181:         # no path, whole string is fname
                   13182:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   13183:         $fname = &Apache::lonnet::clean_filename($fname);
                   13184:         # See if there is anything left
                   13185:         next if ($fname eq '');
                   13186: 
                   13187:         # Check if file already exists as a file or directory.
                   13188:         my ($state,$msg);
                   13189:         if ($context eq 'portfolio') {
                   13190:             my $port_path = $dirpath;
                   13191:             if ($group ne '') {
                   13192:                 $port_path = "groups/$group/$port_path";
                   13193:             }
1.987     raeburn  13194:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   13195:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  13196:                                               $dir_root,$port_path,$disk_quota,
                   13197:                                               $current_disk_usage,$uname,$udom);
                   13198:             if ($state eq 'will_exceed_quota'
1.984     raeburn  13199:                 || $state eq 'file_locked') {
1.661     raeburn  13200:                 $output .= $msg;
                   13201:                 next;
                   13202:             }
                   13203:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   13204:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   13205:             if ($state eq 'exists') {
                   13206:                 $output .= $msg;
                   13207:                 next;
                   13208:             }
                   13209:         }
                   13210:         # Check if extension is valid
                   13211:         if (($fname =~ /\.(\w+)$/) &&
                   13212:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   13213:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   13214:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  13215:             next;
                   13216:         } elsif (($fname =~ /\.(\w+)$/) &&
                   13217:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  13218:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  13219:             next;
                   13220:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   13221:             $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  13222:             next;
                   13223:         }
                   13224:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  13225:         my $subdir = $path;
                   13226:         $subdir =~ s{/+$}{};
1.661     raeburn  13227:         if ($context eq 'portfolio') {
1.984     raeburn  13228:             my $result;
                   13229:             if ($state eq 'existingfile') {
                   13230:                 $result=
                   13231:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  13232:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  13233:             } else {
1.984     raeburn  13234:                 $result=
                   13235:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  13236:                                                     $dirpath.
1.1123    raeburn  13237:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  13238:                 if ($result !~ m|^/uploaded/|) {
                   13239:                     $output .= '<span class="LC_error">'
                   13240:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13241:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13242:                                .'</span><br />';
                   13243:                     next;
                   13244:                 } else {
1.987     raeburn  13245:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13246:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  13247:                 }
1.661     raeburn  13248:             }
1.1123    raeburn  13249:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  13250:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   13251:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  13252:             my $result =
1.1126    raeburn  13253:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  13254:             if ($result !~ m|^/uploaded/|) {
                   13255:                 $output .= '<span class="LC_error">'
                   13256:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   13257:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   13258:                            .'</span><br />';
                   13259:                     next;
                   13260:             } else {
                   13261:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13262:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  13263:                 if ($context eq 'syllabus') {
                   13264:                     &Apache::lonnet::make_public_indefinitely($result);
                   13265:                 }
1.987     raeburn  13266:             }
1.661     raeburn  13267:         } else {
                   13268: # Save the file
                   13269:             my $target = $env{'form.embedded_item_'.$i};
                   13270:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   13271:             my $dest = $fullpath.$fname;
                   13272:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  13273:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  13274:             my $count;
                   13275:             my $filepath = $dir_root;
1.1027    raeburn  13276:             foreach my $subdir (@parts) {
                   13277:                 $filepath .= "/$subdir";
                   13278:                 if (!-e $filepath) {
1.661     raeburn  13279:                     mkdir($filepath,0770);
                   13280:                 }
                   13281:             }
                   13282:             my $fh;
                   13283:             if (!open($fh,'>'.$dest)) {
                   13284:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   13285:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  13286:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   13287:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13288:                            '</span><br />';
                   13289:             } else {
                   13290:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   13291:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   13292:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  13293:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   13294:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  13295:                               '</span><br />';
                   13296:                 } else {
1.987     raeburn  13297:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   13298:                                $url.'</span>').'<br />';
                   13299:                     unless ($context eq 'testbank') {
                   13300:                         $footer .= &mt('View embedded file: [_1]',
                   13301:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   13302:                     }
                   13303:                 }
                   13304:                 close($fh);
                   13305:             }
                   13306:         }
                   13307:         if ($env{'form.embedded_ref_'.$i}) {
                   13308:             $pathchange{$i} = 1;
                   13309:         }
                   13310:     }
                   13311:     if ($output) {
                   13312:         $output = '<p>'.$output.'</p>';
                   13313:     }
                   13314:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   13315:     $returnflag = 'ok';
1.1071    raeburn  13316:     my $numpathchgs = scalar(keys(%pathchange));
                   13317:     if ($numpathchgs > 0) {
1.987     raeburn  13318:         if ($context eq 'portfolio') {
                   13319:             $output .= '<p>'.&mt('or').'</p>';
                   13320:         } elsif ($context eq 'testbank') {
1.1071    raeburn  13321:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   13322:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  13323:             $returnflag = 'modify_orightml';
                   13324:         }
                   13325:     }
1.1071    raeburn  13326:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  13327: }
                   13328: 
                   13329: sub modify_html_form {
                   13330:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   13331:     my $end = 0;
                   13332:     my $modifyform;
                   13333:     if ($context eq 'upload_embedded') {
                   13334:         return unless (ref($pathchange) eq 'HASH');
                   13335:         if ($env{'form.number_embedded_items'}) {
                   13336:             $end += $env{'form.number_embedded_items'};
                   13337:         }
                   13338:         if ($env{'form.number_pathchange_items'}) {
                   13339:             $end += $env{'form.number_pathchange_items'};
                   13340:         }
                   13341:         if ($end) {
                   13342:             for (my $i=0; $i<$end; $i++) {
                   13343:                 if ($i < $env{'form.number_embedded_items'}) {
                   13344:                     next unless($pathchange->{$i});
                   13345:                 }
                   13346:                 $modifyform .=
                   13347:                     &start_data_table_row().
                   13348:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   13349:                     'checked="checked" /></td>'.
                   13350:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   13351:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   13352:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   13353:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   13354:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   13355:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   13356:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   13357:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   13358:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   13359:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   13360:                     &end_data_table_row();
1.1071    raeburn  13361:             }
1.987     raeburn  13362:         }
                   13363:     } else {
                   13364:         $modifyform = $pathchgtable;
                   13365:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   13366:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   13367:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   13368:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   13369:         }
                   13370:     }
                   13371:     if ($modifyform) {
1.1071    raeburn  13372:         if ($actionurl eq '/adm/dependencies') {
                   13373:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   13374:         }
1.987     raeburn  13375:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   13376:                '<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".
                   13377:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   13378:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   13379:                '</ol></p>'."\n".'<p>'.
                   13380:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   13381:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   13382:                &start_data_table()."\n".
                   13383:                &start_data_table_header_row().
                   13384:                '<th>'.&mt('Change?').'</th>'.
                   13385:                '<th>'.&mt('Current reference').'</th>'.
                   13386:                '<th>'.&mt('Required reference').'</th>'.
                   13387:                &end_data_table_header_row()."\n".
                   13388:                $modifyform.
                   13389:                &end_data_table().'<br />'."\n".$hiddenstate.
                   13390:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   13391:                '</form>'."\n";
                   13392:     }
                   13393:     return;
                   13394: }
                   13395: 
                   13396: sub modify_html_refs {
1.1123    raeburn  13397:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  13398:     my $container;
                   13399:     if ($context eq 'portfolio') {
                   13400:         $container = $env{'form.container'};
                   13401:     } elsif ($context eq 'coursedoc') {
                   13402:         $container = $env{'form.primaryurl'};
1.1071    raeburn  13403:     } elsif ($context eq 'manage_dependencies') {
                   13404:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   13405:         $container = "/$container";
1.1123    raeburn  13406:     } elsif ($context eq 'syllabus') {
                   13407:         $container = $url;
1.987     raeburn  13408:     } else {
1.1027    raeburn  13409:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  13410:     }
                   13411:     my (%allfiles,%codebase,$output,$content);
                   13412:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  13413:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  13414:         if (wantarray) {
                   13415:             return ('',0,0); 
                   13416:         } else {
                   13417:             return;
                   13418:         }
                   13419:     }
                   13420:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13421:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  13422:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   13423:             if (wantarray) {
                   13424:                 return ('',0,0);
                   13425:             } else {
                   13426:                 return;
                   13427:             }
                   13428:         } 
1.987     raeburn  13429:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  13430:         if ($content eq '-1') {
                   13431:             if (wantarray) {
                   13432:                 return ('',0,0);
                   13433:             } else {
                   13434:                 return;
                   13435:             }
                   13436:         }
1.987     raeburn  13437:     } else {
1.1071    raeburn  13438:         unless ($container =~ /^\Q$dir_root\E/) {
                   13439:             if (wantarray) {
                   13440:                 return ('',0,0);
                   13441:             } else {
                   13442:                 return;
                   13443:             }
                   13444:         } 
1.1317    raeburn  13445:         if (open(my $fh,'<',$container)) {
1.987     raeburn  13446:             $content = join('', <$fh>);
                   13447:             close($fh);
                   13448:         } else {
1.1071    raeburn  13449:             if (wantarray) {
                   13450:                 return ('',0,0);
                   13451:             } else {
                   13452:                 return;
                   13453:             }
1.987     raeburn  13454:         }
                   13455:     }
                   13456:     my ($count,$codebasecount) = (0,0);
                   13457:     my $mm = new File::MMagic;
                   13458:     my $mime_type = $mm->checktype_contents($content);
                   13459:     if ($mime_type eq 'text/html') {
                   13460:         my $parse_result = 
                   13461:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   13462:                                                     \%codebase,\$content);
                   13463:         if ($parse_result eq 'ok') {
                   13464:             foreach my $i (@changes) {
                   13465:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   13466:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   13467:                 if ($allfiles{$ref}) {
                   13468:                     my $newname =  $orig;
                   13469:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  13470:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  13471:                     if ($attrib_regexp =~ /:/) {
                   13472:                         $attrib_regexp =~ s/\:/|/g;
                   13473:                     }
                   13474:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13475:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13476:                         $count += $numchg;
1.1123    raeburn  13477:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  13478:                         delete($allfiles{$ref});
1.987     raeburn  13479:                     }
                   13480:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  13481:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  13482:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   13483:                         $codebasecount ++;
                   13484:                     }
                   13485:                 }
                   13486:             }
1.1123    raeburn  13487:             my $skiprewrites;
1.987     raeburn  13488:             if ($count || $codebasecount) {
                   13489:                 my $saveresult;
1.1071    raeburn  13490:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  13491:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  13492:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13493:                     if ($url eq $container) {
                   13494:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   13495:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13496:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  13497:                                             $fname.'</span>').'</p>';
1.987     raeburn  13498:                     } else {
                   13499:                          $output = '<p class="LC_error">'.
                   13500:                                    &mt('Error: update failed for: [_1].',
                   13501:                                    '<span class="LC_filename">'.
                   13502:                                    $container.'</span>').'</p>';
                   13503:                     }
1.1123    raeburn  13504:                     if ($context eq 'syllabus') {
                   13505:                         unless ($saveresult eq 'ok') {
                   13506:                             $skiprewrites = 1;
                   13507:                         }
                   13508:                     }
1.987     raeburn  13509:                 } else {
1.1317    raeburn  13510:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  13511:                         print $fh $content;
                   13512:                         close($fh);
                   13513:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   13514:                                   $count,'<span class="LC_filename">'.
                   13515:                                   $container.'</span>').'</p>';
1.661     raeburn  13516:                     } else {
1.987     raeburn  13517:                          $output = '<p class="LC_error">'.
                   13518:                                    &mt('Error: could not update [_1].',
                   13519:                                    '<span class="LC_filename">'.
                   13520:                                    $container.'</span>').'</p>';
1.661     raeburn  13521:                     }
                   13522:                 }
                   13523:             }
1.1123    raeburn  13524:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   13525:                 my ($actionurl,$state);
                   13526:                 $actionurl = "/public/$udom/$uname/syllabus";
                   13527:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   13528:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   13529:                                               \%codebase,
                   13530:                                               {'context' => 'rewrites',
                   13531:                                                'ignore_remote_references' => 1,});
                   13532:                 if (ref($mapping) eq 'HASH') {
                   13533:                     my $rewrites = 0;
                   13534:                     foreach my $key (keys(%{$mapping})) {
                   13535:                         next if ($key =~ m{^https?://});
                   13536:                         my $ref = $mapping->{$key};
                   13537:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   13538:                         my $attrib;
                   13539:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   13540:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   13541:                         }
                   13542:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   13543:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   13544:                             $rewrites += $numchg;
                   13545:                         }
                   13546:                     }
                   13547:                     if ($rewrites) {
                   13548:                         my $saveresult; 
                   13549:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   13550:                         if ($url eq $container) {
                   13551:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   13552:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   13553:                                             $count,'<span class="LC_filename">'.
                   13554:                                             $fname.'</span>').'</p>';
                   13555:                         } else {
                   13556:                             $output .= '<p class="LC_error">'.
                   13557:                                        &mt('Error: could not update links in [_1].',
                   13558:                                        '<span class="LC_filename">'.
                   13559:                                        $container.'</span>').'</p>';
                   13560: 
                   13561:                         }
                   13562:                     }
                   13563:                 }
                   13564:             }
1.987     raeburn  13565:         } else {
                   13566:             &logthis('Failed to parse '.$container.
                   13567:                      ' to modify references: '.$parse_result);
1.661     raeburn  13568:         }
                   13569:     }
1.1071    raeburn  13570:     if (wantarray) {
                   13571:         return ($output,$count,$codebasecount);
                   13572:     } else {
                   13573:         return $output;
                   13574:     }
1.661     raeburn  13575: }
                   13576: 
                   13577: sub check_for_existing {
                   13578:     my ($path,$fname,$element) = @_;
                   13579:     my ($state,$msg);
                   13580:     if (-d $path.'/'.$fname) {
                   13581:         $state = 'exists';
                   13582:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13583:     } elsif (-e $path.'/'.$fname) {
                   13584:         $state = 'exists';
                   13585:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   13586:     }
                   13587:     if ($state eq 'exists') {
                   13588:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   13589:     }
                   13590:     return ($state,$msg);
                   13591: }
                   13592: 
                   13593: sub check_for_upload {
                   13594:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   13595:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  13596:     my $filesize = length($env{'form.'.$element});
                   13597:     if (!$filesize) {
                   13598:         my $msg = '<span class="LC_error">'.
                   13599:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   13600:                       '<span class="LC_filename">'.$fname.'</span>',
                   13601:                       $filesize).'<br />'.
1.1007    raeburn  13602:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  13603:                   '</span>';
                   13604:         return ('zero_bytes',$msg);
                   13605:     }
                   13606:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  13607:     my $getpropath = 1;
1.1021    raeburn  13608:     my ($dirlistref,$listerror) =
                   13609:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  13610:     my $found_file = 0;
                   13611:     my $locked_file = 0;
1.991     raeburn  13612:     my @lockers;
                   13613:     my $navmap;
                   13614:     if ($env{'request.course.id'}) {
                   13615:         $navmap = Apache::lonnavmaps::navmap->new();
                   13616:     }
1.1021    raeburn  13617:     if (ref($dirlistref) eq 'ARRAY') {
                   13618:         foreach my $line (@{$dirlistref}) {
                   13619:             my ($file_name,$rest)=split(/\&/,$line,2);
                   13620:             if ($file_name eq $fname){
                   13621:                 $file_name = $path.$file_name;
                   13622:                 if ($group ne '') {
                   13623:                     $file_name = $group.$file_name;
                   13624:                 }
                   13625:                 $found_file = 1;
                   13626:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   13627:                     foreach my $lock (@lockers) {
                   13628:                         if (ref($lock) eq 'ARRAY') {
                   13629:                             my ($symb,$crsid) = @{$lock};
                   13630:                             if ($crsid eq $env{'request.course.id'}) {
                   13631:                                 if (ref($navmap)) {
                   13632:                                     my $res = $navmap->getBySymb($symb);
                   13633:                                     foreach my $part (@{$res->parts()}) { 
                   13634:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   13635:                                         unless (($slot_status == $res->RESERVED) ||
                   13636:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   13637:                                             $locked_file = 1;
                   13638:                                         }
1.991     raeburn  13639:                                     }
1.1021    raeburn  13640:                                 } else {
                   13641:                                     $locked_file = 1;
1.991     raeburn  13642:                                 }
                   13643:                             } else {
                   13644:                                 $locked_file = 1;
                   13645:                             }
                   13646:                         }
1.1021    raeburn  13647:                    }
                   13648:                 } else {
                   13649:                     my @info = split(/\&/,$rest);
                   13650:                     my $currsize = $info[6]/1000;
                   13651:                     if ($currsize < $filesize) {
                   13652:                         my $extra = $filesize - $currsize;
                   13653:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   13654:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  13655:                                       &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   13656:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   13657:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   13658:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  13659:                             return ('will_exceed_quota',$msg);
                   13660:                         }
1.984     raeburn  13661:                     }
                   13662:                 }
1.661     raeburn  13663:             }
                   13664:         }
                   13665:     }
                   13666:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   13667:         my $msg = '<p class="LC_warning">'.
                   13668:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  13669:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  13670:         return ('will_exceed_quota',$msg);
                   13671:     } elsif ($found_file) {
                   13672:         if ($locked_file) {
1.1179    bisitz   13673:             my $msg = '<p class="LC_warning">';
1.661     raeburn  13674:             $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   13675:             $msg .= '</p>';
1.661     raeburn  13676:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   13677:             return ('file_locked',$msg);
                   13678:         } else {
1.1179    bisitz   13679:             my $msg = '<p class="LC_error">';
1.984     raeburn  13680:             $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   13681:             $msg .= '</p>';
1.984     raeburn  13682:             return ('existingfile',$msg);
1.661     raeburn  13683:         }
                   13684:     }
                   13685: }
                   13686: 
1.987     raeburn  13687: sub check_for_traversal {
                   13688:     my ($path,$url,$toplevel) = @_;
                   13689:     my @parts=split(/\//,$path);
                   13690:     my $cleanpath;
                   13691:     my $fullpath = $url;
                   13692:     for (my $i=0;$i<@parts;$i++) {
                   13693:         next if ($parts[$i] eq '.');
                   13694:         if ($parts[$i] eq '..') {
                   13695:             $fullpath =~ s{([^/]+/)$}{};
                   13696:         } else {
                   13697:             $fullpath .= $parts[$i].'/';
                   13698:         }
                   13699:     }
                   13700:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   13701:         $cleanpath = $1;
                   13702:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   13703:         my $curr_toprel = $1;
                   13704:         my @parts = split(/\//,$curr_toprel);
                   13705:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   13706:         my @urlparts = split(/\//,$url_toprel);
                   13707:         my $doubledots;
                   13708:         my $startdiff = -1;
                   13709:         for (my $i=0; $i<@urlparts; $i++) {
                   13710:             if ($startdiff == -1) {
                   13711:                 unless ($urlparts[$i] eq $parts[$i]) {
                   13712:                     $startdiff = $i;
                   13713:                     $doubledots .= '../';
                   13714:                 }
                   13715:             } else {
                   13716:                 $doubledots .= '../';
                   13717:             }
                   13718:         }
                   13719:         if ($startdiff > -1) {
                   13720:             $cleanpath = $doubledots;
                   13721:             for (my $i=$startdiff; $i<@parts; $i++) {
                   13722:                 $cleanpath .= $parts[$i].'/';
                   13723:             }
                   13724:         }
                   13725:     }
                   13726:     $cleanpath =~ s{(/)$}{};
                   13727:     return $cleanpath;
                   13728: }
1.31      albertel 13729: 
1.1053    raeburn  13730: sub is_archive_file {
                   13731:     my ($mimetype) = @_;
                   13732:     if (($mimetype eq 'application/octet-stream') ||
                   13733:         ($mimetype eq 'application/x-stuffit') ||
                   13734:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   13735:         return 1;
                   13736:     }
                   13737:     return;
                   13738: }
                   13739: 
                   13740: sub decompress_form {
1.1065    raeburn  13741:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  13742:     my %lt = &Apache::lonlocal::texthash (
                   13743:         this => 'This file is an archive file.',
1.1067    raeburn  13744:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  13745:         itsc => 'Its contents are as follows:',
1.1053    raeburn  13746:         youm => 'You may wish to extract its contents.',
                   13747:         extr => 'Extract contents',
1.1067    raeburn  13748:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   13749:         proa => 'Process automatically?',
1.1053    raeburn  13750:         yes  => 'Yes',
                   13751:         no   => 'No',
1.1067    raeburn  13752:         fold => 'Title for folder containing movie',
                   13753:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  13754:     );
1.1065    raeburn  13755:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  13756:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  13757:     my $info = &list_archive_contents($fileloc,\@paths);
                   13758:     if (@paths) {
                   13759:         foreach my $path (@paths) {
                   13760:             $path =~ s{^/}{};
1.1067    raeburn  13761:             if ($path =~ m{^([^/]+)/$}) {
                   13762:                 $topdir = $1;
                   13763:             }
1.1065    raeburn  13764:             if ($path =~ m{^([^/]+)/}) {
                   13765:                 $toplevel{$1} = $path;
                   13766:             } else {
                   13767:                 $toplevel{$path} = $path;
                   13768:             }
                   13769:         }
                   13770:     }
1.1067    raeburn  13771:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  13772:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  13773:                         "$topdir/media/",
                   13774:                         "$topdir/media/$topdir.mp4",
                   13775:                         "$topdir/media/FirstFrame.png",
                   13776:                         "$topdir/media/player.swf",
                   13777:                         "$topdir/media/swfobject.js",
                   13778:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  13779:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  13780:                          "$topdir/$topdir.mp4",
                   13781:                          "$topdir/$topdir\_config.xml",
                   13782:                          "$topdir/$topdir\_controller.swf",
                   13783:                          "$topdir/$topdir\_embed.css",
                   13784:                          "$topdir/$topdir\_First_Frame.png",
                   13785:                          "$topdir/$topdir\_player.html",
                   13786:                          "$topdir/$topdir\_Thumbnails.png",
                   13787:                          "$topdir/playerProductInstall.swf",
                   13788:                          "$topdir/scripts/",
                   13789:                          "$topdir/scripts/config_xml.js",
                   13790:                          "$topdir/scripts/handlebars.js",
                   13791:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   13792:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   13793:                          "$topdir/scripts/modernizr.js",
                   13794:                          "$topdir/scripts/player-min.js",
                   13795:                          "$topdir/scripts/swfobject.js",
                   13796:                          "$topdir/skins/",
                   13797:                          "$topdir/skins/configuration_express.xml",
                   13798:                          "$topdir/skins/express_show/",
                   13799:                          "$topdir/skins/express_show/player-min.css",
                   13800:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  13801:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   13802:                          "$topdir/$topdir.mp4",
                   13803:                          "$topdir/$topdir\_config.xml",
                   13804:                          "$topdir/$topdir\_controller.swf",
                   13805:                          "$topdir/$topdir\_embed.css",
                   13806:                          "$topdir/$topdir\_First_Frame.png",
                   13807:                          "$topdir/$topdir\_player.html",
                   13808:                          "$topdir/$topdir\_Thumbnails.png",
                   13809:                          "$topdir/playerProductInstall.swf",
                   13810:                          "$topdir/scripts/",
                   13811:                          "$topdir/scripts/config_xml.js",
                   13812:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   13813:                          "$topdir/skins/",
                   13814:                          "$topdir/skins/configuration_express.xml",
                   13815:                          "$topdir/skins/express_show/",
                   13816:                          "$topdir/skins/express_show/spritesheet.min.css",
                   13817:                          "$topdir/skins/express_show/spritesheet.png",
                   13818:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  13819:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  13820:         if (@diffs == 0) {
1.1164    raeburn  13821:             $is_camtasia = 6;
                   13822:         } else {
1.1197    raeburn  13823:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  13824:             if (@diffs == 0) {
                   13825:                 $is_camtasia = 8;
1.1197    raeburn  13826:             } else {
                   13827:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   13828:                 if (@diffs == 0) {
                   13829:                     $is_camtasia = 8;
                   13830:                 }
1.1164    raeburn  13831:             }
1.1067    raeburn  13832:         }
                   13833:     }
                   13834:     my $output;
                   13835:     if ($is_camtasia) {
                   13836:         $output = <<"ENDCAM";
                   13837: <script type="text/javascript" language="Javascript">
                   13838: // <![CDATA[
                   13839: 
                   13840: function camtasiaToggle() {
                   13841:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   13842:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  13843:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  13844:                 document.getElementById('camtasia_titles').style.display='block';
                   13845:             } else {
                   13846:                 document.getElementById('camtasia_titles').style.display='none';
                   13847:             }
                   13848:         }
                   13849:     }
                   13850:     return;
                   13851: }
                   13852: 
                   13853: // ]]>
                   13854: </script>
                   13855: <p>$lt{'camt'}</p>
                   13856: ENDCAM
1.1065    raeburn  13857:     } else {
1.1067    raeburn  13858:         $output = '<p>'.$lt{'this'};
                   13859:         if ($info eq '') {
                   13860:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   13861:         } else {
                   13862:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   13863:                        '<div><pre>'.$info.'</pre></div>';
                   13864:         }
1.1065    raeburn  13865:     }
1.1067    raeburn  13866:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  13867:     my $duplicates;
                   13868:     my $num = 0;
                   13869:     if (ref($dirlist) eq 'ARRAY') {
                   13870:         foreach my $item (@{$dirlist}) {
                   13871:             if (ref($item) eq 'ARRAY') {
                   13872:                 if (exists($toplevel{$item->[0]})) {
                   13873:                     $duplicates .= 
                   13874:                         &start_data_table_row().
                   13875:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13876:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   13877:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   13878:                         'value="1" />'.&mt('Yes').'</label>'.
                   13879:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   13880:                         '<td>'.$item->[0].'</td>';
                   13881:                     if ($item->[2]) {
                   13882:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   13883:                     } else {
                   13884:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   13885:                     }
                   13886:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   13887:                                    '<td>'.
                   13888:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   13889:                                    '</td>'.
                   13890:                                    &end_data_table_row();
                   13891:                     $num ++;
                   13892:                 }
                   13893:             }
                   13894:         }
                   13895:     }
                   13896:     my $itemcount;
                   13897:     if (@paths > 0) {
                   13898:         $itemcount = scalar(@paths);
                   13899:     } else {
                   13900:         $itemcount = 1;
                   13901:     }
1.1067    raeburn  13902:     if ($is_camtasia) {
                   13903:         $output .= $lt{'auto'}.'<br />'.
                   13904:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  13905:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  13906:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   13907:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   13908:                    $lt{'no'}.'</label></span><br />'.
                   13909:                    '<div id="camtasia_titles" style="display:block">'.
                   13910:                    &Apache::lonhtmlcommon::start_pick_box().
                   13911:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   13912:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   13913:                    &Apache::lonhtmlcommon::row_closure().
                   13914:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   13915:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   13916:                    &Apache::lonhtmlcommon::row_closure(1).
                   13917:                    &Apache::lonhtmlcommon::end_pick_box().
                   13918:                    '</div>';
                   13919:     }
1.1065    raeburn  13920:     $output .= 
                   13921:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  13922:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   13923:         "\n";
1.1065    raeburn  13924:     if ($duplicates ne '') {
                   13925:         $output .= '<p><span class="LC_warning">'.
                   13926:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   13927:                    &start_data_table().
                   13928:                    &start_data_table_header_row().
                   13929:                    '<th>'.&mt('Overwrite?').'</th>'.
                   13930:                    '<th>'.&mt('Name').'</th>'.
                   13931:                    '<th>'.&mt('Type').'</th>'.
                   13932:                    '<th>'.&mt('Size').'</th>'.
                   13933:                    '<th>'.&mt('Last modified').'</th>'.
                   13934:                    &end_data_table_header_row().
                   13935:                    $duplicates.
                   13936:                    &end_data_table().
                   13937:                    '</p>';
                   13938:     }
1.1067    raeburn  13939:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  13940:     if (ref($hiddenelements) eq 'HASH') {
                   13941:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   13942:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   13943:         }
                   13944:     }
                   13945:     $output .= <<"END";
1.1067    raeburn  13946: <br />
1.1053    raeburn  13947: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   13948: </form>
                   13949: $noextract
                   13950: END
                   13951:     return $output;
                   13952: }
                   13953: 
1.1065    raeburn  13954: sub decompression_utility {
                   13955:     my ($program) = @_;
                   13956:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   13957:     my $location;
                   13958:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   13959:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   13960:                          '/usr/sbin/') {
                   13961:             if (-x $dir.$program) {
                   13962:                 $location = $dir.$program;
                   13963:                 last;
                   13964:             }
                   13965:         }
                   13966:     }
                   13967:     return $location;
                   13968: }
                   13969: 
                   13970: sub list_archive_contents {
                   13971:     my ($file,$pathsref) = @_;
                   13972:     my (@cmd,$output);
                   13973:     my $needsregexp;
                   13974:     if ($file =~ /\.zip$/) {
                   13975:         @cmd = (&decompression_utility('unzip'),"-l");
                   13976:         $needsregexp = 1;
                   13977:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   13978:              ($file =~ /\.tgz$/)) {
                   13979:         @cmd = (&decompression_utility('tar'),"-ztf");
                   13980:     } elsif ($file =~ /\.tar\.bz2$/) {
                   13981:         @cmd = (&decompression_utility('tar'),"-jtf");
                   13982:     } elsif ($file =~ m|\.tar$|) {
                   13983:         @cmd = (&decompression_utility('tar'),"-tf");
                   13984:     }
                   13985:     if (@cmd) {
                   13986:         undef($!);
                   13987:         undef($@);
                   13988:         if (open(my $fh,"-|", @cmd, $file)) {
                   13989:             while (my $line = <$fh>) {
                   13990:                 $output .= $line;
                   13991:                 chomp($line);
                   13992:                 my $item;
                   13993:                 if ($needsregexp) {
                   13994:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   13995:                 } else {
                   13996:                     $item = $line;
                   13997:                 }
                   13998:                 if ($item ne '') {
                   13999:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   14000:                         push(@{$pathsref},$item);
                   14001:                     } 
                   14002:                 }
                   14003:             }
                   14004:             close($fh);
                   14005:         }
                   14006:     }
                   14007:     return $output;
                   14008: }
                   14009: 
1.1053    raeburn  14010: sub decompress_uploaded_file {
                   14011:     my ($file,$dir) = @_;
                   14012:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   14013:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   14014:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   14015:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   14016:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   14017:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   14018:     my $decompressed = $env{'cgi.decompressed'};
                   14019:     &Apache::lonnet::delenv('cgi.file');
                   14020:     &Apache::lonnet::delenv('cgi.dir');
                   14021:     &Apache::lonnet::delenv('cgi.decompressed');
                   14022:     return ($decompressed,$result);
                   14023: }
                   14024: 
1.1055    raeburn  14025: sub process_decompression {
                   14026:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1292    raeburn  14027:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   14028:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14029:                &mt('Unexpected file path.').'</p>'."\n";
                   14030:     }
                   14031:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   14032:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14033:                &mt('Unexpected course context.').'</p>'."\n";
                   14034:     }
1.1293    raeburn  14035:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
1.1292    raeburn  14036:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14037:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   14038:     }
1.1055    raeburn  14039:     my ($dir,$error,$warning,$output);
1.1180    raeburn  14040:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   14041:         $error = &mt('Filename not a supported archive file type.').
                   14042:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  14043:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   14044:     } else {
                   14045:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14046:         if ($docuhome eq 'no_host') {
                   14047:             $error = &mt('Could not determine home server for course.');
                   14048:         } else {
                   14049:             my @ids=&Apache::lonnet::current_machine_ids();
                   14050:             my $currdir = "$dir_root/$destination";
                   14051:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14052:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   14053:                        "$dir_root/$destination";
                   14054:             } else {
                   14055:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   14056:                        "$dir_root/$docudom/$docuname/$destination";
                   14057:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   14058:                     $error = &mt('Archive file not found.');
                   14059:                 }
                   14060:             }
1.1065    raeburn  14061:             my (@to_overwrite,@to_skip);
                   14062:             if ($env{'form.archive_overwrite_total'} > 0) {
                   14063:                 my $total = $env{'form.archive_overwrite_total'};
                   14064:                 for (my $i=0; $i<$total; $i++) {
                   14065:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   14066:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   14067:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   14068:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   14069:                     }
                   14070:                 }
                   14071:             }
                   14072:             my $numskip = scalar(@to_skip);
1.1292    raeburn  14073:             my $numoverwrite = scalar(@to_overwrite);
                   14074:             if (($numskip) && (!$numoverwrite)) { 
1.1065    raeburn  14075:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   14076:             } elsif ($dir eq '') {
1.1055    raeburn  14077:                 $error = &mt('Directory containing archive file unavailable.');
                   14078:             } elsif (!$error) {
1.1065    raeburn  14079:                 my ($decompressed,$display);
1.1292    raeburn  14080:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  14081:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   14082:                     mkdir("$dir/$tempdir",0755);
1.1292    raeburn  14083:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   14084:                         ($decompressed,$display) = 
                   14085:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   14086:                         foreach my $item (@to_skip) {
                   14087:                             if (($item ne '') && ($item !~ /\.\./)) {
                   14088:                                 if (-f "$dir/$tempdir/$item") { 
                   14089:                                     unlink("$dir/$tempdir/$item");
                   14090:                                 } elsif (-d "$dir/$tempdir/$item") {
1.1300    raeburn  14091:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
1.1292    raeburn  14092:                                 }
                   14093:                             }
                   14094:                         }
                   14095:                         foreach my $item (@to_overwrite) {
                   14096:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   14097:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   14098:                                     if (-f "$dir/$item") {
                   14099:                                         unlink("$dir/$item");
                   14100:                                     } elsif (-d "$dir/$item") {
1.1300    raeburn  14101:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
1.1292    raeburn  14102:                                     }
                   14103:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   14104:                                 }
1.1065    raeburn  14105:                             }
                   14106:                         }
1.1292    raeburn  14107:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
1.1300    raeburn  14108:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
1.1292    raeburn  14109:                         }
1.1065    raeburn  14110:                     }
                   14111:                 } else {
                   14112:                     ($decompressed,$display) = 
                   14113:                         &decompress_uploaded_file($file,$dir);
                   14114:                 }
1.1055    raeburn  14115:                 if ($decompressed eq 'ok') {
1.1065    raeburn  14116:                     $output = '<p class="LC_info">'.
                   14117:                               &mt('Files extracted successfully from archive.').
                   14118:                               '</p>'."\n";
1.1055    raeburn  14119:                     my ($warning,$result,@contents);
                   14120:                     my ($newdirlistref,$newlisterror) =
                   14121:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   14122:                                                  $docuname,1);
                   14123:                     my (%is_dir,%changes,@newitems);
                   14124:                     my $dirptr = 16384;
1.1065    raeburn  14125:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  14126:                         foreach my $dir_line (@{$newdirlistref}) {
                   14127:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1292    raeburn  14128:                             unless (($item =~ /^\.+$/) || ($item eq $file)) {
1.1055    raeburn  14129:                                 push(@newitems,$item);
                   14130:                                 if ($dirptr&$testdir) {
                   14131:                                     $is_dir{$item} = 1;
                   14132:                                 }
                   14133:                                 $changes{$item} = 1;
                   14134:                             }
                   14135:                         }
                   14136:                     }
                   14137:                     if (keys(%changes) > 0) {
                   14138:                         foreach my $item (sort(@newitems)) {
                   14139:                             if ($changes{$item}) {
                   14140:                                 push(@contents,$item);
                   14141:                             }
                   14142:                         }
                   14143:                     }
                   14144:                     if (@contents > 0) {
1.1067    raeburn  14145:                         my $wantform;
                   14146:                         unless ($env{'form.autoextract_camtasia'}) {
                   14147:                             $wantform = 1;
                   14148:                         }
1.1056    raeburn  14149:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  14150:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   14151:                                                                 $currdir,\%is_dir,
                   14152:                                                                 \%children,\%parent,
1.1056    raeburn  14153:                                                                 \@contents,\%dirorder,
                   14154:                                                                 \%titles,$wantform);
1.1055    raeburn  14155:                         if ($datatable ne '') {
                   14156:                             $output .= &archive_options_form('decompressed',$datatable,
                   14157:                                                              $count,$hiddenelem);
1.1065    raeburn  14158:                             my $startcount = 6;
1.1055    raeburn  14159:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  14160:                                                            \%titles,\%children);
1.1055    raeburn  14161:                         }
1.1067    raeburn  14162:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  14163:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  14164:                             my %displayed;
                   14165:                             my $total = 1;
                   14166:                             $env{'form.archive_directory'} = [];
                   14167:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   14168:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   14169:                                 $path =~ s{/$}{};
                   14170:                                 my $item;
                   14171:                                 if ($path ne '') {
                   14172:                                     $item = "$path/$titles{$i}";
                   14173:                                 } else {
                   14174:                                     $item = $titles{$i};
                   14175:                                 }
                   14176:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   14177:                                 if ($item eq $contents[0]) {
                   14178:                                     push(@{$env{'form.archive_directory'}},$i);
                   14179:                                     $env{'form.archive_'.$i} = 'display';
                   14180:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   14181:                                     $displayed{'folder'} = $i;
1.1164    raeburn  14182:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   14183:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  14184:                                     $env{'form.archive_'.$i} = 'display';
                   14185:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   14186:                                     $displayed{'web'} = $i;
                   14187:                                 } else {
1.1164    raeburn  14188:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   14189:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   14190:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  14191:                                         push(@{$env{'form.archive_directory'}},$i);
                   14192:                                     }
                   14193:                                     $env{'form.archive_'.$i} = 'dependency';
                   14194:                                 }
                   14195:                                 $total ++;
                   14196:                             }
                   14197:                             for (my $i=1; $i<$total; $i++) {
                   14198:                                 next if ($i == $displayed{'web'});
                   14199:                                 next if ($i == $displayed{'folder'});
                   14200:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   14201:                             }
                   14202:                             $env{'form.phase'} = 'decompress_cleanup';
                   14203:                             $env{'form.archivedelete'} = 1;
                   14204:                             $env{'form.archive_count'} = $total-1;
                   14205:                             $output .=
                   14206:                                 &process_extracted_files('coursedocs',$docudom,
                   14207:                                                          $docuname,$destination,
                   14208:                                                          $dir_root,$hiddenelem);
                   14209:                         }
1.1055    raeburn  14210:                     } else {
                   14211:                         $warning = &mt('No new items extracted from archive file.');
                   14212:                     }
                   14213:                 } else {
                   14214:                     $output = $display;
                   14215:                     $error = &mt('An error occurred during extraction from the archive file.');
                   14216:                 }
                   14217:             }
                   14218:         }
                   14219:     }
                   14220:     if ($error) {
                   14221:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14222:                    $error.'</p>'."\n";
                   14223:     }
                   14224:     if ($warning) {
                   14225:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14226:     }
                   14227:     return $output;
                   14228: }
                   14229: 
                   14230: sub get_extracted {
1.1056    raeburn  14231:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   14232:         $titles,$wantform) = @_;
1.1055    raeburn  14233:     my $count = 0;
                   14234:     my $depth = 0;
                   14235:     my $datatable;
1.1056    raeburn  14236:     my @hierarchy;
1.1055    raeburn  14237:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  14238:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   14239:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  14240:     foreach my $item (@{$contents}) {
                   14241:         $count ++;
1.1056    raeburn  14242:         @{$dirorder->{$count}} = @hierarchy;
                   14243:         $titles->{$count} = $item;
1.1055    raeburn  14244:         &archive_hierarchy($depth,$count,$parent,$children);
                   14245:         if ($wantform) {
                   14246:             $datatable .= &archive_row($is_dir->{$item},$item,
                   14247:                                        $currdir,$depth,$count);
                   14248:         }
                   14249:         if ($is_dir->{$item}) {
                   14250:             $depth ++;
1.1056    raeburn  14251:             push(@hierarchy,$count);
                   14252:             $parent->{$depth} = $count;
1.1055    raeburn  14253:             $datatable .=
                   14254:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  14255:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   14256:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  14257:             $depth --;
1.1056    raeburn  14258:             pop(@hierarchy);
1.1055    raeburn  14259:         }
                   14260:     }
                   14261:     return ($count,$datatable);
                   14262: }
                   14263: 
                   14264: sub recurse_extracted_archive {
1.1056    raeburn  14265:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   14266:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  14267:     my $result='';
1.1056    raeburn  14268:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   14269:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   14270:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  14271:         return $result;
                   14272:     }
                   14273:     my $dirptr = 16384;
                   14274:     my ($newdirlistref,$newlisterror) =
                   14275:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   14276:     if (ref($newdirlistref) eq 'ARRAY') {
                   14277:         foreach my $dir_line (@{$newdirlistref}) {
                   14278:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   14279:             unless ($item =~ /^\.+$/) {
                   14280:                 $$count ++;
1.1056    raeburn  14281:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   14282:                 $titles->{$$count} = $item;
1.1055    raeburn  14283:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  14284: 
1.1055    raeburn  14285:                 my $is_dir;
                   14286:                 if ($dirptr&$testdir) {
                   14287:                     $is_dir = 1;
                   14288:                 }
                   14289:                 if ($wantform) {
                   14290:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   14291:                 }
                   14292:                 if ($is_dir) {
                   14293:                     $$depth ++;
1.1056    raeburn  14294:                     push(@{$hierarchy},$$count);
                   14295:                     $parent->{$$depth} = $$count;
1.1055    raeburn  14296:                     $result .=
                   14297:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   14298:                                                    $docuname,$depth,$count,
1.1056    raeburn  14299:                                                    $hierarchy,$dirorder,$children,
                   14300:                                                    $parent,$titles,$wantform);
1.1055    raeburn  14301:                     $$depth --;
1.1056    raeburn  14302:                     pop(@{$hierarchy});
1.1055    raeburn  14303:                 }
                   14304:             }
                   14305:         }
                   14306:     }
                   14307:     return $result;
                   14308: }
                   14309: 
                   14310: sub archive_hierarchy {
                   14311:     my ($depth,$count,$parent,$children) =@_;
                   14312:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   14313:         if (exists($parent->{$depth})) {
                   14314:              $children->{$parent->{$depth}} .= $count.':';
                   14315:         }
                   14316:     }
                   14317:     return;
                   14318: }
                   14319: 
                   14320: sub archive_row {
                   14321:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   14322:     my ($name) = ($item =~ m{([^/]+)$});
                   14323:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  14324:                                        'display'    => 'Add as file',
1.1055    raeburn  14325:                                        'dependency' => 'Include as dependency',
                   14326:                                        'discard'    => 'Discard',
                   14327:                                       );
                   14328:     if ($is_dir) {
1.1059    raeburn  14329:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  14330:     }
1.1056    raeburn  14331:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   14332:     my $offset = 0;
1.1055    raeburn  14333:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  14334:         $offset ++;
1.1065    raeburn  14335:         if ($action ne 'display') {
                   14336:             $offset ++;
                   14337:         }  
1.1055    raeburn  14338:         $output .= '<td><span class="LC_nobreak">'.
                   14339:                    '<label><input type="radio" name="archive_'.$count.
                   14340:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   14341:         my $text = $choices{$action};
                   14342:         if ($is_dir) {
                   14343:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   14344:             if ($action eq 'display') {
1.1059    raeburn  14345:                 $text = &mt('Add as folder');
1.1055    raeburn  14346:             }
1.1056    raeburn  14347:         } else {
                   14348:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   14349: 
                   14350:         }
                   14351:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   14352:         if ($action eq 'dependency') {
                   14353:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   14354:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   14355:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   14356:                        '<option value=""></option>'."\n".
                   14357:                        '</select>'."\n".
                   14358:                        '</div>';
1.1059    raeburn  14359:         } elsif ($action eq 'display') {
                   14360:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   14361:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   14362:                        '</div>';
1.1055    raeburn  14363:         }
1.1056    raeburn  14364:         $output .= '</td>';
1.1055    raeburn  14365:     }
                   14366:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   14367:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   14368:     for (my $i=0; $i<$depth; $i++) {
                   14369:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   14370:     }
                   14371:     if ($is_dir) {
                   14372:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   14373:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   14374:     } else {
                   14375:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   14376:     }
                   14377:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   14378:                &end_data_table_row();
                   14379:     return $output;
                   14380: }
                   14381: 
                   14382: sub archive_options_form {
1.1065    raeburn  14383:     my ($form,$display,$count,$hiddenelem) = @_;
                   14384:     my %lt = &Apache::lonlocal::texthash(
                   14385:                perm => 'Permanently remove archive file?',
                   14386:                hows => 'How should each extracted item be incorporated in the course?',
                   14387:                cont => 'Content actions for all',
                   14388:                addf => 'Add as folder/file',
                   14389:                incd => 'Include as dependency for a displayed file',
                   14390:                disc => 'Discard',
                   14391:                no   => 'No',
                   14392:                yes  => 'Yes',
                   14393:                save => 'Save',
                   14394:     );
                   14395:     my $output = <<"END";
                   14396: <form name="$form" method="post" action="">
                   14397: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   14398: <label>
                   14399:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   14400: </label>
                   14401: &nbsp;
                   14402: <label>
                   14403:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   14404: </span>
                   14405: </p>
                   14406: <input type="hidden" name="phase" value="decompress_cleanup" />
                   14407: <br />$lt{'hows'}
                   14408: <div class="LC_columnSection">
                   14409:   <fieldset>
                   14410:     <legend>$lt{'cont'}</legend>
                   14411:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   14412:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   14413:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   14414:   </fieldset>
                   14415: </div>
                   14416: END
                   14417:     return $output.
1.1055    raeburn  14418:            &start_data_table()."\n".
1.1065    raeburn  14419:            $display."\n".
1.1055    raeburn  14420:            &end_data_table()."\n".
                   14421:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   14422:            $hiddenelem.
1.1065    raeburn  14423:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  14424:            '</form>';
                   14425: }
                   14426: 
                   14427: sub archive_javascript {
1.1056    raeburn  14428:     my ($startcount,$numitems,$titles,$children) = @_;
                   14429:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  14430:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  14431:     my $scripttag = <<START;
                   14432: <script type="text/javascript">
                   14433: // <![CDATA[
                   14434: 
                   14435: function checkAll(form,prefix) {
                   14436:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   14437:     for (var i=0; i < form.elements.length; i++) {
                   14438:         var id = form.elements[i].id;
                   14439:         if ((id != '') && (id != undefined)) {
                   14440:             if (idstr.test(id)) {
                   14441:                 if (form.elements[i].type == 'radio') {
                   14442:                     form.elements[i].checked = true;
1.1056    raeburn  14443:                     var nostart = i-$startcount;
1.1059    raeburn  14444:                     var offset = nostart%7;
                   14445:                     var count = (nostart-offset)/7;    
1.1056    raeburn  14446:                     dependencyCheck(form,count,offset);
1.1055    raeburn  14447:                 }
                   14448:             }
                   14449:         }
                   14450:     }
                   14451: }
                   14452: 
                   14453: function propagateCheck(form,count) {
                   14454:     if (count > 0) {
1.1059    raeburn  14455:         var startelement = $startcount + ((count-1) * 7);
                   14456:         for (var j=1; j<6; j++) {
                   14457:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  14458:                 var item = startelement + j; 
                   14459:                 if (form.elements[item].type == 'radio') {
                   14460:                     if (form.elements[item].checked) {
                   14461:                         containerCheck(form,count,j);
                   14462:                         break;
                   14463:                     }
1.1055    raeburn  14464:                 }
                   14465:             }
                   14466:         }
                   14467:     }
                   14468: }
                   14469: 
                   14470: numitems = $numitems
1.1056    raeburn  14471: var titles = new Array(numitems);
                   14472: var parents = new Array(numitems);
1.1055    raeburn  14473: for (var i=0; i<numitems; i++) {
1.1056    raeburn  14474:     parents[i] = new Array;
1.1055    raeburn  14475: }
1.1059    raeburn  14476: var maintitle = '$maintitle';
1.1055    raeburn  14477: 
                   14478: START
                   14479: 
1.1056    raeburn  14480:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   14481:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  14482:         for (my $i=0; $i<@contents; $i ++) {
                   14483:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   14484:         }
                   14485:     }
                   14486: 
1.1056    raeburn  14487:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   14488:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   14489:     }
                   14490: 
1.1055    raeburn  14491:     $scripttag .= <<END;
                   14492: 
                   14493: function containerCheck(form,count,offset) {
                   14494:     if (count > 0) {
1.1056    raeburn  14495:         dependencyCheck(form,count,offset);
1.1059    raeburn  14496:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  14497:         form.elements[item].checked = true;
                   14498:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14499:             if (parents[count].length > 0) {
                   14500:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  14501:                     containerCheck(form,parents[count][j],offset);
                   14502:                 }
                   14503:             }
                   14504:         }
                   14505:     }
                   14506: }
                   14507: 
                   14508: function dependencyCheck(form,count,offset) {
                   14509:     if (count > 0) {
1.1059    raeburn  14510:         var chosen = (offset+$startcount)+7*(count-1);
                   14511:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  14512:         var currtype = form.elements[depitem].type;
                   14513:         if (form.elements[chosen].value == 'dependency') {
                   14514:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   14515:             form.elements[depitem].options.length = 0;
                   14516:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  14517:             for (var i=1; i<=numitems; i++) {
                   14518:                 if (i == count) {
                   14519:                     continue;
                   14520:                 }
1.1059    raeburn  14521:                 var startelement = $startcount + (i-1) * 7;
                   14522:                 for (var j=1; j<6; j++) {
                   14523:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  14524:                         var item = startelement + j;
                   14525:                         if (form.elements[item].type == 'radio') {
                   14526:                             if (form.elements[item].checked) {
                   14527:                                 if (form.elements[item].value == 'display') {
                   14528:                                     var n = form.elements[depitem].options.length;
                   14529:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   14530:                                 }
                   14531:                             }
                   14532:                         }
                   14533:                     }
                   14534:                 }
                   14535:             }
                   14536:         } else {
                   14537:             document.getElementById('arc_depon_'+count).style.display='none';
                   14538:             form.elements[depitem].options.length = 0;
                   14539:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   14540:         }
1.1059    raeburn  14541:         titleCheck(form,count,offset);
1.1056    raeburn  14542:     }
                   14543: }
                   14544: 
                   14545: function propagateSelect(form,count,offset) {
                   14546:     if (count > 0) {
1.1065    raeburn  14547:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  14548:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   14549:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14550:             if (parents[count].length > 0) {
                   14551:                 for (var j=0; j<parents[count].length; j++) {
                   14552:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  14553:                 }
                   14554:             }
                   14555:         }
                   14556:     }
                   14557: }
1.1056    raeburn  14558: 
                   14559: function containerSelect(form,count,offset,picked) {
                   14560:     if (count > 0) {
1.1065    raeburn  14561:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  14562:         if (form.elements[item].type == 'radio') {
                   14563:             if (form.elements[item].value == 'dependency') {
                   14564:                 if (form.elements[item+1].type == 'select-one') {
                   14565:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   14566:                         if (form.elements[item+1].options[i].value == picked) {
                   14567:                             form.elements[item+1].selectedIndex = i;
                   14568:                             break;
                   14569:                         }
                   14570:                     }
                   14571:                 }
                   14572:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   14573:                     if (parents[count].length > 0) {
                   14574:                         for (var j=0; j<parents[count].length; j++) {
                   14575:                             containerSelect(form,parents[count][j],offset,picked);
                   14576:                         }
                   14577:                     }
                   14578:                 }
                   14579:             }
                   14580:         }
                   14581:     }
                   14582: }
                   14583: 
1.1059    raeburn  14584: function titleCheck(form,count,offset) {
                   14585:     if (count > 0) {
                   14586:         var chosen = (offset+$startcount)+7*(count-1);
                   14587:         var depitem = $startcount + ((count-1) * 7) + 2;
                   14588:         var currtype = form.elements[depitem].type;
                   14589:         if (form.elements[chosen].value == 'display') {
                   14590:             document.getElementById('arc_title_'+count).style.display='block';
                   14591:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   14592:                 document.getElementById('archive_title_'+count).value=maintitle;
                   14593:             }
                   14594:         } else {
                   14595:             document.getElementById('arc_title_'+count).style.display='none';
                   14596:             if (currtype == 'text') { 
                   14597:                 document.getElementById('archive_title_'+count).value='';
                   14598:             }
                   14599:         }
                   14600:     }
                   14601:     return;
                   14602: }
                   14603: 
1.1055    raeburn  14604: // ]]>
                   14605: </script>
                   14606: END
                   14607:     return $scripttag;
                   14608: }
                   14609: 
                   14610: sub process_extracted_files {
1.1067    raeburn  14611:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  14612:     my $numitems = $env{'form.archive_count'};
1.1294    raeburn  14613:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  14614:     my @ids=&Apache::lonnet::current_machine_ids();
                   14615:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  14616:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  14617:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   14618:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   14619:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   14620:         $pathtocheck = "$dir_root/$destination";
                   14621:         $dir = $dir_root;
                   14622:         $ishome = 1;
                   14623:     } else {
                   14624:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   14625:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1294    raeburn  14626:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  14627:     }
                   14628:     my $currdir = "$dir_root/$destination";
                   14629:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   14630:     if ($env{'form.folderpath'}) {
                   14631:         my @items = split('&',$env{'form.folderpath'});
                   14632:         $folders{'0'} = $items[-2];
1.1099    raeburn  14633:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   14634:             $containers{'0'}='page';
                   14635:         } else {  
                   14636:             $containers{'0'}='sequence';
                   14637:         }
1.1055    raeburn  14638:     }
                   14639:     my @archdirs = &get_env_multiple('form.archive_directory');
                   14640:     if ($numitems) {
                   14641:         for (my $i=1; $i<=$numitems; $i++) {
                   14642:             my $path = $env{'form.archive_content_'.$i};
                   14643:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   14644:                 my $item = $1;
                   14645:                 $toplevelitems{$item} = $i;
                   14646:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   14647:                     $is_dir{$item} = 1;
                   14648:                 }
                   14649:             }
                   14650:         }
                   14651:     }
1.1067    raeburn  14652:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  14653:     if (keys(%toplevelitems) > 0) {
                   14654:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  14655:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   14656:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  14657:     }
1.1066    raeburn  14658:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  14659:     if ($numitems) {
                   14660:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  14661:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  14662:             my $path = $env{'form.archive_content_'.$i};
                   14663:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14664:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   14665:                     if ($prefix ne '' && $path ne '') {
                   14666:                         if (-e $prefix.$path) {
1.1066    raeburn  14667:                             if ((@archdirs > 0) && 
                   14668:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   14669:                                 $todeletedir{$prefix.$path} = 1;
                   14670:                             } else {
                   14671:                                 $todelete{$prefix.$path} = 1;
                   14672:                             }
1.1055    raeburn  14673:                         }
                   14674:                     }
                   14675:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  14676:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  14677:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  14678:                     $docstitle = $env{'form.archive_title_'.$i};
                   14679:                     if ($docstitle eq '') {
                   14680:                         $docstitle = $title;
                   14681:                     }
1.1055    raeburn  14682:                     $outer = 0;
1.1056    raeburn  14683:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14684:                         if (@{$dirorder{$i}} > 0) {
                   14685:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  14686:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   14687:                                     $outer = $item;
                   14688:                                     last;
                   14689:                                 }
                   14690:                             }
                   14691:                         }
                   14692:                     }
                   14693:                     my ($errtext,$fatal) = 
                   14694:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   14695:                                                '/'.$folders{$outer}.'.'.
                   14696:                                                $containers{$outer});
                   14697:                     next if ($fatal);
                   14698:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   14699:                         if ($context eq 'coursedocs') {
1.1056    raeburn  14700:                             $mapinner{$i} = time;
1.1055    raeburn  14701:                             $folders{$i} = 'default_'.$mapinner{$i};
                   14702:                             $containers{$i} = 'sequence';
                   14703:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14704:                                       $folders{$i}.'.'.$containers{$i};
                   14705:                             my $newidx = &LONCAPA::map::getresidx();
                   14706:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  14707:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  14708:                             push(@LONCAPA::map::order,$newidx);
                   14709:                             my ($outtext,$errtext) =
                   14710:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14711:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  14712:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  14713:                             $newseqid{$i} = $newidx;
1.1067    raeburn  14714:                             unless ($errtext) {
1.1294    raeburn  14715:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   14716:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
                   14717:                                             '</li>'."\n";
1.1067    raeburn  14718:                             }
1.1055    raeburn  14719:                         }
                   14720:                     } else {
                   14721:                         if ($context eq 'coursedocs') {
                   14722:                             my $newidx=&LONCAPA::map::getresidx();
                   14723:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   14724:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   14725:                                       $title;
1.1392    raeburn  14726:                             if (($outer !~ /\D/) &&
                   14727:                                 (($mapinner{$outer} eq 'default') || ($mapinner{$outer} !~ /\D/)) &&
                   14728:                                 ($newidx !~ /\D/)) {
1.1294    raeburn  14729:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   14730:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   14731:                                 }
                   14732:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14733:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   14734:                                 }
                   14735:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   14736:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   14737:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   14738:                                         unless ($ishome) {
                   14739:                                             my $fetch = "$newdest{$i}/$title";
                   14740:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   14741:                                             $prompttofetch{$fetch} = 1;
                   14742:                                         }
1.1292    raeburn  14743:                                     }
1.1067    raeburn  14744:                                 }
1.1294    raeburn  14745:                                 $LONCAPA::map::resources[$newidx]=
                   14746:                                     $docstitle.':'.$url.':false:normal:res';
                   14747:                                 push(@LONCAPA::map::order, $newidx);
                   14748:                                 my ($outtext,$errtext)=
                   14749:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   14750:                                                             $docuname.'/'.$folders{$outer}.
                   14751:                                                             '.'.$containers{$outer},1,1);
                   14752:                                 unless ($errtext) {
                   14753:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   14754:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   14755:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   14756:                                                    '</li>'."\n";
                   14757:                                     }
1.1067    raeburn  14758:                                 }
1.1294    raeburn  14759:                             } else {
                   14760:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14761:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1296    raeburn  14762:                             }
1.1055    raeburn  14763:                         }
                   14764:                     }
1.1086    raeburn  14765:                 }
                   14766:             } else {
1.1294    raeburn  14767:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   14768:                                 &HTML::Entities::encode($path,'<>&"')).'<br />'; 
1.1086    raeburn  14769:             }
                   14770:         }
                   14771:         for (my $i=1; $i<=$numitems; $i++) {
                   14772:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   14773:             my $path = $env{'form.archive_content_'.$i};
                   14774:             if ($path =~ /^\Q$pathtocheck\E/) {
                   14775:                 my ($title) = ($path =~ m{/([^/]+)$});
                   14776:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   14777:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   14778:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   14779:                         my ($itemidx,$fullpath,$relpath);
                   14780:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   14781:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  14782:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  14783:                                 if ($dirorder{$i}->[$j] eq $container) {
                   14784:                                     $itemidx = $j;
1.1056    raeburn  14785:                                 }
                   14786:                             }
1.1086    raeburn  14787:                         }
                   14788:                         if ($itemidx eq '') {
                   14789:                             $itemidx =  0;
                   14790:                         } 
                   14791:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   14792:                             if ($mapinner{$referrer{$i}}) {
                   14793:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   14794:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14795:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14796:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14797:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14798:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14799:                                             if (!-e $fullpath) {
                   14800:                                                 mkdir($fullpath,0755);
1.1056    raeburn  14801:                                             }
                   14802:                                         }
1.1086    raeburn  14803:                                     } else {
                   14804:                                         last;
1.1056    raeburn  14805:                                     }
1.1086    raeburn  14806:                                 }
                   14807:                             }
                   14808:                         } elsif ($newdest{$referrer{$i}}) {
                   14809:                             $fullpath = $newdest{$referrer{$i}};
                   14810:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   14811:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   14812:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   14813:                                     last;
                   14814:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   14815:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   14816:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14817:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   14818:                                         if (!-e $fullpath) {
                   14819:                                             mkdir($fullpath,0755);
1.1056    raeburn  14820:                                         }
                   14821:                                     }
1.1086    raeburn  14822:                                 } else {
                   14823:                                     last;
1.1056    raeburn  14824:                                 }
1.1055    raeburn  14825:                             }
                   14826:                         }
1.1086    raeburn  14827:                         if ($fullpath ne '') {
                   14828:                             if (-e "$prefix$path") {
1.1292    raeburn  14829:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   14830:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   14831:                                 }
1.1086    raeburn  14832:                             }
                   14833:                             if (-e "$fullpath/$title") {
                   14834:                                 my $showpath;
                   14835:                                 if ($relpath ne '') {
                   14836:                                     $showpath = "$relpath/$title";
                   14837:                                 } else {
                   14838:                                     $showpath = "/$title";
                   14839:                                 } 
1.1294    raeburn  14840:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   14841:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   14842:                                            '</li>'."\n";
1.1292    raeburn  14843:                                 unless ($ishome) {
                   14844:                                     my $fetch = "$fullpath/$title";
                   14845:                                     $fetch =~ s/^\Q$prefix$dir\E//; 
                   14846:                                     $prompttofetch{$fetch} = 1;
                   14847:                                 }
1.1086    raeburn  14848:                             }
                   14849:                         }
1.1055    raeburn  14850:                     }
1.1086    raeburn  14851:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   14852:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1294    raeburn  14853:                                     &HTML::Entities::encode($path,'<>&"'),
                   14854:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   14855:                                 '<br />';
1.1055    raeburn  14856:                 }
                   14857:             } else {
1.1294    raeburn  14858:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
1.1296    raeburn  14859:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  14860:             }
                   14861:         }
                   14862:         if (keys(%todelete)) {
                   14863:             foreach my $key (keys(%todelete)) {
                   14864:                 unlink($key);
1.1066    raeburn  14865:             }
                   14866:         }
                   14867:         if (keys(%todeletedir)) {
                   14868:             foreach my $key (keys(%todeletedir)) {
                   14869:                 rmdir($key);
                   14870:             }
                   14871:         }
                   14872:         foreach my $dir (sort(keys(%is_dir))) {
                   14873:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   14874:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  14875:             }
                   14876:         }
1.1067    raeburn  14877:         if ($result ne '') {
                   14878:             $output .= '<ul>'."\n".
                   14879:                        $result."\n".
                   14880:                        '</ul>';
                   14881:         }
                   14882:         unless ($ishome) {
                   14883:             my $replicationfail;
                   14884:             foreach my $item (keys(%prompttofetch)) {
                   14885:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   14886:                 unless ($fetchresult eq 'ok') {
                   14887:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   14888:                 }
                   14889:             }
                   14890:             if ($replicationfail) {
                   14891:                 $output .= '<p class="LC_error">'.
                   14892:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   14893:                            $replicationfail.
                   14894:                            '</ul></p>';
                   14895:             }
                   14896:         }
1.1055    raeburn  14897:     } else {
                   14898:         $warning = &mt('No items found in archive.');
                   14899:     }
                   14900:     if ($error) {
                   14901:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   14902:                    $error.'</p>'."\n";
                   14903:     }
                   14904:     if ($warning) {
                   14905:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   14906:     }
                   14907:     return $output;
                   14908: }
                   14909: 
1.1066    raeburn  14910: sub cleanup_empty_dirs {
                   14911:     my ($path) = @_;
                   14912:     if (($path ne '') && (-d $path)) {
                   14913:         if (opendir(my $dirh,$path)) {
                   14914:             my @dircontents = grep(!/^\./,readdir($dirh));
                   14915:             my $numitems = 0;
                   14916:             foreach my $item (@dircontents) {
                   14917:                 if (-d "$path/$item") {
1.1111    raeburn  14918:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  14919:                     if (-e "$path/$item") {
                   14920:                         $numitems ++;
                   14921:                     }
                   14922:                 } else {
                   14923:                     $numitems ++;
                   14924:                 }
                   14925:             }
                   14926:             if ($numitems == 0) {
                   14927:                 rmdir($path);
                   14928:             }
                   14929:             closedir($dirh);
                   14930:         }
                   14931:     }
                   14932:     return;
                   14933: }
                   14934: 
1.41      ng       14935: =pod
1.45      matthew  14936: 
1.1162    raeburn  14937: =item * &get_folder_hierarchy()
1.1068    raeburn  14938: 
                   14939: Provides hierarchy of names of folders/sub-folders containing the current
                   14940: item,
                   14941: 
                   14942: Inputs: 3
                   14943:      - $navmap - navmaps object
                   14944: 
                   14945:      - $map - url for map (either the trigger itself, or map containing
                   14946:                            the resource, which is the trigger).
                   14947: 
                   14948:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   14949: 
                   14950: Outputs: 1 @pathitems - array of folder/subfolder names.
                   14951: 
                   14952: =cut
                   14953: 
                   14954: sub get_folder_hierarchy {
                   14955:     my ($navmap,$map,$showitem) = @_;
                   14956:     my @pathitems;
                   14957:     if (ref($navmap)) {
                   14958:         my $mapres = $navmap->getResourceByUrl($map);
                   14959:         if (ref($mapres)) {
                   14960:             my $pcslist = $mapres->map_hierarchy();
                   14961:             if ($pcslist ne '') {
                   14962:                 my @pcs = split(/,/,$pcslist);
                   14963:                 foreach my $pc (@pcs) {
                   14964:                     if ($pc == 1) {
1.1129    raeburn  14965:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  14966:                     } else {
                   14967:                         my $res = $navmap->getByMapPc($pc);
                   14968:                         if (ref($res)) {
                   14969:                             my $title = $res->compTitle();
                   14970:                             $title =~ s/\W+/_/g;
                   14971:                             if ($title ne '') {
                   14972:                                 push(@pathitems,$title);
                   14973:                             }
                   14974:                         }
                   14975:                     }
                   14976:                 }
                   14977:             }
1.1071    raeburn  14978:             if ($showitem) {
                   14979:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  14980:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  14981:                 } else {
                   14982:                     my $maptitle = $mapres->compTitle();
                   14983:                     $maptitle =~ s/\W+/_/g;
                   14984:                     if ($maptitle ne '') {
                   14985:                         push(@pathitems,$maptitle);
                   14986:                     }
1.1068    raeburn  14987:                 }
                   14988:             }
                   14989:         }
                   14990:     }
                   14991:     return @pathitems;
                   14992: }
                   14993: 
                   14994: =pod
                   14995: 
1.1015    raeburn  14996: =item * &get_turnedin_filepath()
                   14997: 
                   14998: Determines path in a user's portfolio file for storage of files uploaded
                   14999: to a specific essayresponse or dropbox item.
                   15000: 
                   15001: Inputs: 3 required + 1 optional.
                   15002: $symb is symb for resource, $uname and $udom are for current user (required).
                   15003: $caller is optional (can be "submission", if routine is called when storing
                   15004: an upoaded file when "Submit Answer" button was pressed).
                   15005: 
                   15006: Returns array containing $path and $multiresp. 
                   15007: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   15008: than one file upload item.  Callers of routine should append partid as a 
                   15009: subdirectory to $path in cases where $multiresp is 1.
                   15010: 
                   15011: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   15012: 
                   15013: =cut
                   15014: 
                   15015: sub get_turnedin_filepath {
                   15016:     my ($symb,$uname,$udom,$caller) = @_;
                   15017:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   15018:     my $turnindir;
                   15019:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   15020:     $turnindir = $userhash{'turnindir'};
                   15021:     my ($path,$multiresp);
                   15022:     if ($turnindir eq '') {
                   15023:         if ($caller eq 'submission') {
                   15024:             $turnindir = &mt('turned in');
                   15025:             $turnindir =~ s/\W+/_/g;
                   15026:             my %newhash = (
                   15027:                             'turnindir' => $turnindir,
                   15028:                           );
                   15029:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   15030:         }
                   15031:     }
                   15032:     if ($turnindir ne '') {
                   15033:         $path = '/'.$turnindir.'/';
                   15034:         my ($multipart,$turnin,@pathitems);
                   15035:         my $navmap = Apache::lonnavmaps::navmap->new();
                   15036:         if (defined($navmap)) {
                   15037:             my $mapres = $navmap->getResourceByUrl($map);
                   15038:             if (ref($mapres)) {
                   15039:                 my $pcslist = $mapres->map_hierarchy();
                   15040:                 if ($pcslist ne '') {
                   15041:                     foreach my $pc (split(/,/,$pcslist)) {
                   15042:                         my $res = $navmap->getByMapPc($pc);
                   15043:                         if (ref($res)) {
                   15044:                             my $title = $res->compTitle();
                   15045:                             $title =~ s/\W+/_/g;
                   15046:                             if ($title ne '') {
1.1149    raeburn  15047:                                 if (($pc > 1) && (length($title) > 12)) {
                   15048:                                     $title = substr($title,0,12);
                   15049:                                 }
1.1015    raeburn  15050:                                 push(@pathitems,$title);
                   15051:                             }
                   15052:                         }
                   15053:                     }
                   15054:                 }
                   15055:                 my $maptitle = $mapres->compTitle();
                   15056:                 $maptitle =~ s/\W+/_/g;
                   15057:                 if ($maptitle ne '') {
1.1149    raeburn  15058:                     if (length($maptitle) > 12) {
                   15059:                         $maptitle = substr($maptitle,0,12);
                   15060:                     }
1.1015    raeburn  15061:                     push(@pathitems,$maptitle);
                   15062:                 }
                   15063:                 unless ($env{'request.state'} eq 'construct') {
                   15064:                     my $res = $navmap->getBySymb($symb);
                   15065:                     if (ref($res)) {
                   15066:                         my $partlist = $res->parts();
                   15067:                         my $totaluploads = 0;
                   15068:                         if (ref($partlist) eq 'ARRAY') {
                   15069:                             foreach my $part (@{$partlist}) {
                   15070:                                 my @types = $res->responseType($part);
                   15071:                                 my @ids = $res->responseIds($part);
                   15072:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   15073:                                     if ($types[$i] eq 'essay') {
                   15074:                                         my $partid = $part.'_'.$ids[$i];
                   15075:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   15076:                                             $totaluploads ++;
                   15077:                                         }
                   15078:                                     }
                   15079:                                 }
                   15080:                             }
                   15081:                             if ($totaluploads > 1) {
                   15082:                                 $multiresp = 1;
                   15083:                             }
                   15084:                         }
                   15085:                     }
                   15086:                 }
                   15087:             } else {
                   15088:                 return;
                   15089:             }
                   15090:         } else {
                   15091:             return;
                   15092:         }
                   15093:         my $restitle=&Apache::lonnet::gettitle($symb);
                   15094:         $restitle =~ s/\W+/_/g;
                   15095:         if ($restitle eq '') {
                   15096:             $restitle = ($resurl =~ m{/[^/]+$});
                   15097:             if ($restitle eq '') {
                   15098:                 $restitle = time;
                   15099:             }
                   15100:         }
1.1149    raeburn  15101:         if (length($restitle) > 12) {
                   15102:             $restitle = substr($restitle,0,12);
                   15103:         }
1.1015    raeburn  15104:         push(@pathitems,$restitle);
                   15105:         $path .= join('/',@pathitems);
                   15106:     }
                   15107:     return ($path,$multiresp);
                   15108: }
                   15109: 
                   15110: =pod
                   15111: 
1.464     albertel 15112: =back
1.41      ng       15113: 
1.112     bowersj2 15114: =head1 CSV Upload/Handling functions
1.38      albertel 15115: 
1.41      ng       15116: =over 4
                   15117: 
1.648     raeburn  15118: =item * &upfile_store($r)
1.41      ng       15119: 
                   15120: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 15121: needs $env{'form.upfile'}
1.41      ng       15122: returns $datatoken to be put into hidden field
                   15123: 
                   15124: =cut
1.31      albertel 15125: 
                   15126: sub upfile_store {
                   15127:     my $r=shift;
1.258     albertel 15128:     $env{'form.upfile'}=~s/\r/\n/gs;
                   15129:     $env{'form.upfile'}=~s/\f/\n/gs;
                   15130:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   15131:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 15132: 
1.1299    raeburn  15133:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   15134:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   15135:                                      time.'_'.$$);
                   15136:     return if ($datatoken eq '');
                   15137: 
1.31      albertel 15138:     {
1.158     raeburn  15139:         my $datafile = $r->dir_config('lonDaemons').
                   15140:                            '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15141:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 15142:             print $fh $env{'form.upfile'};
1.158     raeburn  15143:             close($fh);
                   15144:         }
1.31      albertel 15145:     }
                   15146:     return $datatoken;
                   15147: }
                   15148: 
1.56      matthew  15149: =pod
                   15150: 
1.1290    raeburn  15151: =item * &load_tmp_file($r,$datatoken)
1.41      ng       15152: 
                   15153: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1290    raeburn  15154: $datatoken is the name to assign to the temporary file.
1.258     albertel 15155: sets $env{'form.upfile'} to the contents of the file
1.41      ng       15156: 
                   15157: =cut
1.31      albertel 15158: 
                   15159: sub load_tmp_file {
1.1290    raeburn  15160:     my ($r,$datatoken) = @_;
                   15161:     return if ($datatoken eq '');
1.31      albertel 15162:     my @studentdata=();
                   15163:     {
1.158     raeburn  15164:         my $studentfile = $r->dir_config('lonDaemons').
1.1290    raeburn  15165:                               '/tmp/'.$datatoken.'.tmp';
1.1317    raeburn  15166:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  15167:             @studentdata=<$fh>;
                   15168:             close($fh);
                   15169:         }
1.31      albertel 15170:     }
1.258     albertel 15171:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 15172: }
                   15173: 
1.1290    raeburn  15174: sub valid_datatoken {
                   15175:     my ($datatoken) = @_;
1.1325    raeburn  15176:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1290    raeburn  15177:         return $datatoken;
                   15178:     }
                   15179:     return;
                   15180: }
                   15181: 
1.56      matthew  15182: =pod
                   15183: 
1.648     raeburn  15184: =item * &upfile_record_sep()
1.41      ng       15185: 
                   15186: Separate uploaded file into records
                   15187: returns array of records,
1.258     albertel 15188: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       15189: 
                   15190: =cut
1.31      albertel 15191: 
                   15192: sub upfile_record_sep {
1.258     albertel 15193:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 15194:     } else {
1.248     albertel 15195: 	my @records;
1.258     albertel 15196: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 15197: 	    if ($line=~/^\s*$/) { next; }
                   15198: 	    push(@records,$line);
                   15199: 	}
                   15200: 	return @records;
1.31      albertel 15201:     }
                   15202: }
                   15203: 
1.56      matthew  15204: =pod
                   15205: 
1.648     raeburn  15206: =item * &record_sep($record)
1.41      ng       15207: 
1.258     albertel 15208: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       15209: 
                   15210: =cut
                   15211: 
1.263     www      15212: sub takeleft {
                   15213:     my $index=shift;
                   15214:     return substr('0000'.$index,-4,4);
                   15215: }
                   15216: 
1.31      albertel 15217: sub record_sep {
                   15218:     my $record=shift;
                   15219:     my %components=();
1.258     albertel 15220:     if ($env{'form.upfiletype'} eq 'xml') {
                   15221:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 15222:         my $i=0;
1.356     albertel 15223:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 15224:             $field=~s/^(\"|\')//;
                   15225:             $field=~s/(\"|\')$//;
1.263     www      15226:             $components{&takeleft($i)}=$field;
1.31      albertel 15227:             $i++;
                   15228:         }
1.258     albertel 15229:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 15230:         my $i=0;
1.356     albertel 15231:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 15232:             $field=~s/^(\"|\')//;
                   15233:             $field=~s/(\"|\')$//;
1.263     www      15234:             $components{&takeleft($i)}=$field;
1.31      albertel 15235:             $i++;
                   15236:         }
                   15237:     } else {
1.561     www      15238:         my $separator=',';
1.480     banghart 15239:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      15240:             $separator=';';
1.480     banghart 15241:         }
1.31      albertel 15242:         my $i=0;
1.561     www      15243: # the character we are looking for to indicate the end of a quote or a record 
                   15244:         my $looking_for=$separator;
                   15245: # do not add the characters to the fields
                   15246:         my $ignore=0;
                   15247: # we just encountered a separator (or the beginning of the record)
                   15248:         my $just_found_separator=1;
                   15249: # store the field we are working on here
                   15250:         my $field='';
                   15251: # work our way through all characters in record
                   15252:         foreach my $character ($record=~/(.)/g) {
                   15253:             if ($character eq $looking_for) {
                   15254:                if ($character ne $separator) {
                   15255: # Found the end of a quote, again looking for separator
                   15256:                   $looking_for=$separator;
                   15257:                   $ignore=1;
                   15258:                } else {
                   15259: # Found a separator, store away what we got
                   15260:                   $components{&takeleft($i)}=$field;
                   15261: 	          $i++;
                   15262:                   $just_found_separator=1;
                   15263:                   $ignore=0;
                   15264:                   $field='';
                   15265:                }
                   15266:                next;
                   15267:             }
                   15268: # single or double quotation marks after a separator indicate beginning of a quote
                   15269: # we are now looking for the end of the quote and need to ignore separators
                   15270:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   15271:                $looking_for=$character;
                   15272:                next;
                   15273:             }
                   15274: # ignore would be true after we reached the end of a quote
                   15275:             if ($ignore) { next; }
                   15276:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   15277:             $field.=$character;
                   15278:             $just_found_separator=0; 
1.31      albertel 15279:         }
1.561     www      15280: # catch the very last entry, since we never encountered the separator
                   15281:         $components{&takeleft($i)}=$field;
1.31      albertel 15282:     }
                   15283:     return %components;
                   15284: }
                   15285: 
1.144     matthew  15286: ######################################################
                   15287: ######################################################
                   15288: 
1.56      matthew  15289: =pod
                   15290: 
1.648     raeburn  15291: =item * &upfile_select_html()
1.41      ng       15292: 
1.144     matthew  15293: Return HTML code to select a file from the users machine and specify 
                   15294: the file type.
1.41      ng       15295: 
                   15296: =cut
                   15297: 
1.144     matthew  15298: ######################################################
                   15299: ######################################################
1.31      albertel 15300: sub upfile_select_html {
1.144     matthew  15301:     my %Types = (
                   15302:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 15303:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  15304:                  space => &mt('Space separated'),
                   15305:                  tab   => &mt('Tabulator separated'),
                   15306: #                 xml   => &mt('HTML/XML'),
                   15307:                  );
                   15308:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  15309:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  15310:     foreach my $type (sort(keys(%Types))) {
                   15311:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   15312:     }
                   15313:     $Str .= "</select>\n";
                   15314:     return $Str;
1.31      albertel 15315: }
                   15316: 
1.301     albertel 15317: sub get_samples {
                   15318:     my ($records,$toget) = @_;
                   15319:     my @samples=({});
                   15320:     my $got=0;
                   15321:     foreach my $rec (@$records) {
                   15322: 	my %temp = &record_sep($rec);
                   15323: 	if (! grep(/\S/, values(%temp))) { next; }
                   15324: 	if (%temp) {
                   15325: 	    $samples[$got]=\%temp;
                   15326: 	    $got++;
                   15327: 	    if ($got == $toget) { last; }
                   15328: 	}
                   15329:     }
                   15330:     return \@samples;
                   15331: }
                   15332: 
1.144     matthew  15333: ######################################################
                   15334: ######################################################
                   15335: 
1.56      matthew  15336: =pod
                   15337: 
1.648     raeburn  15338: =item * &csv_print_samples($r,$records)
1.41      ng       15339: 
                   15340: Prints a table of sample values from each column uploaded $r is an
                   15341: Apache Request ref, $records is an arrayref from
                   15342: &Apache::loncommon::upfile_record_sep
                   15343: 
                   15344: =cut
                   15345: 
1.144     matthew  15346: ######################################################
                   15347: ######################################################
1.31      albertel 15348: sub csv_print_samples {
                   15349:     my ($r,$records) = @_;
1.662     bisitz   15350:     my $samples = &get_samples($records,5);
1.301     albertel 15351: 
1.594     raeburn  15352:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   15353:               &start_data_table_header_row());
1.356     albertel 15354:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   15355:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  15356:     $r->print(&end_data_table_header_row());
1.301     albertel 15357:     foreach my $hash (@$samples) {
1.594     raeburn  15358: 	$r->print(&start_data_table_row());
1.356     albertel 15359: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 15360: 	    $r->print('<td>');
1.356     albertel 15361: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 15362: 	    $r->print('</td>');
                   15363: 	}
1.594     raeburn  15364: 	$r->print(&end_data_table_row());
1.31      albertel 15365:     }
1.594     raeburn  15366:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 15367: }
                   15368: 
1.144     matthew  15369: ######################################################
                   15370: ######################################################
                   15371: 
1.56      matthew  15372: =pod
                   15373: 
1.648     raeburn  15374: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       15375: 
                   15376: Prints a table to create associations between values and table columns.
1.144     matthew  15377: 
1.41      ng       15378: $r is an Apache Request ref,
                   15379: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  15380: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       15381: 
                   15382: =cut
                   15383: 
1.144     matthew  15384: ######################################################
                   15385: ######################################################
1.31      albertel 15386: sub csv_print_select_table {
                   15387:     my ($r,$records,$d) = @_;
1.301     albertel 15388:     my $i=0;
                   15389:     my $samples = &get_samples($records,1);
1.144     matthew  15390:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  15391: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  15392:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  15393:               '<th>'.&mt('Column').'</th>'.
                   15394:               &end_data_table_header_row()."\n");
1.356     albertel 15395:     foreach my $array_ref (@$d) {
                   15396: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  15397: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 15398: 
1.875     bisitz   15399: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  15400: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 15401: 	$r->print('<option value="none"></option>');
1.356     albertel 15402: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   15403: 	    $r->print('<option value="'.$sample.'"'.
                   15404:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   15405:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 15406: 	}
1.594     raeburn  15407: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 15408: 	$i++;
                   15409:     }
1.594     raeburn  15410:     $r->print(&end_data_table());
1.31      albertel 15411:     $i--;
                   15412:     return $i;
                   15413: }
1.56      matthew  15414: 
1.144     matthew  15415: ######################################################
                   15416: ######################################################
                   15417: 
1.56      matthew  15418: =pod
1.31      albertel 15419: 
1.648     raeburn  15420: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       15421: 
                   15422: Prints a table of sample values from the upload and can make associate samples to internal names.
                   15423: 
                   15424: $r is an Apache Request ref,
                   15425: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   15426: $d is an array of 2 element arrays (internal name, displayed name)
                   15427: 
                   15428: =cut
                   15429: 
1.144     matthew  15430: ######################################################
                   15431: ######################################################
1.31      albertel 15432: sub csv_samples_select_table {
                   15433:     my ($r,$records,$d) = @_;
                   15434:     my $i=0;
1.144     matthew  15435:     #
1.662     bisitz   15436:     my $max_samples = 5;
                   15437:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  15438:     $r->print(&start_data_table().
                   15439:               &start_data_table_header_row().'<th>'.
                   15440:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   15441:               &end_data_table_header_row());
1.301     albertel 15442: 
                   15443:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  15444: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  15445: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 15446: 	foreach my $option (@$d) {
                   15447: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  15448: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 15449:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  15450:                       $display.'</option>');
1.31      albertel 15451: 	}
                   15452: 	$r->print('</select></td><td>');
1.662     bisitz   15453: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 15454: 	    if (defined($samples->[$line]{$key})) { 
                   15455: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   15456: 	    }
                   15457: 	}
1.594     raeburn  15458: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 15459: 	$i++;
                   15460:     }
1.594     raeburn  15461:     $r->print(&end_data_table());
1.31      albertel 15462:     $i--;
                   15463:     return($i);
1.115     matthew  15464: }
                   15465: 
1.144     matthew  15466: ######################################################
                   15467: ######################################################
                   15468: 
1.115     matthew  15469: =pod
                   15470: 
1.648     raeburn  15471: =item * &clean_excel_name($name)
1.115     matthew  15472: 
                   15473: Returns a replacement for $name which does not contain any illegal characters.
                   15474: 
                   15475: =cut
                   15476: 
1.144     matthew  15477: ######################################################
                   15478: ######################################################
1.115     matthew  15479: sub clean_excel_name {
                   15480:     my ($name) = @_;
                   15481:     $name =~ s/[:\*\?\/\\]//g;
                   15482:     if (length($name) > 31) {
                   15483:         $name = substr($name,0,31);
                   15484:     }
                   15485:     return $name;
1.25      albertel 15486: }
1.84      albertel 15487: 
1.85      albertel 15488: =pod
                   15489: 
1.648     raeburn  15490: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 15491: 
                   15492: Returns either 1 or undef
                   15493: 
                   15494: 1 if the part is to be hidden, undef if it is to be shown
                   15495: 
                   15496: Arguments are:
                   15497: 
                   15498: $id the id of the part to be checked
                   15499: $symb, optional the symb of the resource to check
                   15500: $udom, optional the domain of the user to check for
                   15501: $uname, optional the username of the user to check for
                   15502: 
                   15503: =cut
1.84      albertel 15504: 
                   15505: sub check_if_partid_hidden {
                   15506:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 15507:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 15508: 					 $symb,$udom,$uname);
1.141     albertel 15509:     my $truth=1;
                   15510:     #if the string starts with !, then the list is the list to show not hide
                   15511:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 15512:     my @hiddenlist=split(/,/,$hiddenparts);
                   15513:     foreach my $checkid (@hiddenlist) {
1.141     albertel 15514: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 15515:     }
1.141     albertel 15516:     return !$truth;
1.84      albertel 15517: }
1.127     matthew  15518: 
1.138     matthew  15519: 
                   15520: ############################################################
                   15521: ############################################################
                   15522: 
                   15523: =pod
                   15524: 
1.157     matthew  15525: =back 
                   15526: 
1.138     matthew  15527: =head1 cgi-bin script and graphing routines
                   15528: 
1.157     matthew  15529: =over 4
                   15530: 
1.648     raeburn  15531: =item * &get_cgi_id()
1.138     matthew  15532: 
                   15533: Inputs: none
                   15534: 
                   15535: Returns an id which can be used to pass environment variables
                   15536: to various cgi-bin scripts.  These environment variables will
                   15537: be removed from the users environment after a given time by
                   15538: the routine &Apache::lonnet::transfer_profile_to_env.
                   15539: 
                   15540: =cut
                   15541: 
                   15542: ############################################################
                   15543: ############################################################
1.152     albertel 15544: my $uniq=0;
1.136     matthew  15545: sub get_cgi_id {
1.154     albertel 15546:     $uniq=($uniq+1)%100000;
1.280     albertel 15547:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  15548: }
                   15549: 
1.127     matthew  15550: ############################################################
                   15551: ############################################################
                   15552: 
                   15553: =pod
                   15554: 
1.648     raeburn  15555: =item * &DrawBarGraph()
1.127     matthew  15556: 
1.138     matthew  15557: Facilitates the plotting of data in a (stacked) bar graph.
                   15558: Puts plot definition data into the users environment in order for 
                   15559: graph.png to plot it.  Returns an <img> tag for the plot.
                   15560: The bars on the plot are labeled '1','2',...,'n'.
                   15561: 
                   15562: Inputs:
                   15563: 
                   15564: =over 4
                   15565: 
                   15566: =item $Title: string, the title of the plot
                   15567: 
                   15568: =item $xlabel: string, text describing the X-axis of the plot
                   15569: 
                   15570: =item $ylabel: string, text describing the Y-axis of the plot
                   15571: 
                   15572: =item $Max: scalar, the maximum Y value to use in the plot
                   15573: If $Max is < any data point, the graph will not be rendered.
                   15574: 
1.140     matthew  15575: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  15576: they are plotted.  If undefined, default values will be used.
                   15577: 
1.178     matthew  15578: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   15579: 
1.138     matthew  15580: =item @Values: An array of array references.  Each array reference holds data
                   15581: to be plotted in a stacked bar chart.
                   15582: 
1.239     matthew  15583: =item If the final element of @Values is a hash reference the key/value
                   15584: pairs will be added to the graph definition.
                   15585: 
1.138     matthew  15586: =back
                   15587: 
                   15588: Returns:
                   15589: 
                   15590: An <img> tag which references graph.png and the appropriate identifying
                   15591: information for the plot.
                   15592: 
1.127     matthew  15593: =cut
                   15594: 
                   15595: ############################################################
                   15596: ############################################################
1.134     matthew  15597: sub DrawBarGraph {
1.178     matthew  15598:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  15599:     #
                   15600:     if (! defined($colors)) {
                   15601:         $colors = ['#33ff00', 
                   15602:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   15603:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   15604:                   ]; 
                   15605:     }
1.228     matthew  15606:     my $extra_settings = {};
                   15607:     if (ref($Values[-1]) eq 'HASH') {
                   15608:         $extra_settings = pop(@Values);
                   15609:     }
1.127     matthew  15610:     #
1.136     matthew  15611:     my $identifier = &get_cgi_id();
                   15612:     my $id = 'cgi.'.$identifier;        
1.129     matthew  15613:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  15614:         return '';
                   15615:     }
1.225     matthew  15616:     #
                   15617:     my @Labels;
                   15618:     if (defined($labels)) {
                   15619:         @Labels = @$labels;
                   15620:     } else {
                   15621:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1263    raeburn  15622:             push(@Labels,$i+1);
1.225     matthew  15623:         }
                   15624:     }
                   15625:     #
1.129     matthew  15626:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  15627:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  15628:     my %ValuesHash;
                   15629:     my $NumSets=1;
                   15630:     foreach my $array (@Values) {
                   15631:         next if (! ref($array));
1.136     matthew  15632:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  15633:             join(',',@$array);
1.129     matthew  15634:     }
1.127     matthew  15635:     #
1.136     matthew  15636:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  15637:     if ($NumBars < 3) {
                   15638:         $width = 120+$NumBars*32;
1.220     matthew  15639:         $xskip = 1;
1.225     matthew  15640:         $bar_width = 30;
                   15641:     } elsif ($NumBars < 5) {
                   15642:         $width = 120+$NumBars*20;
                   15643:         $xskip = 1;
                   15644:         $bar_width = 20;
1.220     matthew  15645:     } elsif ($NumBars < 10) {
1.136     matthew  15646:         $width = 120+$NumBars*15;
                   15647:         $xskip = 1;
                   15648:         $bar_width = 15;
                   15649:     } elsif ($NumBars <= 25) {
                   15650:         $width = 120+$NumBars*11;
                   15651:         $xskip = 5;
                   15652:         $bar_width = 8;
                   15653:     } elsif ($NumBars <= 50) {
                   15654:         $width = 120+$NumBars*8;
                   15655:         $xskip = 5;
                   15656:         $bar_width = 4;
                   15657:     } else {
                   15658:         $width = 120+$NumBars*8;
                   15659:         $xskip = 5;
                   15660:         $bar_width = 4;
                   15661:     }
                   15662:     #
1.137     matthew  15663:     $Max = 1 if ($Max < 1);
                   15664:     if ( int($Max) < $Max ) {
                   15665:         $Max++;
                   15666:         $Max = int($Max);
                   15667:     }
1.127     matthew  15668:     $Title  = '' if (! defined($Title));
                   15669:     $xlabel = '' if (! defined($xlabel));
                   15670:     $ylabel = '' if (! defined($ylabel));
1.369     www      15671:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   15672:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   15673:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  15674:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  15675:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   15676:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   15677:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   15678:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15679:     $ValuesHash{$id.'.height'}   = $height;
                   15680:     $ValuesHash{$id.'.width'}    = $width;
                   15681:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   15682:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   15683:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  15684:     #
1.228     matthew  15685:     # Deal with other parameters
                   15686:     while (my ($key,$value) = each(%$extra_settings)) {
                   15687:         $ValuesHash{$id.'.'.$key} = $value;
                   15688:     }
                   15689:     #
1.646     raeburn  15690:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  15691:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15692: }
                   15693: 
                   15694: ############################################################
                   15695: ############################################################
                   15696: 
                   15697: =pod
                   15698: 
1.648     raeburn  15699: =item * &DrawXYGraph()
1.137     matthew  15700: 
1.138     matthew  15701: Facilitates the plotting of data in an XY graph.
                   15702: Puts plot definition data into the users environment in order for 
                   15703: graph.png to plot it.  Returns an <img> tag for the plot.
                   15704: 
                   15705: Inputs:
                   15706: 
                   15707: =over 4
                   15708: 
                   15709: =item $Title: string, the title of the plot
                   15710: 
                   15711: =item $xlabel: string, text describing the X-axis of the plot
                   15712: 
                   15713: =item $ylabel: string, text describing the Y-axis of the plot
                   15714: 
                   15715: =item $Max: scalar, the maximum Y value to use in the plot
                   15716: If $Max is < any data point, the graph will not be rendered.
                   15717: 
                   15718: =item $colors: Array ref containing the hex color codes for the data to be 
                   15719: plotted in.  If undefined, default values will be used.
                   15720: 
                   15721: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15722: 
                   15723: =item $Ydata: Array ref containing Array refs.  
1.185     www      15724: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  15725: 
                   15726: =item %Values: hash indicating or overriding any default values which are 
                   15727: passed to graph.png.  
                   15728: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15729: 
                   15730: =back
                   15731: 
                   15732: Returns:
                   15733: 
                   15734: An <img> tag which references graph.png and the appropriate identifying
                   15735: information for the plot.
                   15736: 
1.137     matthew  15737: =cut
                   15738: 
                   15739: ############################################################
                   15740: ############################################################
                   15741: sub DrawXYGraph {
                   15742:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   15743:     #
                   15744:     # Create the identifier for the graph
                   15745:     my $identifier = &get_cgi_id();
                   15746:     my $id = 'cgi.'.$identifier;
                   15747:     #
                   15748:     $Title  = '' if (! defined($Title));
                   15749:     $xlabel = '' if (! defined($xlabel));
                   15750:     $ylabel = '' if (! defined($ylabel));
                   15751:     my %ValuesHash = 
                   15752:         (
1.369     www      15753:          $id.'.title'  => &escape($Title),
                   15754:          $id.'.xlabel' => &escape($xlabel),
                   15755:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  15756:          $id.'.y_max_value'=> $Max,
                   15757:          $id.'.labels'     => join(',',@$Xlabels),
                   15758:          $id.'.PlotType'   => 'XY',
                   15759:          );
                   15760:     #
                   15761:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15762:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15763:     }
                   15764:     #
                   15765:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   15766:         return '';
                   15767:     }
                   15768:     my $NumSets=1;
1.138     matthew  15769:     foreach my $array (@{$Ydata}){
1.137     matthew  15770:         next if (! ref($array));
                   15771:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   15772:     }
1.138     matthew  15773:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  15774:     #
                   15775:     # Deal with other parameters
                   15776:     while (my ($key,$value) = each(%Values)) {
                   15777:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  15778:     }
                   15779:     #
1.646     raeburn  15780:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  15781:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   15782: }
                   15783: 
                   15784: ############################################################
                   15785: ############################################################
                   15786: 
                   15787: =pod
                   15788: 
1.648     raeburn  15789: =item * &DrawXYYGraph()
1.138     matthew  15790: 
                   15791: Facilitates the plotting of data in an XY graph with two Y axes.
                   15792: Puts plot definition data into the users environment in order for 
                   15793: graph.png to plot it.  Returns an <img> tag for the plot.
                   15794: 
                   15795: Inputs:
                   15796: 
                   15797: =over 4
                   15798: 
                   15799: =item $Title: string, the title of the plot
                   15800: 
                   15801: =item $xlabel: string, text describing the X-axis of the plot
                   15802: 
                   15803: =item $ylabel: string, text describing the Y-axis of the plot
                   15804: 
                   15805: =item $colors: Array ref containing the hex color codes for the data to be 
                   15806: plotted in.  If undefined, default values will be used.
                   15807: 
                   15808: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   15809: 
                   15810: =item $Ydata1: The first data set
                   15811: 
                   15812: =item $Min1: The minimum value of the left Y-axis
                   15813: 
                   15814: =item $Max1: The maximum value of the left Y-axis
                   15815: 
                   15816: =item $Ydata2: The second data set
                   15817: 
                   15818: =item $Min2: The minimum value of the right Y-axis
                   15819: 
                   15820: =item $Max2: The maximum value of the left Y-axis
                   15821: 
                   15822: =item %Values: hash indicating or overriding any default values which are 
                   15823: passed to graph.png.  
                   15824: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   15825: 
                   15826: =back
                   15827: 
                   15828: Returns:
                   15829: 
                   15830: An <img> tag which references graph.png and the appropriate identifying
                   15831: information for the plot.
1.136     matthew  15832: 
                   15833: =cut
                   15834: 
                   15835: ############################################################
                   15836: ############################################################
1.137     matthew  15837: sub DrawXYYGraph {
                   15838:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   15839:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  15840:     #
                   15841:     # Create the identifier for the graph
                   15842:     my $identifier = &get_cgi_id();
                   15843:     my $id = 'cgi.'.$identifier;
                   15844:     #
                   15845:     $Title  = '' if (! defined($Title));
                   15846:     $xlabel = '' if (! defined($xlabel));
                   15847:     $ylabel = '' if (! defined($ylabel));
                   15848:     my %ValuesHash = 
                   15849:         (
1.369     www      15850:          $id.'.title'  => &escape($Title),
                   15851:          $id.'.xlabel' => &escape($xlabel),
                   15852:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  15853:          $id.'.labels' => join(',',@$Xlabels),
                   15854:          $id.'.PlotType' => 'XY',
                   15855:          $id.'.NumSets' => 2,
1.137     matthew  15856:          $id.'.two_axes' => 1,
                   15857:          $id.'.y1_max_value' => $Max1,
                   15858:          $id.'.y1_min_value' => $Min1,
                   15859:          $id.'.y2_max_value' => $Max2,
                   15860:          $id.'.y2_min_value' => $Min2,
1.136     matthew  15861:          );
                   15862:     #
1.137     matthew  15863:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   15864:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   15865:     }
                   15866:     #
                   15867:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   15868:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  15869:         return '';
                   15870:     }
                   15871:     my $NumSets=1;
1.137     matthew  15872:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  15873:         next if (! ref($array));
                   15874:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  15875:     }
                   15876:     #
                   15877:     # Deal with other parameters
                   15878:     while (my ($key,$value) = each(%Values)) {
                   15879:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  15880:     }
                   15881:     #
1.646     raeburn  15882:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 15883:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  15884: }
                   15885: 
                   15886: ############################################################
                   15887: ############################################################
                   15888: 
                   15889: =pod
                   15890: 
1.157     matthew  15891: =back 
                   15892: 
1.139     matthew  15893: =head1 Statistics helper routines?  
                   15894: 
                   15895: Bad place for them but what the hell.
                   15896: 
1.157     matthew  15897: =over 4
                   15898: 
1.648     raeburn  15899: =item * &chartlink()
1.139     matthew  15900: 
                   15901: Returns a link to the chart for a specific student.  
                   15902: 
                   15903: Inputs:
                   15904: 
                   15905: =over 4
                   15906: 
                   15907: =item $linktext: The text of the link
                   15908: 
                   15909: =item $sname: The students username
                   15910: 
                   15911: =item $sdomain: The students domain
                   15912: 
                   15913: =back
                   15914: 
1.157     matthew  15915: =back
                   15916: 
1.139     matthew  15917: =cut
                   15918: 
                   15919: ############################################################
                   15920: ############################################################
                   15921: sub chartlink {
                   15922:     my ($linktext, $sname, $sdomain) = @_;
                   15923:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      15924:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 15925:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  15926:        '">'.$linktext.'</a>';
1.153     matthew  15927: }
                   15928: 
                   15929: #######################################################
                   15930: #######################################################
                   15931: 
                   15932: =pod
                   15933: 
                   15934: =head1 Course Environment Routines
1.157     matthew  15935: 
                   15936: =over 4
1.153     matthew  15937: 
1.648     raeburn  15938: =item * &restore_course_settings()
1.153     matthew  15939: 
1.648     raeburn  15940: =item * &store_course_settings()
1.153     matthew  15941: 
                   15942: Restores/Store indicated form parameters from the course environment.
                   15943: Will not overwrite existing values of the form parameters.
                   15944: 
                   15945: Inputs: 
                   15946: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   15947: 
                   15948: a hash ref describing the data to be stored.  For example:
                   15949:    
                   15950: %Save_Parameters = ('Status' => 'scalar',
                   15951:     'chartoutputmode' => 'scalar',
                   15952:     'chartoutputdata' => 'scalar',
                   15953:     'Section' => 'array',
1.373     raeburn  15954:     'Group' => 'array',
1.153     matthew  15955:     'StudentData' => 'array',
                   15956:     'Maps' => 'array');
                   15957: 
                   15958: Returns: both routines return nothing
                   15959: 
1.631     raeburn  15960: =back
                   15961: 
1.153     matthew  15962: =cut
                   15963: 
                   15964: #######################################################
                   15965: #######################################################
                   15966: sub store_course_settings {
1.496     albertel 15967:     return &store_settings($env{'request.course.id'},@_);
                   15968: }
                   15969: 
                   15970: sub store_settings {
1.153     matthew  15971:     # save to the environment
                   15972:     # appenv the same items, just to be safe
1.300     albertel 15973:     my $udom  = $env{'user.domain'};
                   15974:     my $uname = $env{'user.name'};
1.496     albertel 15975:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  15976:     my %SaveHash;
                   15977:     my %AppHash;
                   15978:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 15979:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 15980:         my $envname = 'environment.'.$basename;
1.258     albertel 15981:         if (exists($env{'form.'.$setting})) {
1.153     matthew  15982:             # Save this value away
                   15983:             if ($type eq 'scalar' &&
1.258     albertel 15984:                 (! exists($env{$envname}) || 
                   15985:                  $env{$envname} ne $env{'form.'.$setting})) {
                   15986:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   15987:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  15988:             } elsif ($type eq 'array') {
                   15989:                 my $stored_form;
1.258     albertel 15990:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  15991:                     $stored_form = join(',',
                   15992:                                         map {
1.369     www      15993:                                             &escape($_);
1.258     albertel 15994:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  15995:                 } else {
                   15996:                     $stored_form = 
1.369     www      15997:                         &escape($env{'form.'.$setting});
1.153     matthew  15998:                 }
                   15999:                 # Determine if the array contents are the same.
1.258     albertel 16000:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  16001:                     $SaveHash{$basename} = $stored_form;
                   16002:                     $AppHash{$envname}   = $stored_form;
                   16003:                 }
                   16004:             }
                   16005:         }
                   16006:     }
                   16007:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 16008:                                           $udom,$uname);
1.153     matthew  16009:     if ($put_result !~ /^(ok|delayed)/) {
                   16010:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   16011:                                  'got error:'.$put_result);
                   16012:     }
                   16013:     # Make sure these settings stick around in this session, too
1.646     raeburn  16014:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  16015:     return;
                   16016: }
                   16017: 
                   16018: sub restore_course_settings {
1.499     albertel 16019:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 16020: }
                   16021: 
                   16022: sub restore_settings {
                   16023:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  16024:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 16025:         next if (exists($env{'form.'.$setting}));
1.496     albertel 16026:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  16027:             '.'.$setting;
1.258     albertel 16028:         if (exists($env{$envname})) {
1.153     matthew  16029:             if ($type eq 'scalar') {
1.258     albertel 16030:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  16031:             } elsif ($type eq 'array') {
1.258     albertel 16032:                 $env{'form.'.$setting} = [ 
1.153     matthew  16033:                                            map { 
1.369     www      16034:                                                &unescape($_); 
1.258     albertel 16035:                                            } split(',',$env{$envname})
1.153     matthew  16036:                                            ];
                   16037:             }
                   16038:         }
                   16039:     }
1.127     matthew  16040: }
                   16041: 
1.618     raeburn  16042: #######################################################
                   16043: #######################################################
                   16044: 
                   16045: =pod
                   16046: 
                   16047: =head1 Domain E-mail Routines  
                   16048: 
                   16049: =over 4
                   16050: 
1.648     raeburn  16051: =item * &build_recipient_list()
1.618     raeburn  16052: 
1.1144    raeburn  16053: Build recipient lists for following types of e-mail:
1.766     raeburn  16054: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  16055: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   16056: module change checking, student/employee ID conflict checks, as
                   16057: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   16058: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  16059: 
                   16060: Inputs:
1.619     raeburn  16061: defmail (scalar - email address of default recipient), 
1.1144    raeburn  16062: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   16063: requestsmail, updatesmail, or idconflictsmail).
                   16064: 
1.619     raeburn  16065: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  16066: 
1.619     raeburn  16067: origmail (scalar - email address of recipient from loncapa.conf, 
1.1297    raeburn  16068: i.e., predates configuration by DC via domainprefs.pm
                   16069: 
                   16070: $requname username of requester (if mailing type is helpdeskmail)
                   16071: 
                   16072: $requdom domain of requester (if mailing type is helpdeskmail)
                   16073: 
                   16074: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
                   16075: 
1.618     raeburn  16076: 
1.655     raeburn  16077: Returns: comma separated list of addresses to which to send e-mail.
                   16078: 
                   16079: =back
1.618     raeburn  16080: 
                   16081: =cut
                   16082: 
                   16083: ############################################################
                   16084: ############################################################
                   16085: sub build_recipient_list {
1.1297    raeburn  16086:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
1.618     raeburn  16087:     my @recipients;
1.1270    raeburn  16088:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  16089:     my %domconfig =
1.1270    raeburn  16090:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  16091:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  16092:         if (exists($domconfig{'contacts'}{$mailing})) {
                   16093:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   16094:                 my @contacts = ('adminemail','supportemail');
                   16095:                 foreach my $item (@contacts) {
                   16096:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   16097:                         my $addr = $domconfig{'contacts'}{$item}; 
                   16098:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16099:                             push(@recipients,$addr);
                   16100:                         }
1.619     raeburn  16101:                     }
1.1270    raeburn  16102:                 }
                   16103:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   16104:                 if ($mailing eq 'helpdeskmail') {
                   16105:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   16106:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   16107:                         my @ok_bccs;
                   16108:                         foreach my $bcc (@bccs) {
                   16109:                             $bcc =~ s/^\s+//g;
                   16110:                             $bcc =~ s/\s+$//g;
                   16111:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16112:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16113:                                     push(@ok_bccs,$bcc);
                   16114:                                 }
                   16115:                             }
                   16116:                         }
                   16117:                         if (@ok_bccs > 0) {
                   16118:                             $allbcc = join(', ',@ok_bccs);
                   16119:                         }
                   16120:                     }
                   16121:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  16122:                 }
                   16123:             }
1.766     raeburn  16124:         } elsif ($origmail ne '') {
1.1270    raeburn  16125:             $lastresort = $origmail;
1.618     raeburn  16126:         }
1.1297    raeburn  16127:         if ($mailing eq 'helpdeskmail') {
                   16128:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
                   16129:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
                   16130:                 my ($inststatus,$inststatus_checked);
                   16131:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   16132:                     ($env{'user.domain'} ne 'public')) {
                   16133:                     $inststatus_checked = 1;
                   16134:                     $inststatus = $env{'environment.inststatus'};
                   16135:                 }
                   16136:                 unless ($inststatus_checked) {
                   16137:                     if (($requname ne '') && ($requdom ne '')) {
                   16138:                         if (($requname =~ /^$match_username$/) &&
                   16139:                             ($requdom =~ /^$match_domain$/) &&
                   16140:                             (&Apache::lonnet::domain($requdom))) {
                   16141:                             my $requhome = &Apache::lonnet::homeserver($requname,
                   16142:                                                                       $requdom);
                   16143:                             unless ($requhome eq 'no_host') {
                   16144:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
                   16145:                                 $inststatus = $userenv{'inststatus'};
                   16146:                                 $inststatus_checked = 1;
                   16147:                             }
                   16148:                         }
                   16149:                     }
                   16150:                 }
                   16151:                 unless ($inststatus_checked) {
                   16152:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
                   16153:                         my %srch = (srchby     => 'email',
                   16154:                                     srchdomain => $defdom,
                   16155:                                     srchterm   => $reqemail,
                   16156:                                     srchtype   => 'exact');
                   16157:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
                   16158:                         foreach my $uname (keys(%srch_results)) {
                   16159:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16160:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16161:                                 $inststatus_checked = 1;
                   16162:                                 last;
                   16163:                             }
                   16164:                         }
                   16165:                         unless ($inststatus_checked) {
                   16166:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
                   16167:                             if ($dirsrchres eq 'ok') {
                   16168:                                 foreach my $uname (keys(%srch_results)) {
                   16169:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
                   16170:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
                   16171:                                         $inststatus_checked = 1;
                   16172:                                         last;
                   16173:                                     }
                   16174:                                 }
                   16175:                             }
                   16176:                         }
                   16177:                     }
                   16178:                 }
                   16179:                 if ($inststatus ne '') {
                   16180:                     foreach my $status (split(/\:/,$inststatus)) {
                   16181:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
                   16182:                             my @contacts = ('adminemail','supportemail');
                   16183:                             foreach my $item (@contacts) {
                   16184:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
                   16185:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
                   16186:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16187:                                         push(@recipients,$addr);
                   16188:                                     }
                   16189:                                 }
                   16190:                             }
                   16191:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
                   16192:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
                   16193:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
                   16194:                                 my @ok_bccs;
                   16195:                                 foreach my $bcc (@bccs) {
                   16196:                                     $bcc =~ s/^\s+//g;
                   16197:                                     $bcc =~ s/\s+$//g;
                   16198:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16199:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16200:                                             push(@ok_bccs,$bcc);
                   16201:                                         }
                   16202:                                     }
                   16203:                                 }
                   16204:                                 if (@ok_bccs > 0) {
                   16205:                                     $allbcc = join(', ',@ok_bccs);
                   16206:                                 }
                   16207:                             }
                   16208:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
                   16209:                             last;
                   16210:                         }
                   16211:                     }
                   16212:                 }
                   16213:             }
                   16214:         }
1.619     raeburn  16215:     } elsif ($origmail ne '') {
1.1270    raeburn  16216:         $lastresort = $origmail;
                   16217:     }
1.1297    raeburn  16218:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1270    raeburn  16219:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   16220:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   16221:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   16222:             my %what = (
                   16223:                           perlvar => 1,
                   16224:                        );
                   16225:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   16226:             if ($primary) {
                   16227:                 my $gotaddr;
                   16228:                 my ($result,$returnhash) =
                   16229:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   16230:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   16231:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   16232:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   16233:                         $gotaddr = 1;
                   16234:                     }
                   16235:                 }
                   16236:                 unless ($gotaddr) {
                   16237:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   16238:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   16239:                     unless ($uintdom eq $intdom) {
                   16240:                         my %domconfig =
                   16241:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   16242:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   16243:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   16244:                                 my @contacts = ('adminemail','supportemail');
                   16245:                                 foreach my $item (@contacts) {
                   16246:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   16247:                                         my $addr = $domconfig{'contacts'}{$item};
                   16248:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16249:                                             push(@recipients,$addr);
                   16250:                                         }
                   16251:                                     }
                   16252:                                 }
                   16253:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   16254:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   16255:                                 }
                   16256:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   16257:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   16258:                                     my @ok_bccs;
                   16259:                                     foreach my $bcc (@bccs) {
                   16260:                                         $bcc =~ s/^\s+//g;
                   16261:                                         $bcc =~ s/\s+$//g;
                   16262:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   16263:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   16264:                                                 push(@ok_bccs,$bcc);
                   16265:                                             }
                   16266:                                         }
                   16267:                                     }
                   16268:                                     if (@ok_bccs > 0) {
                   16269:                                         $allbcc = join(', ',@ok_bccs);
                   16270:                                     }
                   16271:                                 }
                   16272:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   16273:                             }
                   16274:                         }
                   16275:                     }
                   16276:                 }
                   16277:             }
                   16278:         }
1.618     raeburn  16279:     }
1.688     raeburn  16280:     if (defined($defmail)) {
                   16281:         if ($defmail ne '') {
                   16282:             push(@recipients,$defmail);
                   16283:         }
1.618     raeburn  16284:     }
                   16285:     if ($otheremails) {
1.619     raeburn  16286:         my @others;
                   16287:         if ($otheremails =~ /,/) {
                   16288:             @others = split(/,/,$otheremails);
1.618     raeburn  16289:         } else {
1.619     raeburn  16290:             push(@others,$otheremails);
                   16291:         }
                   16292:         foreach my $addr (@others) {
                   16293:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   16294:                 push(@recipients,$addr);
                   16295:             }
1.618     raeburn  16296:         }
                   16297:     }
1.1298    raeburn  16298:     if ($mailing eq 'helpdeskmail') {
1.1270    raeburn  16299:         if ((!@recipients) && ($lastresort ne '')) {
                   16300:             push(@recipients,$lastresort);
                   16301:         }
                   16302:     } elsif ($lastresort ne '') {
                   16303:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   16304:             push(@recipients,$lastresort);
                   16305:         }
                   16306:     }
1.1271    raeburn  16307:     my $recipientlist = join(',',@recipients);
1.1270    raeburn  16308:     if (wantarray) {
                   16309:         return ($recipientlist,$allbcc,$addtext);
                   16310:     } else {
                   16311:         return $recipientlist;
                   16312:     }
1.618     raeburn  16313: }
                   16314: 
1.127     matthew  16315: ############################################################
                   16316: ############################################################
1.154     albertel 16317: 
1.655     raeburn  16318: =pod
                   16319: 
1.1224    musolffc 16320: =over 4
                   16321: 
1.1223    musolffc 16322: =item * &mime_email()
                   16323: 
                   16324: Sends an email with a possible attachment
                   16325: 
                   16326: Inputs:
                   16327: 
                   16328: =over 4
                   16329: 
                   16330: from -              Sender's email address
                   16331: 
1.1343    raeburn  16332: replyto -           Reply-To email address
                   16333: 
1.1223    musolffc 16334: to -                Email address of recipient
                   16335: 
                   16336: subject -           Subject of email
                   16337: 
                   16338: body -              Body of email
                   16339: 
                   16340: cc_string -         Carbon copy email address
                   16341: 
                   16342: bcc -               Blind carbon copy email address
                   16343: 
                   16344: attachment_path -   Path of file to be attached
                   16345: 
                   16346: file_name -         Name of file to be attached
                   16347: 
                   16348: attachment_text -   The body of an attachment of type "TEXT"
                   16349: 
                   16350: =back
                   16351: 
                   16352: =back
                   16353: 
                   16354: =cut
                   16355: 
                   16356: ############################################################
                   16357: ############################################################
                   16358: 
                   16359: sub mime_email {
1.1343    raeburn  16360:     my ($from,$replyto,$to,$subject,$body,$cc_string,$bcc,$attachment_path, 
                   16361:         $file_name,$attachment_text) = @_;
                   16362:  
1.1223    musolffc 16363:     my $msg = MIME::Lite->new(
                   16364:              From    => $from,
                   16365:              To      => $to,
                   16366:              Subject => $subject,
                   16367:              Type    =>'TEXT',
                   16368:              Data    => $body,
                   16369:              );
1.1343    raeburn  16370:     if ($replyto ne '') {
                   16371:         $msg->add("Reply-To" => $replyto);
                   16372:     }
1.1223    musolffc 16373:     if ($cc_string ne '') {
                   16374:         $msg->add("Cc" => $cc_string);
                   16375:     }
                   16376:     if ($bcc ne '') {
                   16377:         $msg->add("Bcc" => $bcc);
                   16378:     }
                   16379:     $msg->attr("content-type"         => "text/plain");
                   16380:     $msg->attr("content-type.charset" => "UTF-8");
                   16381:     # Attach file if given
                   16382:     if ($attachment_path) {
                   16383:         unless ($file_name) {
                   16384:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
                   16385:         }
                   16386:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
                   16387:         $msg->attach(Type     => $type,
                   16388:                      Path     => $attachment_path,
                   16389:                      Filename => $file_name
                   16390:                      );
                   16391:     # Otherwise attach text if given
                   16392:     } elsif ($attachment_text) {
                   16393:         $msg->attach(Type => 'TEXT',
                   16394:                      Data => $attachment_text);
                   16395:     }
                   16396:     # Send it
                   16397:     $msg->send('sendmail');
                   16398: }
                   16399: 
                   16400: ############################################################
                   16401: ############################################################
                   16402: 
                   16403: =pod
                   16404: 
1.655     raeburn  16405: =head1 Course Catalog Routines
                   16406: 
                   16407: =over 4
                   16408: 
                   16409: =item * &gather_categories()
                   16410: 
                   16411: Converts category definitions - keys of categories hash stored in  
                   16412: coursecategories in configuration.db on the primary library server in a 
                   16413: domain - to an array.  Also generates javascript and idx hash used to 
                   16414: generate Domain Coordinator interface for editing Course Categories.
                   16415: 
                   16416: Inputs:
1.663     raeburn  16417: 
1.655     raeburn  16418: categories (reference to hash of category definitions).
1.663     raeburn  16419: 
1.655     raeburn  16420: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16421:       categories and subcategories).
1.663     raeburn  16422: 
1.655     raeburn  16423: idx (reference to hash of counters used in Domain Coordinator interface for 
                   16424:       editing Course Categories).
1.663     raeburn  16425: 
1.655     raeburn  16426: jsarray (reference to array of categories used to create Javascript arrays for
                   16427:          Domain Coordinator interface for editing Course Categories).
                   16428: 
                   16429: Returns: nothing
                   16430: 
                   16431: Side effects: populates cats, idx and jsarray. 
                   16432: 
                   16433: =cut
                   16434: 
                   16435: sub gather_categories {
                   16436:     my ($categories,$cats,$idx,$jsarray) = @_;
                   16437:     my %counters;
                   16438:     my $num = 0;
                   16439:     foreach my $item (keys(%{$categories})) {
                   16440:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   16441:         if ($container eq '' && $depth == 0) {
                   16442:             $cats->[$depth][$categories->{$item}] = $cat;
                   16443:         } else {
                   16444:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   16445:         }
                   16446:         my ($escitem,$tail) = split(/:/,$item,2);
                   16447:         if ($counters{$tail} eq '') {
                   16448:             $counters{$tail} = $num;
                   16449:             $num ++;
                   16450:         }
                   16451:         if (ref($idx) eq 'HASH') {
                   16452:             $idx->{$item} = $counters{$tail};
                   16453:         }
                   16454:         if (ref($jsarray) eq 'ARRAY') {
                   16455:             push(@{$jsarray->[$counters{$tail}]},$item);
                   16456:         }
                   16457:     }
                   16458:     return;
                   16459: }
                   16460: 
                   16461: =pod
                   16462: 
                   16463: =item * &extract_categories()
                   16464: 
                   16465: Used to generate breadcrumb trails for course categories.
                   16466: 
                   16467: Inputs:
1.663     raeburn  16468: 
1.655     raeburn  16469: categories (reference to hash of category definitions).
1.663     raeburn  16470: 
1.655     raeburn  16471: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16472:       categories and subcategories).
1.663     raeburn  16473: 
1.655     raeburn  16474: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  16475: 
1.655     raeburn  16476: allitems (reference to hash - key is category key 
                   16477:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16478: 
1.655     raeburn  16479: idx (reference to hash of counters used in Domain Coordinator interface for
                   16480:       editing Course Categories).
1.663     raeburn  16481: 
1.655     raeburn  16482: jsarray (reference to array of categories used to create Javascript arrays for
                   16483:          Domain Coordinator interface for editing Course Categories).
                   16484: 
1.665     raeburn  16485: subcats (reference to hash of arrays containing all subcategories within each 
                   16486:          category, -recursive)
                   16487: 
1.1321    raeburn  16488: maxd (reference to hash used to hold max depth for all top-level categories).
                   16489: 
1.655     raeburn  16490: Returns: nothing
                   16491: 
                   16492: Side effects: populates trails and allitems hash references.
                   16493: 
                   16494: =cut
                   16495: 
                   16496: sub extract_categories {
1.1321    raeburn  16497:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  16498:     if (ref($categories) eq 'HASH') {
                   16499:         &gather_categories($categories,$cats,$idx,$jsarray);
                   16500:         if (ref($cats->[0]) eq 'ARRAY') {
                   16501:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   16502:                 my $name = $cats->[0][$i];
                   16503:                 my $item = &escape($name).'::0';
                   16504:                 my $trailstr;
                   16505:                 if ($name eq 'instcode') {
                   16506:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  16507:                 } elsif ($name eq 'communities') {
                   16508:                     $trailstr = &mt('Communities');
1.1239    raeburn  16509:                 } elsif ($name eq 'placement') {
                   16510:                     $trailstr = &mt('Placement Tests');
1.655     raeburn  16511:                 } else {
                   16512:                     $trailstr = $name;
                   16513:                 }
                   16514:                 if ($allitems->{$item} eq '') {
                   16515:                     push(@{$trails},$trailstr);
                   16516:                     $allitems->{$item} = scalar(@{$trails})-1;
                   16517:                 }
                   16518:                 my @parents = ($name);
                   16519:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   16520:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   16521:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  16522:                         if (ref($subcats) eq 'HASH') {
                   16523:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   16524:                         }
1.1321    raeburn  16525:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  16526:                     }
                   16527:                 } else {
                   16528:                     if (ref($subcats) eq 'HASH') {
                   16529:                         $subcats->{$item} = [];
1.655     raeburn  16530:                     }
1.1321    raeburn  16531:                     if (ref($maxd) eq 'HASH') {
                   16532:                         $maxd->{$name} = 1;
                   16533:                     }
1.655     raeburn  16534:                 }
                   16535:             }
                   16536:         }
                   16537:     }
                   16538:     return;
                   16539: }
                   16540: 
                   16541: =pod
                   16542: 
1.1162    raeburn  16543: =item * &recurse_categories()
1.655     raeburn  16544: 
                   16545: Recursively used to generate breadcrumb trails for course categories.
                   16546: 
                   16547: Inputs:
1.663     raeburn  16548: 
1.655     raeburn  16549: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   16550:       categories and subcategories).
1.663     raeburn  16551: 
1.655     raeburn  16552: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  16553: 
                   16554: category (current course category, for which breadcrumb trail is being generated).
                   16555: 
                   16556: trails (reference to array of breadcrumb trails for each category).
                   16557: 
1.655     raeburn  16558: allitems (reference to hash - key is category key
                   16559:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  16560: 
1.655     raeburn  16561: parents (array containing containers directories for current category, 
                   16562:          back to top level). 
                   16563: 
                   16564: Returns: nothing
                   16565: 
                   16566: Side effects: populates trails and allitems hash references
                   16567: 
                   16568: =cut
                   16569: 
                   16570: sub recurse_categories {
1.1321    raeburn  16571:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  16572:     my $shallower = $depth - 1;
                   16573:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   16574:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   16575:             my $name = $cats->[$depth]{$category}[$k];
                   16576:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16577:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16578:             if ($allitems->{$item} eq '') {
                   16579:                 push(@{$trails},$trailstr);
                   16580:                 $allitems->{$item} = scalar(@{$trails})-1;
                   16581:             }
                   16582:             my $deeper = $depth+1;
                   16583:             push(@{$parents},$category);
1.665     raeburn  16584:             if (ref($subcats) eq 'HASH') {
                   16585:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   16586:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   16587:                     my $higher;
                   16588:                     if ($j > 0) {
                   16589:                         $higher = &escape($parents->[$j]).':'.
                   16590:                                   &escape($parents->[$j-1]).':'.$j;
                   16591:                     } else {
                   16592:                         $higher = &escape($parents->[$j]).'::'.$j;
                   16593:                     }
                   16594:                     push(@{$subcats->{$higher}},$subcat);
                   16595:                 }
                   16596:             }
                   16597:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1321    raeburn  16598:                                 $subcats,$maxd);
1.655     raeburn  16599:             pop(@{$parents});
                   16600:         }
                   16601:     } else {
                   16602:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1321    raeburn  16603:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  16604:         if ($allitems->{$item} eq '') {
                   16605:             push(@{$trails},$trailstr);
                   16606:             $allitems->{$item} = scalar(@{$trails})-1;
                   16607:         }
1.1321    raeburn  16608:         if (ref($maxd) eq 'HASH') {
                   16609:             if ($depth > $maxd->{$parents->[0]}) {
                   16610:                 $maxd->{$parents->[0]} = $depth;
                   16611:             }
                   16612:         }
1.655     raeburn  16613:     }
                   16614:     return;
                   16615: }
                   16616: 
1.663     raeburn  16617: =pod
                   16618: 
1.1162    raeburn  16619: =item * &assign_categories_table()
1.663     raeburn  16620: 
                   16621: Create a datatable for display of hierarchical categories in a domain,
                   16622: with checkboxes to allow a course to be categorized. 
                   16623: 
                   16624: Inputs:
                   16625: 
                   16626: cathash - reference to hash of categories defined for the domain (from
                   16627:           configuration.db)
                   16628: 
                   16629: currcat - scalar with an & separated list of categories assigned to a course. 
                   16630: 
1.919     raeburn  16631: type    - scalar contains course type (Course or Community).
                   16632: 
1.1260    raeburn  16633: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16634:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16635: 
1.663     raeburn  16636: Returns: $output (markup to be displayed) 
                   16637: 
                   16638: =cut
                   16639: 
                   16640: sub assign_categories_table {
1.1259    raeburn  16641:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  16642:     my $output;
                   16643:     if (ref($cathash) eq 'HASH') {
1.1321    raeburn  16644:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   16645:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  16646:         $maxdepth = scalar(@cats);
                   16647:         if (@cats > 0) {
                   16648:             my $itemcount = 0;
                   16649:             if (ref($cats[0]) eq 'ARRAY') {
                   16650:                 my @currcategories;
                   16651:                 if ($currcat ne '') {
                   16652:                     @currcategories = split('&',$currcat);
                   16653:                 }
1.919     raeburn  16654:                 my $table;
1.663     raeburn  16655:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   16656:                     my $parent = $cats[0][$i];
1.919     raeburn  16657:                     next if ($parent eq 'instcode');
                   16658:                     if ($type eq 'Community') {
                   16659:                         next unless ($parent eq 'communities');
1.1239    raeburn  16660:                     } elsif ($type eq 'Placement') {
                   16661:                         next unless ($parent eq 'placement');
1.919     raeburn  16662:                     } else {
1.1239    raeburn  16663:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
1.919     raeburn  16664:                     }
1.663     raeburn  16665:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   16666:                     my $item = &escape($parent).'::0';
                   16667:                     my $checked = '';
                   16668:                     if (@currcategories > 0) {
                   16669:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   16670:                             $checked = ' checked="checked"';
1.663     raeburn  16671:                         }
                   16672:                     }
1.919     raeburn  16673:                     my $parent_title = $parent;
                   16674:                     if ($parent eq 'communities') {
                   16675:                         $parent_title = &mt('Communities');
1.1239    raeburn  16676:                     } elsif ($parent eq 'placement') {
                   16677:                         $parent_title = &mt('Placement Tests');
1.919     raeburn  16678:                     }
                   16679:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   16680:                               '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16681:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  16682:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  16683:                     my $depth = 1;
                   16684:                     push(@path,$parent);
1.1259    raeburn  16685:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  16686:                     pop(@path);
1.919     raeburn  16687:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  16688:                     $itemcount ++;
                   16689:                 }
1.919     raeburn  16690:                 if ($itemcount) {
                   16691:                     $output = &Apache::loncommon::start_data_table().
                   16692:                               $table.
                   16693:                               &Apache::loncommon::end_data_table();
                   16694:                 }
1.663     raeburn  16695:             }
                   16696:         }
                   16697:     }
                   16698:     return $output;
                   16699: }
                   16700: 
                   16701: =pod
                   16702: 
1.1162    raeburn  16703: =item * &assign_category_rows()
1.663     raeburn  16704: 
                   16705: Create a datatable row for display of nested categories in a domain,
                   16706: with checkboxes to allow a course to be categorized,called recursively.
                   16707: 
                   16708: Inputs:
                   16709: 
                   16710: itemcount - track row number for alternating colors
                   16711: 
                   16712: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   16713:       categories and subcategories.
                   16714: 
                   16715: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   16716: 
                   16717: parent - parent of current category item
                   16718: 
                   16719: path - Array containing all categories back up through the hierarchy from the
                   16720:        current category to the top level.
                   16721: 
                   16722: currcategories - reference to array of current categories assigned to the course
                   16723: 
1.1260    raeburn  16724: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   16725:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   16726: 
1.663     raeburn  16727: Returns: $output (markup to be displayed).
                   16728: 
                   16729: =cut
                   16730: 
                   16731: sub assign_category_rows {
1.1259    raeburn  16732:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  16733:     my ($text,$name,$item,$chgstr);
                   16734:     if (ref($cats) eq 'ARRAY') {
                   16735:         my $maxdepth = scalar(@{$cats});
                   16736:         if (ref($cats->[$depth]) eq 'HASH') {
                   16737:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   16738:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   16739:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  16740:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  16741:                 for (my $j=0; $j<$numchildren; $j++) {
                   16742:                     $name = $cats->[$depth]{$parent}[$j];
                   16743:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   16744:                     my $deeper = $depth+1;
                   16745:                     my $checked = '';
                   16746:                     if (ref($currcategories) eq 'ARRAY') {
                   16747:                         if (@{$currcategories} > 0) {
                   16748:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   16749:                                 $checked = ' checked="checked"';
1.663     raeburn  16750:                             }
                   16751:                         }
                   16752:                     }
1.664     raeburn  16753:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   16754:                              '<input type="checkbox" name="usecategory" value="'.
1.1259    raeburn  16755:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  16756:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   16757:                              '</td><td>';
1.663     raeburn  16758:                     if (ref($path) eq 'ARRAY') {
                   16759:                         push(@{$path},$name);
1.1259    raeburn  16760:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  16761:                         pop(@{$path});
                   16762:                     }
                   16763:                     $text .= '</td></tr>';
                   16764:                 }
                   16765:                 $text .= '</table></td>';
                   16766:             }
                   16767:         }
                   16768:     }
                   16769:     return $text;
                   16770: }
                   16771: 
1.1181    raeburn  16772: =pod
                   16773: 
                   16774: =back
                   16775: 
                   16776: =cut
                   16777: 
1.655     raeburn  16778: ############################################################
                   16779: ############################################################
                   16780: 
                   16781: 
1.443     albertel 16782: sub commit_customrole {
1.1408    raeburn  16783:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context,$othdomby,$requester) = @_;
1.1399    raeburn  16784:     my $result = &Apache::lonnet::assigncustomrole(
1.1408    raeburn  16785:                      $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,
                   16786:                      $context,$othdomby,$requester);
1.630     raeburn  16787:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 16788:                          ($start?', '.&mt('starting').' '.localtime($start):'').
1.1399    raeburn  16789:                          ($end?', ending '.localtime($end):'').': <b>'.$result.'</b><br />';
                   16790:     if (wantarray) {
                   16791:         return ($output,$result);
                   16792:     } else {
                   16793:         return $output;
                   16794:     }
1.443     albertel 16795: }
                   16796: 
                   16797: sub commit_standardrole {
1.1408    raeburn  16798:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits,
                   16799:         $othdomby,$requester) = @_;
1.1399    raeburn  16800:     my ($output,$logmsg,$linefeed,$result);
1.541     raeburn  16801:     if ($context eq 'auto') {
                   16802:         $linefeed = "\n";
                   16803:     } else {
                   16804:         $linefeed = "<br />\n";
                   16805:     }  
1.443     albertel 16806:     if ($three eq 'st') {
1.1399    raeburn  16807:         $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1408    raeburn  16808:                                       $one,$two,$sec,$context,$credits,$othdomby,
                   16809:                                       $requester);
1.541     raeburn  16810:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  16811:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   16812:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 16813:         } else {
1.541     raeburn  16814:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 16815:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16816:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   16817:             if ($context eq 'auto') {
                   16818:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   16819:             } else {
                   16820:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   16821:                &mt('Add to classlist').': <b>ok</b>';
                   16822:             }
                   16823:             $output .= $linefeed;
1.443     albertel 16824:         }
                   16825:     } else {
                   16826:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   16827:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  16828:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.1408    raeburn  16829:         $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,
                   16830:                                               '','',$context,$othdomby,$requester);
1.541     raeburn  16831:         if ($context eq 'auto') {
                   16832:             $output .= $result.$linefeed;
                   16833:         } else {
                   16834:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   16835:         }
1.443     albertel 16836:     }
1.1399    raeburn  16837:     if (wantarray) {
                   16838:         return ($output,$result);
                   16839:     } else {
                   16840:         return $output;
                   16841:     }
1.443     albertel 16842: }
                   16843: 
                   16844: sub commit_studentrole {
1.1116    raeburn  16845:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
1.1408    raeburn  16846:         $credits,$othdomby,$requester) = @_;
1.626     raeburn  16847:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  16848:     if ($context eq 'auto') {
                   16849:         $linefeed = "\n";
                   16850:     } else {
                   16851:         $linefeed = '<br />'."\n";
                   16852:     }
1.443     albertel 16853:     if (defined($one) && defined($two)) {
                   16854:         my $cid=$one.'_'.$two;
                   16855:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   16856:         my $secchange = 0;
                   16857:         my $expire_role_result;
                   16858:         my $modify_section_result;
1.628     raeburn  16859:         if ($oldsec ne '-1') { 
                   16860:             if ($oldsec ne $sec) {
1.443     albertel 16861:                 $secchange = 1;
1.628     raeburn  16862:                 my $now = time;
1.443     albertel 16863:                 my $uurl='/'.$cid;
                   16864:                 $uurl=~s/\_/\//g;
                   16865:                 if ($oldsec) {
                   16866:                     $uurl.='/'.$oldsec;
                   16867:                 }
1.626     raeburn  16868:                 $oldsecurl = $uurl;
1.628     raeburn  16869:                 $expire_role_result = 
1.1408    raeburn  16870:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,
                   16871:                                                 '','','',$context,$othdomby,$requester);
                   16872:                 if ($env{'request.course.sec'} ne '') {
1.628     raeburn  16873:                     if ($expire_role_result eq 'refused') {
                   16874:                         my @roles = ('st');
                   16875:                         my @statuses = ('previous');
                   16876:                         my @roledoms = ($one);
                   16877:                         my $withsec = 1;
                   16878:                         my %roleshash = 
                   16879:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   16880:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   16881:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   16882:                             my ($oldstart,$oldend) = 
                   16883:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   16884:                             if ($oldend > 0 && $oldend <= $now) {
                   16885:                                 $expire_role_result = 'ok';
                   16886:                             }
                   16887:                         }
                   16888:                     }
                   16889:                 }
1.443     albertel 16890:                 $result = $expire_role_result;
                   16891:             }
                   16892:         }
                   16893:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  16894:             $modify_section_result = 
                   16895:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   16896:                                                            undef,undef,undef,$sec,
                   16897:                                                            $end,$start,'','',$cid,
1.1408    raeburn  16898:                                                            '',$context,$credits,'',
                   16899:                                                            $othdomby,$requester);
1.443     albertel 16900:             if ($modify_section_result =~ /^ok/) {
                   16901:                 if ($secchange == 1) {
1.628     raeburn  16902:                     if ($sec eq '') {
                   16903:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   16904:                     } else {
                   16905:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   16906:                     }
1.443     albertel 16907:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  16908:                     if ($sec eq '') {
                   16909:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   16910:                     } else {
                   16911:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16912:                     }
1.443     albertel 16913:                 } else {
1.628     raeburn  16914:                     if ($sec eq '') {
                   16915:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   16916:                     } else {
                   16917:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   16918:                     }
1.443     albertel 16919:                 }
                   16920:             } else {
1.1115    raeburn  16921:                 if ($secchange) { 
1.628     raeburn  16922:                     $$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;
                   16923:                 } else {
                   16924:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   16925:                 }
1.443     albertel 16926:             }
                   16927:             $result = $modify_section_result;
                   16928:         } elsif ($secchange == 1) {
1.628     raeburn  16929:             if ($oldsec eq '') {
1.1103    raeburn  16930:                 $$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  16931:             } else {
                   16932:                 $$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;
                   16933:             }
1.626     raeburn  16934:             if ($expire_role_result eq 'refused') {
                   16935:                 my $newsecurl = '/'.$cid;
                   16936:                 $newsecurl =~ s/\_/\//g;
                   16937:                 if ($sec ne '') {
                   16938:                     $newsecurl.='/'.$sec;
                   16939:                 }
                   16940:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   16941:                     if ($sec eq '') {
                   16942:                         $$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;
                   16943:                     } else {
                   16944:                         $$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;
                   16945:                     }
                   16946:                 }
                   16947:             }
1.443     albertel 16948:         }
                   16949:     } else {
1.626     raeburn  16950:         $$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 16951:         $result = "error: incomplete course id\n";
                   16952:     }
                   16953:     return $result;
                   16954: }
                   16955: 
1.1108    raeburn  16956: sub show_role_extent {
                   16957:     my ($scope,$context,$role) = @_;
                   16958:     $scope =~ s{^/}{};
                   16959:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   16960:     push(@courseroles,'co');
                   16961:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   16962:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   16963:         $scope =~ s{/}{_};
                   16964:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   16965:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   16966:         my ($audom,$auname) = split(/\//,$scope);
                   16967:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   16968:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   16969:     } else {
                   16970:         $scope =~ s{/$}{};
                   16971:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   16972:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   16973:     }
                   16974: }
                   16975: 
1.443     albertel 16976: ############################################################
                   16977: ############################################################
                   16978: 
1.566     albertel 16979: sub check_clone {
1.578     raeburn  16980:     my ($args,$linefeed) = @_;
1.566     albertel 16981:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   16982:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   16983:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
1.1344    raeburn  16984:     my $clonetitle;
                   16985:     my @clonemsg;
1.566     albertel 16986:     my $can_clone = 0;
1.944     raeburn  16987:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  16988:     if ($lctype ne 'community') {
                   16989:         $lctype = 'course';
                   16990:     }
1.566     albertel 16991:     if ($clonehome eq 'no_host') {
1.944     raeburn  16992:         if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  16993:             push(@clonemsg,({
                   16994:                               mt => 'No new community created.',
                   16995:                               args => [],
                   16996:                             },
                   16997:                             {
                   16998:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
                   16999:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
                   17000:                             }));
1.908     raeburn  17001:         } else {
1.1344    raeburn  17002:             push(@clonemsg,({
                   17003:                               mt => 'No new course created.',
                   17004:                               args => [],
                   17005:                             },
                   17006:                             {
                   17007:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
                   17008:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17009:                             }));
                   17010:         }
1.566     albertel 17011:     } else {
                   17012: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.1344    raeburn  17013:         $clonetitle = $clonedesc{'description'};
1.944     raeburn  17014:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  17015:             if ($clonedesc{'type'} ne 'Community') {
1.1344    raeburn  17016:                 push(@clonemsg,({
                   17017:                                   mt => 'No new community created.',
                   17018:                                   args => [],
                   17019:                                 },
                   17020:                                 {
                   17021:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
                   17022:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
                   17023:                                 }));
                   17024:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
1.908     raeburn  17025:             }
                   17026:         }
1.1262    raeburn  17027: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  17028:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 17029: 	    $can_clone = 1;
                   17030: 	} else {
1.1221    raeburn  17031: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 17032: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1221    raeburn  17033:             if ($clonehash{'cloners'} eq '') {
                   17034:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   17035:                 if ($domdefs{'canclone'}) {
                   17036:                     unless ($domdefs{'canclone'} eq 'none') {
                   17037:                         if ($domdefs{'canclone'} eq 'domain') {
                   17038:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   17039:                                 $can_clone = 1;
                   17040:                             }
                   17041:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17042:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   17043:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   17044:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   17045:                                 $can_clone = 1;
                   17046:                             }
                   17047:                         }
                   17048:                     }
                   17049:                 }
1.578     raeburn  17050:             } else {
1.1221    raeburn  17051: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   17052:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  17053:                     $can_clone = 1;
1.1221    raeburn  17054:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  17055:                     $can_clone = 1;
1.1225    raeburn  17056:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   17057:                     $can_clone = 1;
1.1221    raeburn  17058:                 }
                   17059:                 unless ($can_clone) {
1.1225    raeburn  17060:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
                   17061:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1221    raeburn  17062:                         my (%gotdomdefaults,%gotcodedefaults);
                   17063:                         foreach my $cloner (@cloners) {
                   17064:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   17065:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   17066:                                 my (%codedefaults,@code_order);
                   17067:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   17068:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   17069:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   17070:                                     }
                   17071:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   17072:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   17073:                                     }
                   17074:                                 } else {
                   17075:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   17076:                                                                             \%codedefaults,
                   17077:                                                                             \@code_order);
                   17078:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   17079:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   17080:                                 }
                   17081:                                 if (@code_order > 0) {
                   17082:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   17083:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   17084:                                                                                 $args->{'crscode'})) {
                   17085:                                         $can_clone = 1;
                   17086:                                         last;
                   17087:                                     }
                   17088:                                 }
                   17089:                             }
                   17090:                         }
                   17091:                     }
1.1225    raeburn  17092:                 }
                   17093:             }
                   17094:             unless ($can_clone) {
                   17095:                 my $ccrole = 'cc';
                   17096:                 if ($args->{'crstype'} eq 'Community') {
                   17097:                     $ccrole = 'co';
                   17098:                 }
                   17099: 	        my %roleshash =
                   17100: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   17101: 					          $args->{'ccdomain'},
                   17102:                                                   'userroles',['active'],[$ccrole],
                   17103: 					          [$args->{'clonedomain'}]);
                   17104: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   17105:                     $can_clone = 1;
                   17106:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   17107:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   17108:                     $can_clone = 1;
1.1221    raeburn  17109:                 }
                   17110:             }
                   17111:             unless ($can_clone) {
                   17112:                 if ($args->{'crstype'} eq 'Community') {
1.1344    raeburn  17113:                     push(@clonemsg,({
                   17114:                                       mt => 'No new community created.',
                   17115:                                       args => [],
                   17116:                                     },
                   17117:                                     {
                   17118:                                       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]).',
                   17119:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17120:                                     }));
1.942     raeburn  17121:                 } else {
1.1344    raeburn  17122:                     push(@clonemsg,({
                   17123:                                       mt => 'No new course created.',
                   17124:                                       args => [],
                   17125:                                     },
                   17126:                                     {
                   17127:                                       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]).',
                   17128:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
                   17129:                                     }));
1.1221    raeburn  17130:                 }
1.566     albertel 17131: 	    }
1.578     raeburn  17132:         }
1.566     albertel 17133:     }
1.1344    raeburn  17134:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17135: }
                   17136: 
1.444     albertel 17137: sub construct_course {
1.1262    raeburn  17138:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
1.1344    raeburn  17139:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
                   17140:     my ($outcome,$msgref,$clonemsgref);
1.541     raeburn  17141:     my $linefeed =  '<br />'."\n";
                   17142:     if ($context eq 'auto') {
                   17143:         $linefeed = "\n";
                   17144:     }
1.566     albertel 17145: 
                   17146: #
                   17147: # Are we cloning?
                   17148: #
1.1344    raeburn  17149:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
1.566     albertel 17150:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.1344    raeburn  17151: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
1.566     albertel 17152:         if (!$can_clone) {
1.1344    raeburn  17153: 	    return (0,$outcome,$clonemsgref);
1.566     albertel 17154: 	}
                   17155:     }
                   17156: 
1.444     albertel 17157: #
                   17158: # Open course
                   17159: #
1.1239    raeburn  17160:     my $showncrstype;
                   17161:     if ($args->{'crstype'} eq 'Placement') {
                   17162:         $showncrstype = 'placement test'; 
                   17163:     } else {  
                   17164:         $showncrstype = lc($args->{'crstype'});
                   17165:     }
1.444     albertel 17166:     my %cenv=();
                   17167:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   17168:                                              $args->{'cdescr'},
                   17169:                                              $args->{'curl'},
                   17170:                                              $args->{'course_home'},
                   17171:                                              $args->{'nonstandard'},
                   17172:                                              $args->{'crscode'},
                   17173:                                              $args->{'ccuname'}.':'.
                   17174:                                              $args->{'ccdomain'},
1.882     raeburn  17175:                                              $args->{'crstype'},
1.1344    raeburn  17176:                                              $cnum,$context,$category,
                   17177:                                              $callercontext);
1.444     albertel 17178: 
                   17179:     # Note: The testing routines depend on this being output; see 
                   17180:     # Utils::Course. This needs to at least be output as a comment
                   17181:     # if anyone ever decides to not show this, and Utils::Course::new
                   17182:     # will need to be suitably modified.
1.1344    raeburn  17183:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17184:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17185:     } else {
                   17186:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
                   17187:     }
1.943     raeburn  17188:     if ($$courseid =~ /^error:/) {
1.1344    raeburn  17189:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17190:     }
                   17191: 
1.444     albertel 17192: #
                   17193: # Check if created correctly
                   17194: #
1.479     albertel 17195:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 17196:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  17197:     if ($crsuhome eq 'no_host') {
1.1344    raeburn  17198:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
                   17199:             $outcome .= &mt_user($user_lh,
                   17200:                             'Course creation failed, unrecognized course home server.');
                   17201:         } else {
                   17202:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
                   17203:         }
                   17204:         $outcome .= $linefeed;
                   17205:         return (0,$outcome,$clonemsgref);
1.943     raeburn  17206:     }
1.541     raeburn  17207:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 17208: 
1.444     albertel 17209: #
1.566     albertel 17210: # Do the cloning
                   17211: #   
1.1344    raeburn  17212:     my @clonemsg;
1.566     albertel 17213:     if ($can_clone && $cloneid) {
1.1344    raeburn  17214:         push(@clonemsg,
                   17215:                       {
                   17216:                           mt => 'Created [_1] by cloning from [_2]',
                   17217:                           args => [$showncrstype,$clonetitle],
                   17218:                       });
1.566     albertel 17219: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 17220: # Copy all files
1.1344    raeburn  17221:         my @info =
                   17222: 	    &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
                   17223: 	                                             $args->{'dateshift'},$args->{'crscode'},
                   17224:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
                   17225:                                                      $args->{'tinyurls'});
                   17226:         if (@info) {
                   17227:             push(@clonemsg,@info);
                   17228:         }
1.444     albertel 17229: # Restore URL
1.566     albertel 17230: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 17231: # Restore title
1.566     albertel 17232: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  17233: # Restore creation date, creator and creation context.
                   17234:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   17235:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   17236:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 17237: # Mark as cloned
1.566     albertel 17238: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      17239: # Need to clone grading mode
                   17240:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   17241:         $cenv{'grading'}=$newenv{'grading'};
                   17242: # Do not clone these environment entries
                   17243:         &Apache::lonnet::del('environment',
                   17244:                   ['default_enrollment_start_date',
                   17245:                    'default_enrollment_end_date',
                   17246:                    'question.email',
                   17247:                    'policy.email',
                   17248:                    'comment.email',
                   17249:                    'pch.users.denied',
1.725     raeburn  17250:                    'plc.users.denied',
                   17251:                    'hidefromcat',
1.1121    raeburn  17252:                    'checkforpriv',
1.1355    raeburn  17253:                    'categories'],
1.638     www      17254:                    $$crsudom,$$crsunum);
1.1170    raeburn  17255:         if ($args->{'textbook'}) {
                   17256:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   17257:         }
1.444     albertel 17258:     }
1.566     albertel 17259: 
1.444     albertel 17260: #
                   17261: # Set environment (will override cloned, if existing)
                   17262: #
                   17263:     my @sections = ();
                   17264:     my @xlists = ();
                   17265:     if ($args->{'crstype'}) {
                   17266:         $cenv{'type'}=$args->{'crstype'};
                   17267:     }
1.1371    raeburn  17268:     if ($args->{'lti'}) {
                   17269:         $cenv{'internal.lti'}=$args->{'lti'};
                   17270:     }
1.444     albertel 17271:     if ($args->{'crsid'}) {
                   17272:         $cenv{'courseid'}=$args->{'crsid'};
                   17273:     }
                   17274:     if ($args->{'crscode'}) {
                   17275:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   17276:     }
                   17277:     if ($args->{'crsquota'} ne '') {
                   17278:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   17279:     } else {
                   17280:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   17281:     }
                   17282:     if ($args->{'ccuname'}) {
                   17283:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   17284:                                         ':'.$args->{'ccdomain'};
                   17285:     } else {
                   17286:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   17287:     }
1.1116    raeburn  17288:     if ($args->{'defaultcredits'}) {
                   17289:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   17290:     }
1.444     albertel 17291:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
1.1412    raeburn  17292:     my @oklcsecs = (); # Used to accumulate LON-CAPA sections for validated institutional sections.
1.444     albertel 17293:     if ($args->{'crssections'}) {
                   17294:         $cenv{'internal.sectionnums'} = '';
                   17295:         if ($args->{'crssections'} =~ m/,/) {
                   17296:             @sections = split/,/,$args->{'crssections'};
                   17297:         } else {
                   17298:             $sections[0] = $args->{'crssections'};
                   17299:         }
                   17300:         if (@sections > 0) {
                   17301:             foreach my $item (@sections) {
                   17302:                 my ($sec,$gp) = split/:/,$item;
                   17303:                 my $class = $args->{'crscode'}.$sec;
                   17304:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   17305:                 $cenv{'internal.sectionnums'} .= $item.',';
1.1412    raeburn  17306:                 if ($addcheck eq 'ok') {
                   17307:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17308:                         push(@oklcsecs,$gp);
                   17309:                     }
                   17310:                 } else {
1.1263    raeburn  17311:                     push(@badclasses,$class);
1.444     albertel 17312:                 }
                   17313:             }
                   17314:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   17315:         }
                   17316:     }
                   17317: # do not hide course coordinator from staff listing, 
                   17318: # even if privileged
                   17319:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  17320: # add course coordinator's domain to domains to check for privileged users
                   17321: # if different to course domain
                   17322:     if ($$crsudom ne $args->{'ccdomain'}) {
                   17323:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   17324:     }
1.444     albertel 17325: # add crosslistings
                   17326:     if ($args->{'crsxlist'}) {
                   17327:         $cenv{'internal.crosslistings'}='';
                   17328:         if ($args->{'crsxlist'} =~ m/,/) {
                   17329:             @xlists = split/,/,$args->{'crsxlist'};
                   17330:         } else {
                   17331:             $xlists[0] = $args->{'crsxlist'};
                   17332:         }
                   17333:         if (@xlists > 0) {
                   17334:             foreach my $item (@xlists) {
                   17335:                 my ($xl,$gp) = split/:/,$item;
                   17336:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   17337:                 $cenv{'internal.crosslistings'} .= $item.',';
1.1412    raeburn  17338:                 if ($addcheck eq 'ok') {
                   17339:                     unless (grep(/^\Q$gp\E$/,@oklcsecs)) {
                   17340:                         push(@oklcsecs,$gp);
                   17341:                     }
                   17342:                 } else {
1.1263    raeburn  17343:                     push(@badclasses,$xl);
1.444     albertel 17344:                 }
                   17345:             }
                   17346:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   17347:         }
                   17348:     }
                   17349:     if ($args->{'autoadds'}) {
                   17350:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   17351:     }
                   17352:     if ($args->{'autodrops'}) {
                   17353:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   17354:     }
                   17355: # check for notification of enrollment changes
                   17356:     my @notified = ();
                   17357:     if ($args->{'notify_owner'}) {
                   17358:         if ($args->{'ccuname'} ne '') {
                   17359:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   17360:         }
                   17361:     }
                   17362:     if ($args->{'notify_dc'}) {
                   17363:         if ($uname ne '') { 
1.630     raeburn  17364:             push(@notified,$uname.':'.$udom);
1.444     albertel 17365:         }
                   17366:     }
                   17367:     if (@notified > 0) {
                   17368:         my $notifylist;
                   17369:         if (@notified > 1) {
                   17370:             $notifylist = join(',',@notified);
                   17371:         } else {
                   17372:             $notifylist = $notified[0];
                   17373:         }
                   17374:         $cenv{'internal.notifylist'} = $notifylist;
                   17375:     }
                   17376:     if (@badclasses > 0) {
                   17377:         my %lt=&Apache::lonlocal::texthash(
1.1264    raeburn  17378:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   17379:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   17380:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 17381:         );
1.1264    raeburn  17382:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   17383:                            &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  17384:         if ($context eq 'auto') {
                   17385:             $outcome .= $badclass_msg.$linefeed;
1.1261    raeburn  17386:         } else {
1.566     albertel 17387:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1261    raeburn  17388:         }
                   17389:         foreach my $item (@badclasses) {
1.541     raeburn  17390:             if ($context eq 'auto') {
1.1261    raeburn  17391:                 $outcome .= " - $item\n";
1.541     raeburn  17392:             } else {
1.1261    raeburn  17393:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  17394:             }
1.1261    raeburn  17395:         }
                   17396:         if ($context eq 'auto') {
                   17397:             $outcome .= $linefeed;
                   17398:         } else {
                   17399:             $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  17400:         } 
1.444     albertel 17401:     }
                   17402:     if ($args->{'no_end_date'}) {
                   17403:         $args->{'endaccess'} = 0;
                   17404:     }
1.1412    raeburn  17405: #  If an official course with institutional sections is created by cloning 
                   17406: #  an existing course, section-specific hiding of course totals in student's
                   17407: #  view of grades as copied from cloned course, will be checked for valid 
                   17408: #  sections.
                   17409:     if (($can_clone && $cloneid) &&
                   17410:         ($cenv{'internal.coursecode'} ne '') &&
                   17411:         ($cenv{'grading'} eq 'standard') &&
                   17412:         ($cenv{'hidetotals'} ne '') &&
                   17413:         ($cenv{'hidetotals'} ne 'all')) {
                   17414:         my @hidesecs;
                   17415:         my $deletehidetotals;
                   17416:         if (@oklcsecs) {
                   17417:             foreach my $sec (split(/,/,$cenv{'hidetotals'})) {
                   17418:                 if (grep(/^\Q$sec$/,@oklcsecs)) {
                   17419:                     push(@hidesecs,$sec);
                   17420:                 }
                   17421:             }
                   17422:             if (@hidesecs) {
                   17423:                 $cenv{'hidetotals'} = join(',',@hidesecs);
                   17424:             } else {
                   17425:                 $deletehidetotals = 1;
                   17426:             }
                   17427:         } else {
                   17428:             $deletehidetotals = 1;
                   17429:         }
                   17430:         if ($deletehidetotals) {
                   17431:             delete($cenv{'hidetotals'});
                   17432:             &Apache::lonnet::del('environment',['hidetotals'],$$crsudom,$$crsunum);
                   17433:         }
                   17434:     }
1.444     albertel 17435:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   17436:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   17437:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   17438:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   17439:     if ($args->{'showphotos'}) {
                   17440:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   17441:     }
                   17442:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   17443:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   17444:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   17445:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  17446:             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'); 
                   17447:             if ($context eq 'auto') {
                   17448:                 $outcome .= $krb_msg;
                   17449:             } else {
1.566     albertel 17450:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  17451:             }
                   17452:             $outcome .= $linefeed;
1.444     albertel 17453:         }
                   17454:     }
                   17455:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   17456:        if ($args->{'setpolicy'}) {
                   17457:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17458:        }
                   17459:        if ($args->{'setcontent'}) {
                   17460:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17461:        }
1.1251    raeburn  17462:        if ($args->{'setcomment'}) {
                   17463:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   17464:        }
1.444     albertel 17465:     }
                   17466:     if ($args->{'reshome'}) {
                   17467: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   17468: 	$cenv{'reshome'}=~s/\/+$/\//;
                   17469:     }
                   17470: #
                   17471: # course has keyed access
                   17472: #
                   17473:     if ($args->{'setkeys'}) {
                   17474:        $cenv{'keyaccess'}='yes';
                   17475:     }
                   17476: # if specified, key authority is not course, but user
                   17477: # only active if keyaccess is yes
                   17478:     if ($args->{'keyauth'}) {
1.487     albertel 17479: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   17480: 	$user = &LONCAPA::clean_username($user);
                   17481: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     17482: 	if ($user ne '' && $domain ne '') {
1.487     albertel 17483: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 17484: 	}
                   17485:     }
                   17486: 
1.1166    raeburn  17487: #
1.1167    raeburn  17488: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  17489: #
                   17490:     if ($args->{'uniquecode'}) {
                   17491:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   17492:         if ($code) {
                   17493:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  17494:             my %crsinfo =
                   17495:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   17496:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   17497:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   17498:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   17499:             } 
1.1166    raeburn  17500:             if (ref($coderef)) {
                   17501:                 $$coderef = $code;
                   17502:             }
                   17503:         }
                   17504:     }
                   17505: 
1.444     albertel 17506:     if ($args->{'disresdis'}) {
                   17507:         $cenv{'pch.roles.denied'}='st';
                   17508:     }
                   17509:     if ($args->{'disablechat'}) {
                   17510:         $cenv{'plc.roles.denied'}='st';
                   17511:     }
                   17512: 
                   17513:     # Record we've not yet viewed the Course Initialization Helper for this 
                   17514:     # course
                   17515:     $cenv{'course.helper.not.run'} = 1;
                   17516:     #
                   17517:     # Use new Randomseed
                   17518:     #
                   17519:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   17520:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   17521:     #
                   17522:     # The encryption code and receipt prefix for this course
                   17523:     #
                   17524:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   17525:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   17526:     #
                   17527:     # By default, use standard grading
                   17528:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   17529: 
1.541     raeburn  17530:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   17531:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17532: #
                   17533: # Open all assignments
                   17534: #
                   17535:     if ($args->{'openall'}) {
1.1341    raeburn  17536:        my $opendate = time;
                   17537:        if ($args->{'openallfrom'} =~ /^\d+$/) {
                   17538:            $opendate = $args->{'openallfrom'};
                   17539:        }
1.444     albertel 17540:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
1.1341    raeburn  17541:        my %storecontent = ($storeunder         => $opendate,
1.444     albertel 17542:                            $storeunder.'.type' => 'date_start');
1.1341    raeburn  17543:        $outcome .= &mt('All assignments open starting [_1]',
                   17544:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
                   17545:                    &Apache::lonnet::cput
                   17546:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 17547:    }
                   17548: #
                   17549: # Set first page
                   17550: #
                   17551:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   17552: 	    || ($cloneid)) {
                   17553: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 17554: 
                   17555: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   17556:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   17557: 
1.444     albertel 17558:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   17559:         my $title; my $url;
                   17560:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   17561: 	    $title=&mt('Syllabus');
1.444     albertel 17562:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   17563:         } else {
1.963     raeburn  17564:             $title=&mt('Table of Contents');
1.444     albertel 17565:             $url='/adm/navmaps';
                   17566:         }
1.445     albertel 17567: 
                   17568:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   17569: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   17570: 
                   17571: 	if ($errtext) { $fatal=2; }
1.541     raeburn  17572:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 17573:     }
1.566     albertel 17574: 
1.1237    raeburn  17575: # 
                   17576: # Set params for Placement Tests
                   17577: #
1.1239    raeburn  17578:     if ($args->{'crstype'} eq 'Placement') {
                   17579:        my %storecontent; 
                   17580:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
                   17581:        my %defaults = (
                   17582:                         buttonshide   => { value => 'yes',
                   17583:                                            type => 'string_yesno',},
                   17584:                         type          => { value => 'randomizetry',
                   17585:                                            type  => 'string_questiontype',},
                   17586:                         maxtries      => { value => 1,
                   17587:                                            type => 'int_pos',},
                   17588:                         problemstatus => { value => 'no',
                   17589:                                            type  => 'string_problemstatus',},
                   17590:                       );
                   17591:        foreach my $key (keys(%defaults)) {
                   17592:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
                   17593:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
                   17594:        }
1.1237    raeburn  17595:        &Apache::lonnet::cput
                   17596:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
                   17597:     }
                   17598: 
1.1344    raeburn  17599:     return (1,$outcome,\@clonemsg);
1.444     albertel 17600: }
                   17601: 
1.1166    raeburn  17602: sub make_unique_code {
                   17603:     my ($cdom,$cnum) = @_;
                   17604:     # get lock on uniquecodes db
                   17605:     my $lockhash = {
                   17606:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   17607:                                                   ':'.$env{'user.domain'},
                   17608:                    };
                   17609:     my $tries = 0;
                   17610:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17611:     my ($code,$error);
                   17612:   
                   17613:     while (($gotlock ne 'ok') && ($tries<3)) {
                   17614:         $tries ++;
                   17615:         sleep 1;
                   17616:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   17617:     }
                   17618:     if ($gotlock eq 'ok') {
                   17619:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   17620:         my $gotcode;
                   17621:         my $attempts = 0;
                   17622:         while ((!$gotcode) && ($attempts < 100)) {
                   17623:             $code = &generate_code();
                   17624:             if (!exists($currcodes{$code})) {
                   17625:                 $gotcode = 1;
                   17626:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   17627:                     $error = 'nostore';
                   17628:                 }
                   17629:             }
                   17630:             $attempts ++;
                   17631:         }
                   17632:         my @del_lock = ($cnum."\0".'uniquecodes');
                   17633:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   17634:     } else {
                   17635:         $error = 'nolock';
                   17636:     }
                   17637:     return ($code,$error);
                   17638: }
                   17639: 
                   17640: sub generate_code {
                   17641:     my $code;
                   17642:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   17643:     for (my $i=0; $i<6; $i++) {
                   17644:         my $lettnum = int (rand 2);
                   17645:         my $item = '';
                   17646:         if ($lettnum) {
                   17647:             $item = $letts[int( rand(18) )];
                   17648:         } else {
                   17649:             $item = 1+int( rand(8) );
                   17650:         }
                   17651:         $code .= $item;
                   17652:     }
                   17653:     return $code;
                   17654: }
                   17655: 
1.444     albertel 17656: ############################################################
                   17657: ############################################################
                   17658: 
1.1237    raeburn  17659: # Community, Course and Placement Test
1.378     raeburn  17660: sub course_type {
                   17661:     my ($cid) = @_;
                   17662:     if (!defined($cid)) {
                   17663:         $cid = $env{'request.course.id'};
                   17664:     }
1.404     albertel 17665:     if (defined($env{'course.'.$cid.'.type'})) {
                   17666:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  17667:     } else {
                   17668:         return 'Course';
1.377     raeburn  17669:     }
                   17670: }
1.156     albertel 17671: 
1.406     raeburn  17672: sub group_term {
                   17673:     my $crstype = &course_type();
                   17674:     my %names = (
                   17675:                   'Course' => 'group',
1.865     raeburn  17676:                   'Community' => 'group',
1.1237    raeburn  17677:                   'Placement' => 'group',
1.406     raeburn  17678:                 );
                   17679:     return $names{$crstype};
                   17680: }
                   17681: 
1.902     raeburn  17682: sub course_types {
1.1310    raeburn  17683:     my @types = ('official','unofficial','community','textbook','placement','lti');
1.902     raeburn  17684:     my %typename = (
                   17685:                          official   => 'Official course',
                   17686:                          unofficial => 'Unofficial course',
                   17687:                          community  => 'Community',
1.1165    raeburn  17688:                          textbook   => 'Textbook course',
1.1237    raeburn  17689:                          placement  => 'Placement test',
1.1310    raeburn  17690:                          lti        => 'LTI provider',
1.902     raeburn  17691:                    );
                   17692:     return (\@types,\%typename);
                   17693: }
                   17694: 
1.156     albertel 17695: sub icon {
                   17696:     my ($file)=@_;
1.505     albertel 17697:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 17698:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 17699:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 17700:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   17701: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   17702: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17703: 	            $curfext.".gif") {
                   17704: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   17705: 		$curfext.".gif";
                   17706: 	}
                   17707:     }
1.249     albertel 17708:     return &lonhttpdurl($iconname);
1.154     albertel 17709: } 
1.84      albertel 17710: 
1.575     albertel 17711: sub lonhttpdurl {
1.692     www      17712: #
                   17713: # Had been used for "small fry" static images on separate port 8080.
                   17714: # Modify here if lightweight http functionality desired again.
                   17715: # Currently eliminated due to increasing firewall issues.
                   17716: #
1.575     albertel 17717:     my ($url)=@_;
1.692     www      17718:     return $url;
1.215     albertel 17719: }
                   17720: 
1.213     albertel 17721: sub connection_aborted {
                   17722:     my ($r)=@_;
                   17723:     $r->print(" ");$r->rflush();
                   17724:     my $c = $r->connection;
                   17725:     return $c->aborted();
                   17726: }
                   17727: 
1.221     foxr     17728: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     17729: #    strings as 'strings'.
                   17730: sub escape_single {
1.221     foxr     17731:     my ($input) = @_;
1.223     albertel 17732:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     17733:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   17734:     return $input;
                   17735: }
1.223     albertel 17736: 
1.222     foxr     17737: #  Same as escape_single, but escape's "'s  This 
                   17738: #  can be used for  "strings"
                   17739: sub escape_double {
                   17740:     my ($input) = @_;
                   17741:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   17742:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   17743:     return $input;
                   17744: }
1.223     albertel 17745:  
1.222     foxr     17746: #   Escapes the last element of a full URL.
                   17747: sub escape_url {
                   17748:     my ($url)   = @_;
1.238     raeburn  17749:     my @urlslices = split(/\//, $url,-1);
1.369     www      17750:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  17751:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     17752: }
1.462     albertel 17753: 
1.820     raeburn  17754: sub compare_arrays {
                   17755:     my ($arrayref1,$arrayref2) = @_;
                   17756:     my (@difference,%count);
                   17757:     @difference = ();
                   17758:     %count = ();
                   17759:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   17760:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   17761:         foreach my $element (keys(%count)) {
                   17762:             if ($count{$element} == 1) {
                   17763:                 push(@difference,$element);
                   17764:             }
                   17765:         }
                   17766:     }
                   17767:     return @difference;
                   17768: }
                   17769: 
1.1322    raeburn  17770: sub lon_status_items {
                   17771:     my %defaults = (
                   17772:                      E         => 100,
                   17773:                      W         => 4,
                   17774:                      N         => 1,
1.1324    raeburn  17775:                      U         => 5,
1.1322    raeburn  17776:                      threshold => 200,
                   17777:                      sysmail   => 2500,
                   17778:                    );
                   17779:     my %names = (
                   17780:                    E => 'Errors',
                   17781:                    W => 'Warnings',
                   17782:                    N => 'Notices',
1.1324    raeburn  17783:                    U => 'Unsent',
1.1322    raeburn  17784:                 );
                   17785:     return (\%defaults,\%names);
                   17786: }
                   17787: 
1.817     bisitz   17788: # -------------------------------------------------------- Initialize user login
1.462     albertel 17789: sub init_user_environment {
1.463     albertel 17790:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 17791:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   17792: 
                   17793:     my $public=($username eq 'public' && $domain eq 'public');
                   17794: 
1.1415    raeburn  17795:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv,
                   17796:         $coauthorenv);
1.462     albertel 17797:     my $now=time;
                   17798: 
                   17799:     if ($public) {
                   17800: 	my $max_public=100;
                   17801: 	my $oldest;
                   17802: 	my $oldest_time=0;
                   17803: 	for(my $next=1;$next<=$max_public;$next++) {
                   17804: 	    if (-e $lonids."/publicuser_$next.id") {
                   17805: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   17806: 		if ($mtime<$oldest_time || !$oldest_time) {
                   17807: 		    $oldest_time=$mtime;
                   17808: 		    $oldest=$next;
                   17809: 		}
                   17810: 	    } else {
                   17811: 		$cookie="publicuser_$next";
                   17812: 		last;
                   17813: 	    }
                   17814: 	}
                   17815: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   17816:     } else {
1.1275    raeburn  17817: 	# See if old ID present, if so, remove if this isn't a robot,
                   17818: 	# killing any existing non-robot sessions
1.463     albertel 17819: 	if (!$args->{'robot'}) {
                   17820: 	    opendir(DIR,$lonids);
                   17821: 	    while ($filename=readdir(DIR)) {
                   17822: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
1.1320    raeburn  17823:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
                   17824:                             &GDBM_READER(),0640)) {
1.1295    raeburn  17825:                         my $linkedfile;
1.1320    raeburn  17826:                         if (exists($oldenv{'user.linkedenv'})) {
                   17827:                             $linkedfile = $oldenv{'user.linkedenv'};
1.1295    raeburn  17828:                         }
1.1320    raeburn  17829:                         untie(%oldenv);
                   17830:                         if (unlink("$lonids/$filename")) {
                   17831:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   17832:                                 if (-l "$lonids/$linkedfile.id") {
                   17833:                                     unlink("$lonids/$linkedfile.id");
                   17834:                                 }
1.1295    raeburn  17835:                             }
                   17836:                         }
                   17837:                     } else {
                   17838:                         unlink($lonids.'/'.$filename);
                   17839:                     }
1.463     albertel 17840: 		}
1.462     albertel 17841: 	    }
1.463     albertel 17842: 	    closedir(DIR);
1.1204    raeburn  17843: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   17844:             my $namespace = 'nohist_courseeditor';
                   17845:             my $lockingkey = 'paste'."\0".'locked_num';
                   17846:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   17847:                                                 $domain,$username);
                   17848:             if (exists($lockhash{$lockingkey})) {
                   17849:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   17850:                 unless ($delresult eq 'ok') {
                   17851:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   17852:                 }
                   17853:             }
1.462     albertel 17854: 	}
                   17855: # Give them a new cookie
1.463     albertel 17856: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      17857: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 17858: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 17859:     
                   17860: # Initialize roles
                   17861: 
1.1414    raeburn  17862: 	($userroles,$firstaccenv,$timerintenv,$coauthorenv) = 
1.1062    raeburn  17863:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 17864:     }
                   17865: # ------------------------------------ Check browser type and MathML capability
                   17866: 
1.1194    raeburn  17867:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   17868:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 17869: 
                   17870: # ------------------------------------------------------------- Get environment
                   17871: 
                   17872:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   17873:     my ($tmp) = keys(%userenv);
1.1275    raeburn  17874:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1.462     albertel 17875: 	undef(%userenv);
                   17876:     }
                   17877:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   17878: 	$form->{'interface'}=$userenv{'interface'};
                   17879:     }
                   17880:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   17881: 
                   17882: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   17883:     foreach my $option ('interface','localpath','localres') {
                   17884:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 17885:     }
                   17886: # --------------------------------------------------------- Write first profile
                   17887: 
                   17888:     {
1.1350    raeburn  17889:         my $ip = &Apache::lonnet::get_requestor_ip($r);
1.462     albertel 17890: 	my %initial_env = 
                   17891: 	    ("user.name"          => $username,
                   17892: 	     "user.domain"        => $domain,
                   17893: 	     "user.home"          => $authhost,
                   17894: 	     "browser.type"       => $clientbrowser,
                   17895: 	     "browser.version"    => $clientversion,
                   17896: 	     "browser.mathml"     => $clientmathml,
                   17897: 	     "browser.unicode"    => $clientunicode,
                   17898: 	     "browser.os"         => $clientos,
1.1137    raeburn  17899:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  17900:              "browser.info"       => $clientinfo,
1.1194    raeburn  17901:              "browser.osversion"  => $clientosversion,
1.462     albertel 17902: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   17903: 	     "request.course.fn"  => '',
                   17904: 	     "request.course.uri" => '',
                   17905: 	     "request.course.sec" => '',
                   17906: 	     "request.role"       => 'cm',
                   17907: 	     "request.role.adv"   => $env{'user.adv'},
1.1350    raeburn  17908: 	     "request.host"       => $ip,);
1.462     albertel 17909: 
                   17910:         if ($form->{'localpath'}) {
                   17911: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   17912: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   17913:         }
                   17914: 	
                   17915: 	if ($form->{'interface'}) {
                   17916: 	    $form->{'interface'}=~s/\W//gs;
                   17917: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   17918: 	    $env{'browser.interface'}=$form->{'interface'};
                   17919: 	}
                   17920: 
1.1157    raeburn  17921:         if ($form->{'iptoken'}) {
                   17922:             my $lonhost = $r->dir_config('lonHostID');
                   17923:             $initial_env{"user.noloadbalance"} = $lonhost;
                   17924:             $env{'user.noloadbalance'} = $lonhost;
                   17925:         }
                   17926: 
1.1268    raeburn  17927:         if ($form->{'noloadbalance'}) {
                   17928:             my @hosts = &Apache::lonnet::current_machine_ids();
                   17929:             my $hosthere = $form->{'noloadbalance'};
                   17930:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   17931:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   17932:                 $env{'user.noloadbalance'} = $hosthere;
                   17933:             }
                   17934:         }
                   17935: 
1.1016    raeburn  17936:         unless ($domain eq 'public') {
1.1273    raeburn  17937:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   17938:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   17939: 
1.1414    raeburn  17940:             foreach my $tool ('aboutme','blog','webdav','portfolio','portaccess','timezone') {
                   17941:                 $userenv{'availabletools.'.$tool} =
1.1273    raeburn  17942:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   17943:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   17944:             }
1.980     raeburn  17945: 
1.1311    raeburn  17946:             foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
1.1273    raeburn  17947:                 $userenv{'canrequest.'.$crstype} =
                   17948:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   17949:                                                       'reload','requestcourses',
                   17950:                                                       \%userenv,\%domdef,\%is_adv);
                   17951:             }
1.724     raeburn  17952: 
1.1418    raeburn  17953:             if ((ref($userroles) eq 'HASH') && ($userroles->{'user.author'}) &&
                   17954:                 (exists($userroles->{"user.role.au./$domain/"}))) {
                   17955:                 if ($userenv{'authoreditors'}) {
                   17956:                     $userenv{'editors'} = $userenv{'authoreditors'};
                   17957:                 } elsif ($domdef{'editors'} ne '') {
                   17958:                     $userenv{'editors'} = $domdef{'editors'};
                   17959:                 } else {
                   17960:                     $userenv{'editors'} = 'edit,xml';
                   17961:                 }
                   17962:             }
                   17963: 
1.1273    raeburn  17964:             $userenv{'canrequest.author'} =
                   17965:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   17966:                                                   'reload','requestauthor',
1.980     raeburn  17967:                                                   \%userenv,\%domdef,\%is_adv);
1.1273    raeburn  17968:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   17969:                                                  $domain,$username);
                   17970:             my $reqstatus = $reqauthor{'author_status'};
                   17971:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   17972:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   17973:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   17974:                                                       $reqauthor{'author'}{'timestamp'};
                   17975:                 }
1.1092    raeburn  17976:             }
1.1287    raeburn  17977:             my ($types,$typename) = &course_types();
                   17978:             if (ref($types) eq 'ARRAY') {
                   17979:                 my @options = ('approval','validate','autolimit');
                   17980:                 my $optregex = join('|',@options);
                   17981:                 my (%willtrust,%trustchecked);
                   17982:                 foreach my $type (@{$types}) {
                   17983:                     my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
                   17984:                     if ($dom_str ne '') {
                   17985:                         my $updatedstr = '';
                   17986:                         my @possdomains = split(',',$dom_str);
                   17987:                         foreach my $entry (@possdomains) {
                   17988:                             my ($extdom,$extopt) = split(':',$entry);
                   17989:                             unless ($trustchecked{$extdom}) {
                   17990:                                 $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
                   17991:                                 $trustchecked{$extdom} = 1;
                   17992:                             }
                   17993:                             if ($willtrust{$extdom}) {
                   17994:                                 $updatedstr .= $entry.',';
                   17995:                             }
                   17996:                         }
                   17997:                         $updatedstr =~ s/,$//;
                   17998:                         if ($updatedstr) {
                   17999:                             $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
                   18000:                         } else {
                   18001:                             delete($userenv{'reqcrsotherdom.'.$type});
                   18002:                         }
                   18003:                     }
                   18004:                 }
                   18005:             }
1.1092    raeburn  18006:         }
1.462     albertel 18007: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  18008: 
1.462     albertel 18009: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   18010: 		 &GDBM_WRCREAT(),0640)) {
                   18011: 	    &_add_to_env(\%disk_env,\%initial_env);
                   18012: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   18013: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  18014:             if (ref($firstaccenv) eq 'HASH') {
                   18015:                 &_add_to_env(\%disk_env,$firstaccenv);
                   18016:             }
                   18017:             if (ref($timerintenv) eq 'HASH') {
                   18018:                 &_add_to_env(\%disk_env,$timerintenv);
                   18019:             }
1.1414    raeburn  18020:             if (ref($coauthorenv) eq 'HASH') {
                   18021:                 if (keys(%{$coauthorenv})) {
                   18022:                     &_add_to_env(\%disk_env,$coauthorenv);
                   18023:                 }
                   18024:             }
1.463     albertel 18025: 	    if (ref($args->{'extra_env'})) {
                   18026: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   18027: 	    }
1.462     albertel 18028: 	    untie(%disk_env);
                   18029: 	} else {
1.705     tempelho 18030: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   18031: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 18032: 	    return 'error: '.$!;
                   18033: 	}
                   18034:     }
                   18035:     $env{'request.role'}='cm';
                   18036:     $env{'request.role.adv'}=$env{'user.adv'};
                   18037:     $env{'browser.type'}=$clientbrowser;
                   18038: 
                   18039:     return $cookie;
                   18040: 
                   18041: }
                   18042: 
                   18043: sub _add_to_env {
                   18044:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  18045:     if (ref($env_data) eq 'HASH') {
                   18046:         while (my ($key,$value) = each(%$env_data)) {
                   18047: 	    $idf->{$prefix.$key} = $value;
                   18048: 	    $env{$prefix.$key}   = $value;
                   18049:         }
1.462     albertel 18050:     }
                   18051: }
                   18052: 
1.685     tempelho 18053: # --- Get the symbolic name of a problem and the url
                   18054: sub get_symb {
                   18055:     my ($request,$silent) = @_;
1.726     raeburn  18056:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 18057:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   18058:     if ($symb eq '') {
                   18059:         if (!$silent) {
1.1071    raeburn  18060:             if (ref($request)) { 
                   18061:                 $request->print("Unable to handle ambiguous references:$url:.");
                   18062:             }
1.685     tempelho 18063:             return ();
                   18064:         }
                   18065:     }
                   18066:     &Apache::lonenc::check_decrypt(\$symb);
                   18067:     return ($symb);
                   18068: }
                   18069: 
                   18070: # --------------------------------------------------------------Get annotation
                   18071: 
                   18072: sub get_annotation {
                   18073:     my ($symb,$enc) = @_;
                   18074: 
                   18075:     my $key = $symb;
                   18076:     if (!$enc) {
                   18077:         $key =
                   18078:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   18079:     }
                   18080:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   18081:     return $annotation{$key};
                   18082: }
                   18083: 
                   18084: sub clean_symb {
1.731     raeburn  18085:     my ($symb,$delete_enc) = @_;
1.685     tempelho 18086: 
                   18087:     &Apache::lonenc::check_decrypt(\$symb);
                   18088:     my $enc = $env{'request.enc'};
1.731     raeburn  18089:     if ($delete_enc) {
1.730     raeburn  18090:         delete($env{'request.enc'});
                   18091:     }
1.685     tempelho 18092: 
                   18093:     return ($symb,$enc);
                   18094: }
1.462     albertel 18095: 
1.1181    raeburn  18096: ############################################################
                   18097: ############################################################
                   18098: 
                   18099: =pod
                   18100: 
                   18101: =head1 Routines for building display used to search for courses
                   18102: 
                   18103: 
                   18104: =over 4
                   18105: 
                   18106: =item * &build_filters()
                   18107: 
                   18108: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  18109: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   18110: and quotacheck.pl
                   18111: 
1.1181    raeburn  18112: 
                   18113: Inputs:
                   18114: 
                   18115: filterlist - anonymous array of fields to include as potential filters 
                   18116: 
                   18117: crstype - course type
                   18118: 
                   18119: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   18120:               to pop-open a course selector (will contain "extra element"). 
                   18121: 
                   18122: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   18123: 
                   18124: filter - anonymous hash of criteria and their values
                   18125: 
                   18126: action - form action
                   18127: 
                   18128: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   18129: 
1.1182    raeburn  18130: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  18131: 
                   18132: cloneruname - username of owner of new course who wants to clone
                   18133: 
                   18134: clonerudom - domain of owner of new course who wants to clone
                   18135: 
                   18136: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   18137: 
                   18138: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   18139: 
                   18140: codedom - domain
                   18141: 
                   18142: formname - value of form element named "form". 
                   18143: 
                   18144: fixeddom - domain, if fixed.
                   18145: 
                   18146: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   18147: 
                   18148: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   18149: 
                   18150: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   18151: 
                   18152: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   18153: 
                   18154: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   18155: 
                   18156: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   18157: 
                   18158: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   18159: 
1.1182    raeburn  18160: 
1.1181    raeburn  18161: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   18162: 
1.1182    raeburn  18163: 
1.1181    raeburn  18164: Side Effects: None
                   18165: 
                   18166: =cut
                   18167: 
                   18168: # ---------------------------------------------- search for courses based on last activity etc.
                   18169: 
                   18170: sub build_filters {
                   18171:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   18172:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   18173:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   18174:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   18175:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  18176:     my ($list,$jscript);
1.1181    raeburn  18177:     my $onchange = 'javascript:updateFilters(this)';
                   18178:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   18179:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   18180:         $typeselectform,$instcodetitle);
                   18181:     if ($formname eq '') {
                   18182:         $formname = $caller;
                   18183:     }
                   18184:     foreach my $item (@{$filterlist}) {
                   18185:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   18186:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   18187:             if ($item eq 'domainfilter') {
                   18188:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   18189:             } elsif ($item eq 'coursefilter') {
                   18190:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   18191:             } elsif ($item eq 'ownerfilter') {
                   18192:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18193:             } elsif ($item eq 'ownerdomfilter') {
                   18194:                 $filter->{'ownerdomfilter'} =
                   18195:                     &LONCAPA::clean_domain($filter->{$item});
                   18196:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   18197:                                                        'ownerdomfilter',1);
                   18198:             } elsif ($item eq 'personfilter') {
                   18199:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   18200:             } elsif ($item eq 'persondomfilter') {
                   18201:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   18202:                                                         'persondomfilter',1);
                   18203:             } else {
                   18204:                 $filter->{$item} =~ s/\W//g;
                   18205:             }
                   18206:             if (!$filter->{$item}) {
                   18207:                 $filter->{$item} = '';
                   18208:             }
                   18209:         }
                   18210:         if ($item eq 'domainfilter') {
                   18211:             my $allow_blank = 1;
                   18212:             if ($formname eq 'portform') {
                   18213:                 $allow_blank=0;
                   18214:             } elsif ($formname eq 'studentform') {
                   18215:                 $allow_blank=0;
                   18216:             }
                   18217:             if ($fixeddom) {
                   18218:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   18219:                                     ' value="'.$codedom.'" />'.
                   18220:                                     &Apache::lonnet::domain($codedom,'description');
                   18221:             } else {
                   18222:                 $domainselectform = &select_dom_form($filter->{$item},
                   18223:                                                      'domainfilter',
                   18224:                                                       $allow_blank,'',$onchange);
                   18225:             }
                   18226:         } else {
                   18227:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   18228:         }
                   18229:     }
                   18230: 
                   18231:     # last course activity filter and selection
                   18232:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   18233: 
                   18234:     # course created filter and selection
                   18235:     if (exists($filter->{'createdfilter'})) {
                   18236:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   18237:     }
                   18238: 
1.1239    raeburn  18239:     my $prefix = $crstype;
                   18240:     if ($crstype eq 'Placement') {
                   18241:         $prefix = 'Placement Test'
                   18242:     }
1.1181    raeburn  18243:     my %lt = &Apache::lonlocal::texthash(
1.1239    raeburn  18244:                 'cac' => "$prefix Activity",
                   18245:                 'ccr' => "$prefix Created",
                   18246:                 'cde' => "$prefix Title",
                   18247:                 'cdo' => "$prefix Domain",
1.1181    raeburn  18248:                 'ins' => 'Institutional Code',
                   18249:                 'inc' => 'Institutional Categorization',
1.1239    raeburn  18250:                 'cow' => "$prefix Owner/Co-owner",
                   18251:                 'cop' => "$prefix Personnel Includes",
1.1181    raeburn  18252:                 'cog' => 'Type',
                   18253:              );
                   18254: 
                   18255:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18256:         my $typeval = 'Course';
                   18257:         if ($crstype eq 'Community') {
                   18258:             $typeval = 'Community';
1.1239    raeburn  18259:         } elsif ($crstype eq 'Placement') {
                   18260:             $typeval = 'Placement';
1.1181    raeburn  18261:         }
                   18262:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   18263:     } else {
                   18264:         $typeselectform =  '<select name="type" size="1"';
                   18265:         if ($onchange) {
                   18266:             $typeselectform .= ' onchange="'.$onchange.'"';
                   18267:         }
                   18268:         $typeselectform .= '>'."\n";
1.1237    raeburn  18269:         foreach my $posstype ('Course','Community','Placement') {
1.1239    raeburn  18270:             my $shown;
                   18271:             if ($posstype eq 'Placement') {
                   18272:                 $shown = &mt('Placement Test');
                   18273:             } else {
                   18274:                 $shown = &mt($posstype);
                   18275:             }
1.1181    raeburn  18276:             $typeselectform.='<option value="'.$posstype.'"'.
1.1239    raeburn  18277:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
1.1181    raeburn  18278:         }
                   18279:         $typeselectform.="</select>";
                   18280:     }
                   18281: 
                   18282:     my ($cloneableonlyform,$cloneabletitle);
                   18283:     if (exists($filter->{'cloneableonly'})) {
                   18284:         my $cloneableon = '';
                   18285:         my $cloneableoff = ' checked="checked"';
                   18286:         if ($filter->{'cloneableonly'}) {
                   18287:             $cloneableon = $cloneableoff;
                   18288:             $cloneableoff = '';
                   18289:         }
                   18290:         $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>';
                   18291:         if ($formname eq 'ccrs') {
1.1187    bisitz   18292:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  18293:         } else {
                   18294:             $cloneabletitle = &mt('Cloneable by you');
                   18295:         }
                   18296:     }
                   18297:     my $officialjs;
                   18298:     if ($crstype eq 'Course') {
                   18299:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  18300: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   18301: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   18302:             if ($codedom) { 
1.1181    raeburn  18303:                 $officialjs = 1;
                   18304:                 ($instcodeform,$jscript,$$numtitlesref) =
                   18305:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   18306:                                                                   $officialjs,$codetitlesref);
                   18307:                 if ($jscript) {
1.1182    raeburn  18308:                     $jscript = '<script type="text/javascript">'."\n".
                   18309:                                '// <![CDATA['."\n".
                   18310:                                $jscript."\n".
                   18311:                                '// ]]>'."\n".
                   18312:                                '</script>'."\n";
1.1181    raeburn  18313:                 }
                   18314:             }
                   18315:             if ($instcodeform eq '') {
                   18316:                 $instcodeform =
                   18317:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   18318:                     $list->{'instcodefilter'}.'" />';
                   18319:                 $instcodetitle = $lt{'ins'};
                   18320:             } else {
                   18321:                 $instcodetitle = $lt{'inc'};
                   18322:             }
                   18323:             if ($fixeddom) {
                   18324:                 $instcodetitle .= '<br />('.$codedom.')';
                   18325:             }
                   18326:         }
                   18327:     }
                   18328:     my $output = qq|
                   18329: <form method="post" name="filterpicker" action="$action">
                   18330: <input type="hidden" name="form" value="$formname" />
                   18331: |;
                   18332:     if ($formname eq 'modifycourse') {
                   18333:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   18334:                    '<input type="hidden" name="prevphase" value="'.
                   18335:                    $prevphase.'" />'."\n";
1.1198    musolffc 18336:     } elsif ($formname eq 'quotacheck') {
                   18337:         $output .= qq|
                   18338: <input type="hidden" name="sortby" value="" />
                   18339: <input type="hidden" name="sortorder" value="" />
                   18340: |;
                   18341:     } else {
1.1181    raeburn  18342:         my $name_input;
                   18343:         if ($cnameelement ne '') {
                   18344:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   18345:                           $cnameelement.'" />';
                   18346:         }
                   18347:         $output .= qq|
1.1182    raeburn  18348: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   18349: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  18350: $name_input
                   18351: $roleelement
                   18352: $multelement
                   18353: $typeelement
                   18354: |;
                   18355:         if ($formname eq 'portform') {
                   18356:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   18357:         }
                   18358:     }
                   18359:     if ($fixeddom) {
                   18360:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   18361:     }
                   18362:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   18363:     if ($sincefilterform) {
                   18364:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   18365:                   .$sincefilterform
                   18366:                   .&Apache::lonhtmlcommon::row_closure();
                   18367:     }
                   18368:     if ($createdfilterform) {
                   18369:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   18370:                   .$createdfilterform
                   18371:                   .&Apache::lonhtmlcommon::row_closure();
                   18372:     }
                   18373:     if ($domainselectform) {
                   18374:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   18375:                   .$domainselectform
                   18376:                   .&Apache::lonhtmlcommon::row_closure();
                   18377:     }
                   18378:     if ($typeselectform) {
                   18379:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   18380:             $output .= $typeselectform;
                   18381:         } else {
                   18382:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   18383:                       .$typeselectform
                   18384:                       .&Apache::lonhtmlcommon::row_closure();
                   18385:         }
                   18386:     }
                   18387:     if ($instcodeform) {
                   18388:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   18389:                   .$instcodeform
                   18390:                   .&Apache::lonhtmlcommon::row_closure();
                   18391:     }
                   18392:     if (exists($filter->{'ownerfilter'})) {
                   18393:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   18394:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18395:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   18396:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18397:                    $ownerdomselectform.'</td></tr></table>'.
                   18398:                    &Apache::lonhtmlcommon::row_closure();
                   18399:     }
                   18400:     if (exists($filter->{'personfilter'})) {
                   18401:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   18402:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   18403:                    '<input type="text" name="personfilter" size="20" value="'.
                   18404:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   18405:                    $persondomselectform.'</td></tr></table>'.
                   18406:                    &Apache::lonhtmlcommon::row_closure();
                   18407:     }
                   18408:     if (exists($filter->{'coursefilter'})) {
                   18409:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   18410:                   .'<input type="text" name="coursefilter" size="25" value="'
                   18411:                   .$list->{'coursefilter'}.'" />'
                   18412:                   .&Apache::lonhtmlcommon::row_closure();
                   18413:     }
                   18414:     if ($cloneableonlyform) {
                   18415:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   18416:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   18417:     }
                   18418:     if (exists($filter->{'descriptfilter'})) {
                   18419:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   18420:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   18421:                   .$list->{'descriptfilter'}.'" />'
                   18422:                   .&Apache::lonhtmlcommon::row_closure(1);
                   18423:     }
                   18424:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   18425:                '<input type="hidden" name="updater" value="" />'."\n".
                   18426:                '<input type="submit" name="gosearch" value="'.
                   18427:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   18428:     return $jscript.$clonewarning.$output;
                   18429: }
                   18430: 
                   18431: =pod 
                   18432: 
                   18433: =item * &timebased_select_form()
                   18434: 
1.1182    raeburn  18435: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  18436: filter e.g., Course Activity, Course Created, when searching for courses
                   18437: or communities
                   18438: 
                   18439: Inputs:
                   18440: 
                   18441: item - name of form element (sincefilter or createdfilter)
                   18442: 
                   18443: filter - anonymous hash of criteria and their values
                   18444: 
                   18445: Returns: HTML for a select box contained a blank, then six time selections,
                   18446:          with value set in incoming form variables currently selected. 
                   18447: 
                   18448: Side Effects: None
                   18449: 
                   18450: =cut
                   18451: 
                   18452: sub timebased_select_form {
                   18453:     my ($item,$filter) = @_;
                   18454:     if (ref($filter) eq 'HASH') {
                   18455:         $filter->{$item} =~ s/[^\d-]//g;
                   18456:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   18457:         return &select_form(
                   18458:                             $filter->{$item},
                   18459:                             $item,
                   18460:                             {      '-1' => '',
                   18461:                                 '86400' => &mt('today'),
                   18462:                                '604800' => &mt('last week'),
                   18463:                               '2592000' => &mt('last month'),
                   18464:                               '7776000' => &mt('last three months'),
                   18465:                              '15552000' => &mt('last six months'),
                   18466:                              '31104000' => &mt('last year'),
                   18467:                     'select_form_order' =>
                   18468:                            ['-1','86400','604800','2592000','7776000',
                   18469:                             '15552000','31104000']});
                   18470:     }
                   18471: }
                   18472: 
                   18473: =pod
                   18474: 
                   18475: =item * &js_changer()
                   18476: 
                   18477: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  18478: when course type or domain is changed, and also to hide 'Searching ...' on
                   18479: page load completion for page showing search result.
1.1181    raeburn  18480: 
                   18481: Inputs: None
                   18482: 
1.1183    raeburn  18483: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  18484: 
                   18485: Side Effects: None
                   18486: 
                   18487: =cut
                   18488: 
                   18489: sub js_changer {
                   18490:     return <<ENDJS;
                   18491: <script type="text/javascript">
                   18492: // <![CDATA[
                   18493: function updateFilters(caller) {
                   18494:     if (typeof(caller) != "undefined") {
                   18495:         document.filterpicker.updater.value = caller.name;
                   18496:     }
                   18497:     document.filterpicker.submit();
                   18498: }
1.1183    raeburn  18499: 
                   18500: function hideSearching() {
                   18501:     if (document.getElementById('searching')) {
                   18502:         document.getElementById('searching').style.display = 'none';
                   18503:     }
                   18504:     return;
                   18505: }
                   18506: 
1.1181    raeburn  18507: // ]]>
                   18508: </script>
                   18509: 
                   18510: ENDJS
                   18511: }
                   18512: 
                   18513: =pod
                   18514: 
1.1182    raeburn  18515: =item * &search_courses()
                   18516: 
                   18517: Process selected filters form course search form and pass to lonnet::courseiddump
                   18518: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   18519: 
                   18520: Inputs:
                   18521: 
                   18522: dom - domain being searched 
                   18523: 
                   18524: type - course type ('Course' or 'Community' or '.' if any).
                   18525: 
                   18526: filter - anonymous hash of criteria and their values
                   18527: 
                   18528: numtitles - for institutional codes - number of categories
                   18529: 
                   18530: cloneruname - optional username of new course owner
                   18531: 
                   18532: clonerudom - optional domain of new course owner
                   18533: 
1.1221    raeburn  18534: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
1.1182    raeburn  18535:             (used when DC is using course creation form)
                   18536: 
                   18537: codetitles - reference to array of titles of components in institutional codes (official courses).
                   18538: 
1.1221    raeburn  18539: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   18540:            (and so can clone automatically)
                   18541: 
                   18542: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   18543: 
                   18544: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
                   18545:               courses to clone 
1.1182    raeburn  18546: 
                   18547: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   18548: 
                   18549: 
                   18550: Side Effects: None
                   18551: 
                   18552: =cut
                   18553: 
                   18554: 
                   18555: sub search_courses {
1.1221    raeburn  18556:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   18557:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1182    raeburn  18558:     my (%courses,%showcourses,$cloner);
                   18559:     if (($filter->{'ownerfilter'} ne '') ||
                   18560:         ($filter->{'ownerdomfilter'} ne '')) {
                   18561:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   18562:                                        $filter->{'ownerdomfilter'};
                   18563:     }
                   18564:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   18565:         if (!$filter->{$item}) {
                   18566:             $filter->{$item}='.';
                   18567:         }
                   18568:     }
                   18569:     my $now = time;
                   18570:     my $timefilter =
                   18571:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   18572:     my ($createdbefore,$createdafter);
                   18573:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   18574:         $createdbefore = $now;
                   18575:         $createdafter = $now-$filter->{'createdfilter'};
                   18576:     }
                   18577:     my ($instcodefilter,$regexpok);
                   18578:     if ($numtitles) {
                   18579:         if ($env{'form.official'} eq 'on') {
                   18580:             $instcodefilter =
                   18581:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18582:             $regexpok = 1;
                   18583:         } elsif ($env{'form.official'} eq 'off') {
                   18584:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   18585:             unless ($instcodefilter eq '') {
                   18586:                 $regexpok = -1;
                   18587:             }
                   18588:         }
                   18589:     } else {
                   18590:         $instcodefilter = $filter->{'instcodefilter'};
                   18591:     }
                   18592:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   18593:     if ($type eq '') { $type = '.'; }
                   18594: 
                   18595:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   18596:         $cloner = $cloneruname.':'.$clonerudom;
                   18597:     }
                   18598:     %courses = &Apache::lonnet::courseiddump($dom,
                   18599:                                              $filter->{'descriptfilter'},
                   18600:                                              $timefilter,
                   18601:                                              $instcodefilter,
                   18602:                                              $filter->{'combownerfilter'},
                   18603:                                              $filter->{'coursefilter'},
                   18604:                                              undef,undef,$type,$regexpok,undef,undef,
1.1221    raeburn  18605:                                              undef,undef,$cloner,$cc_clone,
1.1182    raeburn  18606:                                              $filter->{'cloneableonly'},
                   18607:                                              $createdbefore,$createdafter,undef,
1.1221    raeburn  18608:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1182    raeburn  18609:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   18610:         my $ccrole;
                   18611:         if ($type eq 'Community') {
                   18612:             $ccrole = 'co';
                   18613:         } else {
                   18614:             $ccrole = 'cc';
                   18615:         }
                   18616:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   18617:                                                      $filter->{'persondomfilter'},
                   18618:                                                      'userroles',undef,
                   18619:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   18620:                                                      $dom);
                   18621:         foreach my $role (keys(%rolehash)) {
                   18622:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   18623:             my $cid = $cdom.'_'.$cnum;
                   18624:             if (exists($courses{$cid})) {
                   18625:                 if (ref($courses{$cid}) eq 'HASH') {
                   18626:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   18627:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1263    raeburn  18628:                             push(@{$courses{$cid}{roles}},$courserole);
1.1182    raeburn  18629:                         }
                   18630:                     } else {
                   18631:                         $courses{$cid}{roles} = [$courserole];
                   18632:                     }
                   18633:                     $showcourses{$cid} = $courses{$cid};
                   18634:                 }
                   18635:             }
                   18636:         }
                   18637:         %courses = %showcourses;
                   18638:     }
                   18639:     return %courses;
                   18640: }
                   18641: 
                   18642: =pod
                   18643: 
1.1181    raeburn  18644: =back
                   18645: 
1.1207    raeburn  18646: =head1 Routines for version requirements for current course.
                   18647: 
                   18648: =over 4
                   18649: 
                   18650: =item * &check_release_required()
                   18651: 
                   18652: Compares required LON-CAPA version with version on server, and
                   18653: if required version is newer looks for a server with the required version.
                   18654: 
                   18655: Looks first at servers in user's owen domain; if none suitable, looks at
                   18656: servers in course's domain are permitted to host sessions for user's domain.
                   18657: 
                   18658: Inputs:
                   18659: 
                   18660: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18661: 
                   18662: $courseid - Course ID of current course
                   18663: 
                   18664: $rolecode - User's current role in course (for switchserver query string).
                   18665: 
                   18666: $required - LON-CAPA version needed by course (format: Major.Minor).
                   18667: 
                   18668: 
                   18669: Returns:
                   18670: 
                   18671: $switchserver - query string tp append to /adm/switchserver call (if 
                   18672:                 current server's LON-CAPA version is too old. 
                   18673: 
                   18674: $warning - Message is displayed if no suitable server could be found.
                   18675: 
                   18676: =cut
                   18677: 
                   18678: sub check_release_required {
                   18679:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   18680:     my ($switchserver,$warning);
                   18681:     if ($required ne '') {
                   18682:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   18683:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18684:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   18685:             my $otherserver;
                   18686:             if (($major eq '' && $minor eq '') ||
                   18687:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   18688:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   18689:                 my $switchlcrev =
                   18690:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   18691:                                                            $userdomserver);
                   18692:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   18693:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   18694:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   18695:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   18696:                     if ($cdom ne $env{'user.domain'}) {
                   18697:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   18698:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   18699:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   18700:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   18701:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   18702:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   18703:                         my $canhost =
                   18704:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   18705:                                                               $coursedomserver,
                   18706:                                                               $remoterev,
                   18707:                                                               $udomdefaults{'remotesessions'},
                   18708:                                                               $defdomdefaults{'hostedsessions'});
                   18709: 
                   18710:                         if ($canhost) {
                   18711:                             $otherserver = $coursedomserver;
                   18712:                         } else {
                   18713:                             $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.");
                   18714:                         }
                   18715:                     } else {
                   18716:                         $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).");
                   18717:                     }
                   18718:                 } else {
                   18719:                     $otherserver = $userdomserver;
                   18720:                 }
                   18721:             }
                   18722:             if ($otherserver ne '') {
                   18723:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   18724:             }
                   18725:         }
                   18726:     }
                   18727:     return ($switchserver,$warning);
                   18728: }
                   18729: 
                   18730: =pod
                   18731: 
                   18732: =item * &check_release_result()
                   18733: 
                   18734: Inputs:
                   18735: 
                   18736: $switchwarning - Warning message if no suitable server found to host session.
                   18737: 
                   18738: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18739:                 and current role.
                   18740: 
                   18741: Returns: HTML to display with information about requirement to switch server.
                   18742:          Either displaying warning with link to Roles/Courses screen or
                   18743:          display link to switchserver.
                   18744: 
1.1181    raeburn  18745: =cut
                   18746: 
1.1207    raeburn  18747: sub check_release_result {
                   18748:     my ($switchwarning,$switchserver) = @_;
                   18749:     my $output = &start_page('Selected course unavailable on this server').
                   18750:                  '<p class="LC_warning">';
                   18751:     if ($switchwarning) {
                   18752:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   18753:         if (&show_course()) {
                   18754:             $output .= &mt('Display courses');
                   18755:         } else {
                   18756:             $output .= &mt('Display roles');
                   18757:         }
                   18758:         $output .= '</a>';
                   18759:     } elsif ($switchserver) {
                   18760:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   18761:                    '<br />'.
                   18762:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   18763:                    &mt('Switch Server').
                   18764:                    '</a>';
                   18765:     }
                   18766:     $output .= '</p>'.&end_page();
                   18767:     return $output;
                   18768: }
                   18769: 
                   18770: =pod
                   18771: 
                   18772: =item * &needs_coursereinit()
                   18773: 
                   18774: Determine if course contents stored for user's session needs to be
                   18775: refreshed, because content has changed since "Big Hash" last tied.
                   18776: 
                   18777: Check for change is made if time last checked is more than 10 minutes ago
                   18778: (by default).
                   18779: 
                   18780: Inputs:
                   18781: 
                   18782: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   18783: 
                   18784: $interval (optional) - Time which may elapse (in s) between last check for content
                   18785:                        change in current course. (default: 600 s).  
                   18786: 
                   18787: Returns: an array; first element is:
                   18788: 
                   18789: =over 4
                   18790: 
                   18791: 'switch' - if content updates mean user's session
                   18792:            needs to be switched to a server running a newer LON-CAPA version
                   18793:  
                   18794: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   18795:            on current server hosting user's session                
                   18796: 
                   18797: ''       - if no action required.
                   18798: 
                   18799: =back
                   18800: 
                   18801: If first item element is 'switch':
                   18802: 
                   18803: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   18804: 
                   18805: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   18806:                               and current role. 
                   18807: 
                   18808: otherwise: no other elements returned.
                   18809: 
                   18810: =back
                   18811: 
                   18812: =cut
                   18813: 
                   18814: sub needs_coursereinit {
                   18815:     my ($loncaparev,$interval) = @_;
                   18816:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   18817:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   18818:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   18819:     my $now = time;
                   18820:     if ($interval eq '') {
                   18821:         $interval = 600;
                   18822:     }
                   18823:     if (($now-$env{'request.course.timechecked'})>$interval) {
1.1282    raeburn  18824:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
1.1372    raeburn  18825:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  18826:         if ($blocked) {
                   18827:             return ();
                   18828:         }
1.1391    raeburn  18829:         my $update;
                   18830:         my $lastmainchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18831:         my $lastsuppchange = &Apache::lonnet::get_suppchange($cdom,$cnum);
                   18832:         if ($lastmainchange > $env{'request.course.tied'}) {
                   18833:             my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18834:             if ($needswitch) {
                   18835:                 return ('switch',$switchwarning,$switchserver);
                   18836:             }
                   18837:             $update = 'main';
                   18838:         }
                   18839:         if ($lastsuppchange > $env{'request.course.suppupdated'}) {
                   18840:             if ($update) {
                   18841:                 $update = 'both';
                   18842:             } else {
                   18843:                 my ($needswitch,$switchwarning,$switchserver) = &switch_for_update($loncaparev,$cdom,$cnum);
                   18844:                 if ($needswitch) {
                   18845:                     return ('switch',$switchwarning,$switchserver);
                   18846:                 } else {
                   18847:                     $update = 'supp';
1.1207    raeburn  18848:                 }
                   18849:             }
1.1391    raeburn  18850:             return ($update);
                   18851:         }
                   18852:     }
                   18853:     return ();
                   18854: }
                   18855: 
                   18856: sub switch_for_update {
                   18857:     my ($loncaparev,$cdom,$cnum) = @_;
                   18858:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18859:     if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   18860:         my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   18861:         if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   18862:             &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   18863:                                     $curr_reqd_hash{'internal.releaserequired'}});
                   18864:             my ($switchserver,$switchwarning) =
                   18865:                 &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   18866:                                         $curr_reqd_hash{'internal.releaserequired'});
                   18867:             if ($switchwarning ne '' || $switchserver ne '') {
                   18868:                 return ('switch',$switchwarning,$switchserver);
                   18869:             }
1.1207    raeburn  18870:         }
                   18871:     }
                   18872:     return ();
                   18873: }
1.1181    raeburn  18874: 
1.1083    raeburn  18875: sub update_content_constraints {
1.1395    raeburn  18876:     my ($cdom,$cnum,$chome,$cid) = @_;
1.1083    raeburn  18877:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   18878:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
1.1307    raeburn  18879:     my (%checkresponsetypes,%checkcrsrestypes);
1.1083    raeburn  18880:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
1.1236    raeburn  18881:         my ($item,$name,$value) = split(/:/,$key);
1.1083    raeburn  18882:         if ($item eq 'resourcetag') {
                   18883:             if ($name eq 'responsetype') {
                   18884:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   18885:             }
1.1307    raeburn  18886:         } elsif ($item eq 'course') {
                   18887:             if ($name eq 'courserestype') {
                   18888:                 $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
                   18889:             }
1.1083    raeburn  18890:         }
                   18891:     }
                   18892:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18893:     if (defined($navmap)) {
1.1307    raeburn  18894:         my (%allresponses,%allcrsrestypes);
                   18895:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
                   18896:             if ($res->is_tool()) {
                   18897:                 if ($allcrsrestypes{'exttool'}) {
                   18898:                     $allcrsrestypes{'exttool'} ++;
                   18899:                 } else {
                   18900:                     $allcrsrestypes{'exttool'} = 1;
                   18901:                 }
                   18902:                 next;
                   18903:             }
1.1083    raeburn  18904:             my %responses = $res->responseTypes();
                   18905:             foreach my $key (keys(%responses)) {
                   18906:                 next unless(exists($checkresponsetypes{$key}));
                   18907:                 $allresponses{$key} += $responses{$key};
                   18908:             }
                   18909:         }
                   18910:         foreach my $key (keys(%allresponses)) {
                   18911:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   18912:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18913:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18914:             }
                   18915:         }
1.1307    raeburn  18916:         foreach my $key (keys(%allcrsrestypes)) {
1.1308    raeburn  18917:             my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
1.1307    raeburn  18918:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18919:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   18920:             }
                   18921:         }
1.1083    raeburn  18922:         undef($navmap);
                   18923:     }
1.1391    raeburn  18924:     if (&Apache::lonnet::count_supptools($cnum,$cdom,1)) {
1.1308    raeburn  18925:         my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
                   18926:         if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   18927:             ($reqdmajor,$reqdminor) = ($major,$minor);
                   18928:         }
                   18929:     }
1.1083    raeburn  18930:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   18931:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   18932:     }
                   18933:     return;
                   18934: }
                   18935: 
1.1110    raeburn  18936: sub allmaps_incourse {
                   18937:     my ($cdom,$cnum,$chome,$cid) = @_;
                   18938:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   18939:         $cid = $env{'request.course.id'};
                   18940:         $cdom = $env{'course.'.$cid.'.domain'};
                   18941:         $cnum = $env{'course.'.$cid.'.num'};
                   18942:         $chome = $env{'course.'.$cid.'.home'};
                   18943:     }
                   18944:     my %allmaps = ();
                   18945:     my $lastchange =
                   18946:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   18947:     if ($lastchange > $env{'request.course.tied'}) {
                   18948:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   18949:         unless ($ferr) {
1.1395    raeburn  18950:             &update_content_constraints($cdom,$cnum,$chome,$cid);
1.1110    raeburn  18951:         }
                   18952:     }
                   18953:     my $navmap = Apache::lonnavmaps::navmap->new();
                   18954:     if (defined($navmap)) {
                   18955:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   18956:             $allmaps{$res->src()} = 1;
                   18957:         }
                   18958:     }
                   18959:     return \%allmaps;
                   18960: }
                   18961: 
1.1083    raeburn  18962: sub parse_supplemental_title {
                   18963:     my ($title) = @_;
                   18964: 
                   18965:     my ($foldertitle,$renametitle);
                   18966:     if ($title =~ /&amp;&amp;&amp;/) {
                   18967:         $title = &HTML::Entites::decode($title);
                   18968:     }
                   18969:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   18970:         $renametitle=$4;
                   18971:         my ($time,$uname,$udom) = ($1,$2,$3);
                   18972:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   18973:         my $name =  &plainname($uname,$udom);
                   18974:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   18975:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
1.1401    raeburn  18976:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.$name;
1.1402    raeburn  18977:         if ($foldertitle ne '') {
1.1401    raeburn  18978:             $title .= ': <br />'.$foldertitle;
                   18979:         }
1.1083    raeburn  18980:     }
                   18981:     if (wantarray) {
                   18982:         return ($title,$foldertitle,$renametitle);
                   18983:     }
                   18984:     return $title;
                   18985: }
                   18986: 
1.1395    raeburn  18987: sub get_supplemental {
                   18988:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   18989:     my $hashid=$cnum.':'.$cdom;
                   18990:     my ($supplemental,$cached,$set_httprefs);
                   18991:     unless ($ignorecache) {
                   18992:         ($supplemental,$cached) = &Apache::lonnet::is_cached_new('supplemental',$hashid);
                   18993:     }
                   18994:     unless (defined($cached)) {
                   18995:         my $chome=&Apache::lonnet::homeserver($cnum,$cdom);
                   18996:         unless ($chome eq 'no_host') {
                   18997:             my @order = @LONCAPA::map::order;
                   18998:             my @resources = @LONCAPA::map::resources;
                   18999:             my @resparms = @LONCAPA::map::resparms;
                   19000:             my @zombies = @LONCAPA::map::zombies;
                   19001:             my ($errors,%ids,%hidden);
                   19002:             $errors =
                   19003:                 &recurse_supplemental($cnum,$cdom,'supplemental.sequence',
                   19004:                                       $errors,$possdel,\%ids,\%hidden);
                   19005:             @LONCAPA::map::order = @order;
                   19006:             @LONCAPA::map::resources = @resources;
                   19007:             @LONCAPA::map::resparms = @resparms;
                   19008:             @LONCAPA::map::zombies = @zombies;
                   19009:             $set_httprefs = 1;
                   19010:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19011:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19012:             }
                   19013:             $supplemental = {
                   19014:                                ids => \%ids,
                   19015:                                hidden => \%hidden,
                   19016:                             };
                   19017:             &Apache::lonnet::do_cache_new('supplemental',$hashid,$supplemental,600);
                   19018:         }
                   19019:     }
                   19020:     return ($supplemental,$set_httprefs);
                   19021: }
                   19022: 
1.1143    raeburn  19023: sub recurse_supplemental {
1.1391    raeburn  19024:     my ($cnum,$cdom,$suppmap,$errors,$possdel,$suppids,$hiddensupp,$hidden) = @_;
                   19025:     if (($suppmap) && (ref($suppids) eq 'HASH') && (ref($hiddensupp) eq 'HASH')) {
                   19026:         my $mapnum;
                   19027:         if ($suppmap eq 'supplemental.sequence') {
                   19028:             $mapnum = 0;
                   19029:         } else {
                   19030:             ($mapnum) = ($suppmap =~ /^supplemental_(\d+)\.sequence$/);
                   19031:         }
1.1143    raeburn  19032:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   19033:         if ($fatal) {
                   19034:             $errors ++;
                   19035:         } else {
1.1389    raeburn  19036:             my @order = @LONCAPA::map::order;
                   19037:             if (@order > 0) {
                   19038:                 my @resources = @LONCAPA::map::resources;
1.1391    raeburn  19039:                 my @resparms = @LONCAPA::map::resparms;
1.1389    raeburn  19040:                 foreach my $idx (@order) {
                   19041:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$resources[$idx]);
1.1143    raeburn  19042:                     if (($src ne '') && ($status eq 'res')) {
1.1391    raeburn  19043:                         my $id = $mapnum.':'.$idx;
                   19044:                         push(@{$suppids->{$src}},$id);
                   19045:                         if (($hidden) || (&get_supp_parameter($resparms[$idx],'parameter_hiddenresource') =~ /^yes/i)) {
                   19046:                             $hiddensupp->{$id} = 1;
                   19047:                         }
1.1146    raeburn  19048:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
1.1391    raeburn  19049:                             $errors = &recurse_supplemental($cnum,$cdom,$1,$errors,$possdel,$suppids,
                   19050:                                                             $hiddensupp,$hiddensupp->{$id});
1.1143    raeburn  19051:                         } else {
1.1391    raeburn  19052:                             my $allowed;
                   19053:                             if (($env{'request.role.adv'}) || (!$hiddensupp->{$id})) {
                   19054:                                 $allowed = 1;
                   19055:                             } elsif ($possdel) {
                   19056:                                 foreach my $item (@{$suppids->{$src}}) {
                   19057:                                     next if ($item eq $id);
                   19058:                                     unless ($hiddensupp->{$item}) {
                   19059:                                        $allowed = 1;
                   19060:                                        last;
                   19061:                                     }
                   19062:                                 }
                   19063:                                 if ((!$allowed) && (exists($env{'httpref.'.$src}))) {
                   19064:                                     &Apache::lonnet::delenv('httpref.'.$src);
                   19065:                                 }
                   19066:                             }
                   19067:                             if ($allowed && (!exists($env{'httpref.'.$src}))) {
                   19068:                                 &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
1.1308    raeburn  19069:                             }
1.1143    raeburn  19070:                         }
                   19071:                     }
                   19072:                 }
                   19073:             }
                   19074:         }
                   19075:     }
1.1391    raeburn  19076:     return $errors;
                   19077: }
                   19078: 
                   19079: sub set_supp_httprefs {
                   19080:     my ($cnum,$cdom,$supplemental,$possdel) = @_;
                   19081:     if (ref($supplemental) eq 'HASH') {
                   19082:         if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   19083:             foreach my $src (keys(%{$supplemental->{'ids'}})) {
                   19084:                 next if ($src =~ /\.sequence$/);
                   19085:                 if (ref($supplemental->{'ids'}->{$src}) eq 'ARRAY') {
                   19086:                     my $allowed;
                   19087:                     if ($env{'request.role.adv'}) {
                   19088:                         $allowed = 1;
                   19089:                     } else {
                   19090:                         foreach my $id (@{$supplemental->{'ids'}->{$src}}) {
                   19091:                             unless ($supplemental->{'hidden'}->{$id}) {
                   19092:                                 $allowed = 1;
                   19093:                                 last;
                   19094:                             }
                   19095:                         }
                   19096:                     }
                   19097:                     if (exists($env{'httpref.'.$src})) {
                   19098:                         if ($possdel) {
                   19099:                             unless ($allowed) {
                   19100:                                 &Apache::lonnet::delenv('httpref.'.$src);
                   19101:                             }
                   19102:                         }
                   19103:                     } elsif ($allowed) {
                   19104:                         &Apache::lonnet::allowuploaded('/adm/coursedoc',$src);
                   19105:                     }
                   19106:                 }
                   19107:             }
                   19108:             if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   19109:                 &Apache::lonnet::appenv({'request.course.suppupdated' => time});
                   19110:             }
                   19111:         }
                   19112:     }
                   19113: }
                   19114: 
                   19115: sub get_supp_parameter {
                   19116:     my ($resparm,$name)=@_;
                   19117:     return if ($resparm eq '');
                   19118:     my $value=undef;
                   19119:     my $ptype=undef;
                   19120:     foreach (split('&&&',$resparm)) {
                   19121:         my ($thistype,$thisname,$thisvalue)=split('___',$_);
                   19122:         if ($thisname eq $name) {
                   19123:             $value=$thisvalue;
                   19124:             $ptype=$thistype;
                   19125:         }
                   19126:     }
                   19127:     return $value;
1.1143    raeburn  19128: }
                   19129: 
1.1101    raeburn  19130: sub symb_to_docspath {
1.1267    raeburn  19131:     my ($symb,$navmapref) = @_;
                   19132:     return unless ($symb && ref($navmapref));
1.1101    raeburn  19133:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   19134:     if ($resurl=~/\.(sequence|page)$/) {
                   19135:         $mapurl=$resurl;
                   19136:     } elsif ($resurl eq 'adm/navmaps') {
                   19137:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   19138:     }
                   19139:     my $mapresobj;
1.1267    raeburn  19140:     unless (ref($$navmapref)) {
                   19141:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   19142:     }
                   19143:     if (ref($$navmapref)) {
                   19144:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1101    raeburn  19145:     }
                   19146:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   19147:     my $type=$2;
                   19148:     my $path;
                   19149:     if (ref($mapresobj)) {
                   19150:         my $pcslist = $mapresobj->map_hierarchy();
                   19151:         if ($pcslist ne '') {
                   19152:             foreach my $pc (split(/,/,$pcslist)) {
                   19153:                 next if ($pc <= 1);
1.1267    raeburn  19154:                 my $res = $$navmapref->getByMapPc($pc);
1.1101    raeburn  19155:                 if (ref($res)) {
                   19156:                     my $thisurl = $res->src();
                   19157:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   19158:                     my $thistitle = $res->title();
                   19159:                     $path .= '&'.
                   19160:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  19161:                              &escape($thistitle).
1.1101    raeburn  19162:                              ':'.$res->randompick().
                   19163:                              ':'.$res->randomout().
                   19164:                              ':'.$res->encrypted().
                   19165:                              ':'.$res->randomorder().
                   19166:                              ':'.$res->is_page();
                   19167:                 }
                   19168:             }
                   19169:         }
                   19170:         $path =~ s/^\&//;
                   19171:         my $maptitle = $mapresobj->title();
                   19172:         if ($mapurl eq 'default') {
1.1129    raeburn  19173:             $maptitle = 'Main Content';
1.1101    raeburn  19174:         }
                   19175:         $path .= (($path ne '')? '&' : '').
                   19176:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19177:                  &escape($maptitle).
1.1101    raeburn  19178:                  ':'.$mapresobj->randompick().
                   19179:                  ':'.$mapresobj->randomout().
                   19180:                  ':'.$mapresobj->encrypted().
                   19181:                  ':'.$mapresobj->randomorder().
                   19182:                  ':'.$mapresobj->is_page();
                   19183:     } else {
                   19184:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   19185:         my $ispage = (($type eq 'page')? 1 : '');
                   19186:         if ($mapurl eq 'default') {
1.1129    raeburn  19187:             $maptitle = 'Main Content';
1.1101    raeburn  19188:         }
                   19189:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  19190:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  19191:     }
                   19192:     unless ($mapurl eq 'default') {
                   19193:         $path = 'default&'.
1.1146    raeburn  19194:                 &escape('Main Content').
1.1101    raeburn  19195:                 ':::::&'.$path;
                   19196:     }
                   19197:     return $path;
                   19198: }
                   19199: 
1.1393    raeburn  19200: sub validate_folderpath {
                   19201:     my ($supplementalflag,$allowed,$coursenum,$coursedom) = @_;
                   19202:     if ($env{'form.folderpath'} ne '') {
                   19203:         my @items = split(/\&/,$env{'form.folderpath'});
1.1394    raeburn  19204:         my ($badpath,$changed,$got_supp,$supppath,%supphidden,%suppids);
1.1393    raeburn  19205:         for (my $i=0; $i<@items; $i++) {
                   19206:             my $odd = $i%2;
                   19207:             if (($odd) && (!$supplementalflag) && ($items[$i] !~ /^[^:]*:(|\d+):(|1):(|1):(|1):(|1)$/)) {
                   19208:                 $badpath = 1;
1.1394    raeburn  19209:             } elsif ($odd && $supplementalflag) {
1.1393    raeburn  19210:                 my $idx = $i-1;
1.1394    raeburn  19211:                 if ($items[$i] =~ /^([^:]*)::(|1):::$/) {
                   19212:                     my $esc_name = $1;
                   19213:                     if ((!$allowed) || ($items[$idx] eq 'supplemental')) {
                   19214:                         $supppath .= '&'.$esc_name;
                   19215:                         $changed = 1;
                   19216:                     } else {
                   19217:                         $supppath .= '&'.$items[$i];
                   19218:                     }
                   19219:                 } elsif (($allowed) && ($items[$idx] ne 'supplemental')) {
                   19220:                     $changed = 1;
1.1393    raeburn  19221:                     my $is_hidden;
                   19222:                     unless ($got_supp) {
1.1395    raeburn  19223:                         my ($supplemental) = &get_supplemental($coursenum,$coursedom);
1.1393    raeburn  19224:                         if (ref($supplemental) eq 'HASH') {
                   19225:                             if (ref($supplemental->{'hidden'}) eq 'HASH') {
                   19226:                                 %supphidden = %{$supplemental->{'hidden'}};
                   19227:                             }
                   19228:                             if (ref($supplemental->{'ids'}) eq 'HASH') {
                   19229:                                 %suppids = %{$supplemental->{'ids'}};
                   19230:                             }
                   19231:                         }
                   19232:                         $got_supp = 1;
                   19233:                     }
                   19234:                     if (ref($suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}) eq 'ARRAY') {
                   19235:                         my $mapid = $suppids{"/uploaded/$coursedom/$coursenum/$items[$idx].sequence"}->[0];
                   19236:                         if ($supphidden{$mapid}) {
                   19237:                             $is_hidden = 1;
                   19238:                         }
                   19239:                     }
1.1394    raeburn  19240:                     $supppath .= '&'.$items[$i].'::'.$is_hidden.':::';
                   19241:                 } else {
                   19242:                     $supppath .= '&'.$items[$i];
1.1393    raeburn  19243:                 }
                   19244:             } elsif ((!$odd) && ($items[$i] !~ /^(default|supplemental)(|_\d+)$/)) {
                   19245:                 $badpath = 1;
1.1394    raeburn  19246:             } elsif ($supplementalflag) {
1.1393    raeburn  19247:                 $supppath .= '&'.$items[$i];
                   19248:             }
                   19249:             last if ($badpath);
                   19250:         }
                   19251:         if ($badpath) {
                   19252:             delete($env{'form.folderpath'});
1.1394    raeburn  19253:         } elsif ($changed && $supplementalflag) {
1.1393    raeburn  19254:             $supppath =~ s/^\&//;
                   19255:             $env{'form.folderpath'} = $supppath;
                   19256:         }
                   19257:     }
                   19258:     return;
                   19259: }
                   19260: 
1.1094    raeburn  19261: sub captcha_display {
1.1327    raeburn  19262:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19263:     my ($output,$error);
1.1234    raeburn  19264:     my ($captcha,$pubkey,$privkey,$version) = 
1.1327    raeburn  19265:         &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19266:     if ($captcha eq 'original') {
1.1094    raeburn  19267:         $output = &create_captcha();
                   19268:         unless ($output) {
1.1172    raeburn  19269:             $error = 'captcha';
1.1094    raeburn  19270:         }
                   19271:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19272:         $output = &create_recaptcha($pubkey,$version);
1.1094    raeburn  19273:         unless ($output) {
1.1172    raeburn  19274:             $error = 'recaptcha';
1.1094    raeburn  19275:         }
                   19276:     }
1.1234    raeburn  19277:     return ($output,$error,$captcha,$version);
1.1094    raeburn  19278: }
                   19279: 
                   19280: sub captcha_response {
1.1327    raeburn  19281:     my ($context,$lonhost,$defdom) = @_;
1.1094    raeburn  19282:     my ($captcha_chk,$captcha_error);
1.1327    raeburn  19283:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
1.1095    raeburn  19284:     if ($captcha eq 'original') {
1.1094    raeburn  19285:         ($captcha_chk,$captcha_error) = &check_captcha();
                   19286:     } elsif ($captcha eq 'recaptcha') {
1.1234    raeburn  19287:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1094    raeburn  19288:     } else {
                   19289:         $captcha_chk = 1;
                   19290:     }
                   19291:     return ($captcha_chk,$captcha_error);
                   19292: }
                   19293: 
                   19294: sub get_captcha_config {
1.1327    raeburn  19295:     my ($context,$lonhost,$dom_in_effect) = @_;
1.1234    raeburn  19296:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1094    raeburn  19297:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   19298:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   19299:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  19300:     if ($context eq 'usercreation') {
                   19301:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   19302:         if (ref($domconfig{$context}) eq 'HASH') {
                   19303:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   19304:             if (ref($hashtocheck) eq 'HASH') {
                   19305:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   19306:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   19307:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   19308:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   19309:                     }
                   19310:                     if ($privkey && $pubkey) {
                   19311:                         $captcha = 'recaptcha';
1.1234    raeburn  19312:                         $version = $hashtocheck->{'recaptchaversion'};
                   19313:                         if ($version ne '2') {
                   19314:                             $version = 1;
                   19315:                         }
1.1095    raeburn  19316:                     } else {
                   19317:                         $captcha = 'original';
                   19318:                     }
                   19319:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   19320:                     $captcha = 'original';
                   19321:                 }
1.1094    raeburn  19322:             }
1.1095    raeburn  19323:         } else {
                   19324:             $captcha = 'captcha';
                   19325:         }
                   19326:     } elsif ($context eq 'login') {
                   19327:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   19328:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   19329:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   19330:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  19331:             if ($privkey && $pubkey) {
                   19332:                 $captcha = 'recaptcha';
1.1234    raeburn  19333:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   19334:                 if ($version ne '2') {
                   19335:                     $version = 1; 
                   19336:                 }
1.1095    raeburn  19337:             } else {
                   19338:                 $captcha = 'original';
1.1094    raeburn  19339:             }
1.1095    raeburn  19340:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   19341:             $captcha = 'original';
1.1094    raeburn  19342:         }
1.1327    raeburn  19343:     } elsif ($context eq 'passwords') {
                   19344:         if ($dom_in_effect) {
                   19345:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
                   19346:             if ($passwdconf{'captcha'} eq 'recaptcha') {
                   19347:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
                   19348:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
                   19349:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
                   19350:                 }
                   19351:                 if ($privkey && $pubkey) {
                   19352:                     $captcha = 'recaptcha';
                   19353:                     $version = $passwdconf{'recaptchaversion'};
                   19354:                     if ($version ne '2') {
                   19355:                         $version = 1;
                   19356:                     }
                   19357:                 } else {
                   19358:                     $captcha = 'original';
                   19359:                 }
                   19360:             } elsif ($passwdconf{'captcha'} ne 'notused') {
                   19361:                 $captcha = 'original';
                   19362:             }
                   19363:         }
                   19364:     } 
1.1234    raeburn  19365:     return ($captcha,$pubkey,$privkey,$version);
1.1094    raeburn  19366: }
                   19367: 
                   19368: sub create_captcha {
                   19369:     my %captcha_params = &captcha_settings();
                   19370:     my ($output,$maxtries,$tries) = ('',10,0);
                   19371:     while ($tries < $maxtries) {
                   19372:         $tries ++;
                   19373:         my $captcha = Authen::Captcha->new (
                   19374:                                            output_folder => $captcha_params{'output_dir'},
                   19375:                                            data_folder   => $captcha_params{'db_dir'},
                   19376:                                           );
                   19377:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   19378: 
                   19379:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   19380:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
1.1367    raeburn  19381:                       '<span class="LC_nobreak">'.
1.1094    raeburn  19382:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1390    raeburn  19383:                       '<input type="text" size="5" name="code" value="" autocomplete="new-password" />'.
1.1367    raeburn  19384:                       '</span><br />'.
1.1176    raeburn  19385:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  19386:             last;
                   19387:         }
                   19388:     }
1.1323    raeburn  19389:     if ($output eq '') {
                   19390:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
                   19391:     }
1.1094    raeburn  19392:     return $output;
                   19393: }
                   19394: 
                   19395: sub captcha_settings {
                   19396:     my %captcha_params = (
                   19397:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   19398:                            www_output_dir => "/captchaspool",
                   19399:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   19400:                            numchars       => '5',
                   19401:                          );
                   19402:     return %captcha_params;
                   19403: }
                   19404: 
                   19405: sub check_captcha {
                   19406:     my ($captcha_chk,$captcha_error);
                   19407:     my $code = $env{'form.code'};
                   19408:     my $md5sum = $env{'form.crypt'};
                   19409:     my %captcha_params = &captcha_settings();
                   19410:     my $captcha = Authen::Captcha->new(
                   19411:                       output_folder => $captcha_params{'output_dir'},
                   19412:                       data_folder   => $captcha_params{'db_dir'},
                   19413:                   );
1.1109    raeburn  19414:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  19415:     my %captcha_hash = (
                   19416:                         0       => 'Code not checked (file error)',
                   19417:                        -1      => 'Failed: code expired',
                   19418:                        -2      => 'Failed: invalid code (not in database)',
                   19419:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   19420:     );
                   19421:     if ($captcha_chk != 1) {
                   19422:         $captcha_error = $captcha_hash{$captcha_chk}
                   19423:     }
                   19424:     return ($captcha_chk,$captcha_error);
                   19425: }
                   19426: 
                   19427: sub create_recaptcha {
1.1234    raeburn  19428:     my ($pubkey,$version) = @_;
                   19429:     if ($version >= 2) {
1.1367    raeburn  19430:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
                   19431:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
1.1234    raeburn  19432:     } else {
                   19433:         my $use_ssl;
                   19434:         if ($ENV{'SERVER_PORT'} == 443) {
                   19435:             $use_ssl = 1;
                   19436:         }
                   19437:         my $captcha = Captcha::reCAPTCHA->new;
                   19438:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   19439:                $captcha->get_html($pubkey,undef,$use_ssl).
                   19440:                &mt('If the text is hard to read, [_1] will replace them.',
                   19441:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   19442:                '<br /><br />';
                   19443:     }
1.1094    raeburn  19444: }
                   19445: 
                   19446: sub check_recaptcha {
1.1234    raeburn  19447:     my ($privkey,$version) = @_;
1.1094    raeburn  19448:     my $captcha_chk;
1.1350    raeburn  19449:     my $ip = &Apache::lonnet::get_requestor_ip();
1.1234    raeburn  19450:     if ($version >= 2) {
                   19451:         my %info = (
                   19452:                      secret   => $privkey, 
                   19453:                      response => $env{'form.g-recaptcha-response'},
1.1350    raeburn  19454:                      remoteip => $ip,
1.1234    raeburn  19455:                    );
1.1280    raeburn  19456:         my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
                   19457:         $request->content(join('&',map {
                   19458:                          my $name = escape($_);
                   19459:                          "$name=" . ( ref($info{$_}) eq 'ARRAY'
                   19460:                          ? join("&$name=", map {escape($_) } @{$info{$_}})
                   19461:                          : &escape($info{$_}) );
                   19462:         } keys(%info)));
                   19463:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
1.1234    raeburn  19464:         if ($response->is_success)  {
                   19465:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   19466:             if (ref($data) eq 'HASH') {
                   19467:                 if ($data->{'success'}) {
                   19468:                     $captcha_chk = 1;
                   19469:                 }
                   19470:             }
                   19471:         }
                   19472:     } else {
                   19473:         my $captcha = Captcha::reCAPTCHA->new;
                   19474:         my $captcha_result =
                   19475:             $captcha->check_answer(
                   19476:                                     $privkey,
1.1350    raeburn  19477:                                     $ip,
1.1234    raeburn  19478:                                     $env{'form.recaptcha_challenge_field'},
                   19479:                                     $env{'form.recaptcha_response_field'},
                   19480:                                   );
                   19481:         if ($captcha_result->{is_valid}) {
                   19482:             $captcha_chk = 1;
                   19483:         }
1.1094    raeburn  19484:     }
                   19485:     return $captcha_chk;
                   19486: }
                   19487: 
1.1174    raeburn  19488: sub emailusername_info {
1.1244    raeburn  19489:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1174    raeburn  19490:     my %titles = &Apache::lonlocal::texthash (
                   19491:                      lastname      => 'Last Name',
                   19492:                      firstname     => 'First Name',
                   19493:                      institution   => 'School/college/university',
                   19494:                      location      => "School's city, state/province, country",
                   19495:                      web           => "School's web address",
                   19496:                      officialemail => 'E-mail address at institution (if different)',
1.1244    raeburn  19497:                      id            => 'Student/Employee ID',
1.1174    raeburn  19498:                  );
                   19499:     return (\@fields,\%titles);
                   19500: }
                   19501: 
1.1161    raeburn  19502: sub cleanup_html {
                   19503:     my ($incoming) = @_;
                   19504:     my $outgoing;
                   19505:     if ($incoming ne '') {
                   19506:         $outgoing = $incoming;
                   19507:         $outgoing =~ s/;/&#059;/g;
                   19508:         $outgoing =~ s/\#/&#035;/g;
                   19509:         $outgoing =~ s/\&/&#038;/g;
                   19510:         $outgoing =~ s/</&#060;/g;
                   19511:         $outgoing =~ s/>/&#062;/g;
                   19512:         $outgoing =~ s/\(/&#040/g;
                   19513:         $outgoing =~ s/\)/&#041;/g;
                   19514:         $outgoing =~ s/"/&#034;/g;
                   19515:         $outgoing =~ s/'/&#039;/g;
                   19516:         $outgoing =~ s/\$/&#036;/g;
                   19517:         $outgoing =~ s{/}{&#047;}g;
                   19518:         $outgoing =~ s/=/&#061;/g;
                   19519:         $outgoing =~ s/\\/&#092;/g
                   19520:     }
                   19521:     return $outgoing;
                   19522: }
                   19523: 
1.1190    musolffc 19524: # Checks for critical messages and returns a redirect url if one exists.
                   19525: # $interval indicates how often to check for messages.
1.1282    raeburn  19526: # $context is the calling context -- roles, grades, contents, menu or flip. 
1.1190    musolffc 19527: sub critical_redirect {
1.1282    raeburn  19528:     my ($interval,$context) = @_;
1.1356    raeburn  19529:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   19530:         return ();
                   19531:     }
1.1190    musolffc 19532:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
1.1282    raeburn  19533:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
                   19534:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   19535:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1372    raeburn  19536:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
1.1282    raeburn  19537:             if ($blocked) {
                   19538:                 my $checkrole = "cm./$cdom/$cnum";
                   19539:                 if ($env{'request.course.sec'} ne '') {
                   19540:                     $checkrole .= "/$env{'request.course.sec'}";
                   19541:                 }
                   19542:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   19543:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   19544:                     return;
                   19545:                 }
                   19546:             }
                   19547:         }
1.1190    musolffc 19548:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   19549:                                         $env{'user.name'});
                   19550:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  19551:         my $redirecturl;
1.1190    musolffc 19552:         if ($what[0]) {
1.1356    raeburn  19553: 	    if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
1.1190    musolffc 19554: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  19555: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   19556:                 return (1, $url);
1.1190    musolffc 19557:             }
1.1191    raeburn  19558:         }
                   19559:     } 
                   19560:     return ();
1.1190    musolffc 19561: }
                   19562: 
1.1174    raeburn  19563: # Use:
                   19564: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   19565: #
                   19566: ##################################################
                   19567: #          password associated functions         #
                   19568: ##################################################
                   19569: sub des_keys {
                   19570:     # Make a new key for DES encryption.
                   19571:     # Each key has two parts which are returned separately.
                   19572:     # Please note:  Each key must be passed through the &hex function
                   19573:     # before it is output to the web browser.  The hex versions cannot
                   19574:     # be used to decrypt.
                   19575:     my @hexstr=('0','1','2','3','4','5','6','7',
                   19576:                 '8','9','a','b','c','d','e','f');
                   19577:     my $lkey='';
                   19578:     for (0..7) {
                   19579:         $lkey.=$hexstr[rand(15)];
                   19580:     }
                   19581:     my $ukey='';
                   19582:     for (0..7) {
                   19583:         $ukey.=$hexstr[rand(15)];
                   19584:     }
                   19585:     return ($lkey,$ukey);
                   19586: }
                   19587: 
                   19588: sub des_decrypt {
                   19589:     my ($key,$cyphertext) = @_;
                   19590:     my $keybin=pack("H16",$key);
                   19591:     my $cypher;
                   19592:     if ($Crypt::DES::VERSION>=2.03) {
                   19593:         $cypher=new Crypt::DES $keybin;
                   19594:     } else {
                   19595:         $cypher=new DES $keybin;
                   19596:     }
1.1233    raeburn  19597:     my $plaintext='';
                   19598:     my $cypherlength = length($cyphertext);
                   19599:     my $numchunks = int($cypherlength/32);
                   19600:     for (my $j=0; $j<$numchunks; $j++) {
                   19601:         my $start = $j*32;
                   19602:         my $cypherblock = substr($cyphertext,$start,32);
                   19603:         my $chunk =
                   19604:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   19605:         $chunk .=
                   19606:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   19607:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   19608:         $plaintext .= $chunk;
                   19609:     }
1.1174    raeburn  19610:     return $plaintext;
                   19611: }
                   19612: 
1.1344    raeburn  19613: sub get_requested_shorturls {
1.1309    raeburn  19614:     my ($cdom,$cnum,$navmap) = @_;
                   19615:     return unless (ref($navmap));
1.1344    raeburn  19616:     my ($numnew,$errors);
1.1309    raeburn  19617:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
                   19618:     if (@toshorten) {
                   19619:         my (%maps,%resources,%titles);
                   19620:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
                   19621:                                                                'shorturls',$cdom,$cnum);
                   19622:         if (keys(%resources)) {
1.1344    raeburn  19623:             my %tocreate;
1.1309    raeburn  19624:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
                   19625:                 my $symb = $resources{$item};
                   19626:                 if ($symb) {
                   19627:                     $tocreate{$cnum.'&'.$symb} = 1;
                   19628:                 }
                   19629:             }
1.1344    raeburn  19630:             if (keys(%tocreate)) {
                   19631:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
                   19632:                                                       \%tocreate);
                   19633:             }
1.1309    raeburn  19634:         }
1.1344    raeburn  19635:     }
                   19636:     return ($numnew,$errors);
                   19637: }
                   19638: 
                   19639: sub make_short_symbs {
                   19640:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
                   19641:     my ($numnew,@errors);
                   19642:     if (ref($tocreateref) eq 'HASH') {
                   19643:         my %tocreate = %{$tocreateref};
1.1309    raeburn  19644:         if (keys(%tocreate)) {
                   19645:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
                   19646:             my $su = Short::URL->new(no_vowels => 1);
                   19647:             my $init = '';
                   19648:             my (%newunique,%addcourse,%courseonly,%failed);
                   19649:             # get lock on tiny db
                   19650:             my $now = time;
1.1344    raeburn  19651:             if ($lockuser eq '') {
                   19652:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
                   19653:             }
1.1309    raeburn  19654:             my $lockhash = {
1.1344    raeburn  19655:                                 "lock\0$now" => $lockuser,
1.1309    raeburn  19656:                             };
                   19657:             my $tries = 0;
                   19658:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
                   19659:             my ($code,$error);
                   19660:             while (($gotlock ne 'ok') && ($tries<3)) {
                   19661:                 $tries ++;
                   19662:                 sleep 1;
1.1319    raeburn  19663:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
1.1309    raeburn  19664:             }
                   19665:             if ($gotlock eq 'ok') {
                   19666:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
                   19667:                                        \%addcourse,\%courseonly,\%failed);
                   19668:                 if (keys(%failed)) {
                   19669:                     my $numfailed = scalar(keys(%failed));
                   19670:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
                   19671:                 }
                   19672:                 if (keys(%newunique)) {
                   19673:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
                   19674:                     if ($putres eq 'ok') {
                   19675:                         $numnew = scalar(keys(%newunique));
                   19676:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
                   19677:                         unless ($newputres eq 'ok') {
                   19678:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
                   19679:                         }
                   19680:                     } else {
                   19681:                         push(@errors,&mt('error: could not store unique six character URLs'));
                   19682:                     }
                   19683:                 }
                   19684:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
                   19685:                 unless ($dellockres eq 'ok') {
                   19686:                     push(@errors,&mt('error: could not release lockfile'));
                   19687:                 }
                   19688:             } else {
                   19689:                 push(@errors,&mt('error: could not obtain lockfile'));
                   19690:             }
                   19691:             if (keys(%courseonly)) {
                   19692:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
                   19693:                 if ($result ne 'ok') {
                   19694:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
                   19695:                 }
                   19696:             }
                   19697:         }
                   19698:     }
                   19699:     return ($numnew,\@errors);
                   19700: }
                   19701: 
                   19702: sub shorten_symbs {
                   19703:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
                   19704:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
                   19705:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
                   19706:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
                   19707:     my (%possibles,%collisions);
                   19708:     foreach my $key (keys(%{$tocreate})) {
                   19709:         my $num = String::CRC32::crc32($key);
                   19710:         my $tiny = $su->encode($num,$init);
                   19711:         if ($tiny) {
                   19712:             $possibles{$tiny} = $key;
                   19713:         }
                   19714:     }
                   19715:     if (!$init) {
                   19716:         $init = 1;
                   19717:     } else {
                   19718:         $init ++;
                   19719:     }
                   19720:     if (keys(%possibles)) {
                   19721:         my @posstiny = keys(%possibles);
                   19722:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
                   19723:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
                   19724:         if (keys(%currtiny)) {
                   19725:             foreach my $key (keys(%currtiny)) {
                   19726:                 next if ($currtiny{$key} eq '');
                   19727:                 if ($currtiny{$key} eq $possibles{$key}) {
                   19728:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
                   19729:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19730:                         $courseonly->{$tsymb} = $key;
                   19731:                     }
                   19732:                 } else {
                   19733:                     $collisions{$possibles{$key}} = 1;
                   19734:                 }
                   19735:                 delete($possibles{$key});
                   19736:             }
                   19737:         }
                   19738:         foreach my $key (keys(%possibles)) {
                   19739:             $newunique->{$key} = $possibles{$key};
                   19740:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
                   19741:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
                   19742:                 $addcourse->{$tsymb} = $key;
                   19743:             }
                   19744:         }
                   19745:     }
                   19746:     if (keys(%collisions)) {
                   19747:         if ($init <5) {
                   19748:             if (!$init) {
                   19749:                 $init = 1;
                   19750:             } else {
                   19751:                 $init ++;
                   19752:             }
                   19753:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
                   19754:                                    $newunique,$addcourse,$courseonly,$failed);
                   19755:         } else {
                   19756:             foreach my $key (keys(%collisions)) {
                   19757:                 $failed->{$key} = 1;
                   19758:             }
                   19759:         }
                   19760:     }
                   19761:     return $init;
                   19762: }
                   19763: 
1.1328    raeburn  19764: sub is_nonframeable {
1.1329    raeburn  19765:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
                   19766:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
1.1330    raeburn  19767:     return if (($remprotocol eq '') || ($remhost eq ''));
1.1329    raeburn  19768: 
                   19769:     $remprotocol = lc($remprotocol);
                   19770:     $remhost = lc($remhost);
                   19771:     my $remport = 80;
                   19772:     if ($remprotocol eq 'https') {
                   19773:         $remport = 443;
                   19774:     }
1.1330    raeburn  19775:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
1.1329    raeburn  19776:     if ($cached) {
                   19777:         unless ($nocache) {
                   19778:             if ($result) {
                   19779:                 return 1;
                   19780:             } else {
                   19781:                 return 0;
                   19782:             }
                   19783:         }
                   19784:     }
1.1328    raeburn  19785:     my $uselink;
                   19786:     my $request = new HTTP::Request('HEAD',$url);
                   19787:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
                   19788:     if ($response->is_success()) {
                   19789:         my $secpolicy = lc($response->header('content-security-policy'));
                   19790:         my $xframeop = lc($response->header('x-frame-options'));
                   19791:         $secpolicy =~ s/^\s+|\s+$//g;
                   19792:         $xframeop =~ s/^\s+|\s+$//g;
                   19793:         if (($secpolicy ne '') || ($xframeop ne '')) {
1.1329    raeburn  19794:             my $remotehost = $remprotocol.'://'.$remhost;
1.1328    raeburn  19795:             my ($origin,$protocol,$port);
                   19796:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
                   19797:                 $port = $ENV{'SERVER_PORT'};
                   19798:             } else {
                   19799:                 $port = 80;
                   19800:             }
                   19801:             if ($absolute eq '') {
                   19802:                 $protocol = 'http:';
                   19803:                 if ($port == 443) {
                   19804:                     $protocol = 'https:';
                   19805:                 }
                   19806:                 $origin = $protocol.'//'.lc($hostname);
                   19807:             } else {
                   19808:                 $origin = lc($absolute);
                   19809:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
                   19810:             }
                   19811:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
                   19812:                 my $framepolicy = $1;
                   19813:                 $framepolicy =~ s/^\s+|\s+$//g;
                   19814:                 my @policies = split(/\s+/,$framepolicy);
                   19815:                 if (@policies) {
                   19816:                     if (grep(/^\Q'none'\E$/,@policies)) {
                   19817:                         $uselink = 1;
                   19818:                     } else {
                   19819:                         $uselink = 1;
                   19820:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
                   19821:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
                   19822:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
                   19823:                             undef($uselink);
                   19824:                         }
                   19825:                         if ($uselink) {
                   19826:                             if (grep(/^\Q'self'\E$/,@policies)) {
                   19827:                                 if (($origin ne '') && ($remotehost eq $origin)) {
                   19828:                                     undef($uselink);
                   19829:                                 }
                   19830:                             }
                   19831:                         }
                   19832:                         if ($uselink) {
                   19833:                             my @possok;
                   19834:                             if ($ip ne '') {
                   19835:                                 push(@possok,$ip);
                   19836:                             }
                   19837:                             my $hoststr = '';
                   19838:                             foreach my $part (reverse(split(/\./,$hostname))) {
                   19839:                                 if ($hoststr eq '') {
                   19840:                                     $hoststr = $part;
                   19841:                                 } else {
                   19842:                                     $hoststr = "$part.$hoststr";
                   19843:                                 }
                   19844:                                 if ($hoststr eq $hostname) {
                   19845:                                     push(@possok,$hostname);
                   19846:                                 } else {
                   19847:                                     push(@possok,"*.$hoststr");
                   19848:                                 }
                   19849:                             }
                   19850:                             if (@possok) {
                   19851:                                 foreach my $poss (@possok) {
                   19852:                                     last if (!$uselink);
                   19853:                                     foreach my $policy (@policies) {
                   19854:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
                   19855:                                             undef($uselink);
                   19856:                                             last;
                   19857:                                         }
                   19858:                                     }
                   19859:                                 }
                   19860:                             }
                   19861:                         }
                   19862:                     }
                   19863:                 }
                   19864:             } elsif ($xframeop ne '') {
                   19865:                 $uselink = 1;
                   19866:                 my @policies = split(/\s*,\s*/,$xframeop);
                   19867:                 if (@policies) {
                   19868:                     unless (grep(/^deny$/,@policies)) {
                   19869:                         if ($origin ne '') {
                   19870:                             if (grep(/^sameorigin$/,@policies)) {
                   19871:                                 if ($remotehost eq $origin) {
                   19872:                                     undef($uselink);
                   19873:                                 }
                   19874:                             }
                   19875:                             if ($uselink) {
                   19876:                                 foreach my $policy (@policies) {
                   19877:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
                   19878:                                         my $allowfrom = $1;
                   19879:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
                   19880:                                             undef($uselink);
                   19881:                                             last;
                   19882:                                         }
                   19883:                                     }
                   19884:                                 }
                   19885:                             }
                   19886:                         }
                   19887:                     }
                   19888:                 }
                   19889:             }
                   19890:         }
                   19891:     }
1.1329    raeburn  19892:     if ($nocache) {
                   19893:         if ($cached) {
                   19894:             my $devalidate;
                   19895:             if ($uselink && !$result) {
                   19896:                 $devalidate = 1;
                   19897:             } elsif (!$uselink && $result) {
                   19898:                 $devalidate = 1;
                   19899:             }
                   19900:             if ($devalidate) {
                   19901:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
                   19902:             }
                   19903:         }
                   19904:     } else {
                   19905:         if ($uselink) {
                   19906:             $result = 1;
                   19907:         } else {
                   19908:             $result = 0;
                   19909:         }
                   19910:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
                   19911:     }
1.1328    raeburn  19912:     return $uselink;
                   19913: }
                   19914: 
1.1359    raeburn  19915: sub page_menu {
                   19916:     my ($menucolls,$menunum) = @_;
                   19917:     my %menu;
                   19918:     foreach my $item (split(/;/,$menucolls)) {
                   19919:         my ($num,$value) = split(/\%/,$item);
                   19920:         if ($num eq $menunum) {
                   19921:             my @entries = split(/\&/,$value);
                   19922:             foreach my $entry (@entries) {
                   19923:                 my ($name,$fields) = split(/=/,$entry);
1.1368    raeburn  19924:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
1.1359    raeburn  19925:                     $menu{$name} = $fields;
                   19926:                 } else {
                   19927:                     my @shown;
                   19928:                     if ($fields =~ /,/) {
                   19929:                         @shown = split(/,/,$fields);
                   19930:                     } else {
                   19931:                         @shown = ($fields);
                   19932:                     }
                   19933:                     if (@shown) {
                   19934:                         foreach my $field (@shown) {
                   19935:                             next if ($field eq '');
                   19936:                             $menu{$field} = 1;
                   19937:                         }
                   19938:                     }
                   19939:                 }
                   19940:             }
                   19941:         }
                   19942:     }
                   19943:     return %menu;
                   19944: }
                   19945: 
1.112     bowersj2 19946: 1;
                   19947: __END__;
1.41      ng       19948: 

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