![]() ![]() | ![]() |
- Localization - wrong index in &mt() call.
1: # The LearningOnline Network with CAPA 2: # a pile of common routines 3: # 4: # $Id: loncommon.pm,v 1.1103 2012/12/17 17:45:32 raeburn Exp $ 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: # 28: 29: # Makes a table out of the previous attempts 30: # Inputs result_from_symbread, user, domain, course_id 31: # Reads in non-network-related .tab files 32: 33: # POD header: 34: 35: =pod 36: 37: =head1 NAME 38: 39: Apache::loncommon - pile of common routines 40: 41: =head1 SYNOPSIS 42: 43: Common routines for manipulating connections, student answers, 44: domains, common Javascript fragments, etc. 45: 46: =head1 OVERVIEW 47: 48: A collection of commonly used subroutines that don't have a natural 49: home anywhere else. This collection helps remove 50: redundancy from other modules and increase efficiency of memory usage. 51: 52: =cut 53: 54: # End of POD header 55: package Apache::loncommon; 56: 57: use strict; 58: use Apache::lonnet; 59: use GDBM_File; 60: use POSIX qw(strftime mktime); 61: use Apache::lonmenu(); 62: use Apache::lonenc(); 63: use Apache::lonlocal; 64: use Apache::lonnet(); 65: use HTML::Entities; 66: use Apache::lonhtmlcommon(); 67: use Apache::loncoursedata(); 68: use Apache::lontexconvert(); 69: use Apache::lonclonecourse(); 70: use LONCAPA qw(:DEFAULT :match); 71: use DateTime::TimeZone; 72: use DateTime::Locale::Catalog; 73: use Text::Aspell; 74: use Authen::Captcha; 75: use Captcha::reCAPTCHA; 76: 77: # ---------------------------------------------- Designs 78: use vars qw(%defaultdesign); 79: 80: my $readit; 81: 82: 83: ## 84: ## Global Variables 85: ## 86: 87: 88: # ----------------------------------------------- SSI with retries: 89: # 90: 91: =pod 92: 93: =head1 Server Side include with retries: 94: 95: =over 4 96: 97: =item * &ssi_with_retries(resource,retries form) 98: 99: Performs an ssi with some number of retries. Retries continue either 100: until the result is ok or until the retry count supplied by the 101: caller is exhausted. 102: 103: Inputs: 104: 105: =over 4 106: 107: resource - Identifies the resource to insert. 108: 109: retries - Count of the number of retries allowed. 110: 111: form - Hash that identifies the rendering options. 112: 113: =back 114: 115: Returns: 116: 117: =over 4 118: 119: content - The content of the response. If retries were exhausted this is empty. 120: 121: response - The response from the last attempt (which may or may not have been successful. 122: 123: =back 124: 125: =back 126: 127: =cut 128: 129: sub ssi_with_retries { 130: my ($resource, $retries, %form) = @_; 131: 132: 133: my $ok = 0; # True if we got a good response. 134: my $content; 135: my $response; 136: 137: # Try to get the ssi done. within the retries count: 138: 139: do { 140: ($content, $response) = &Apache::lonnet::ssi($resource, %form); 141: $ok = $response->is_success; 142: if (!$ok) { 143: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message); 144: } 145: $retries--; 146: } while (!$ok && ($retries > 0)); 147: 148: if (!$ok) { 149: $content = ''; # On error return an empty content. 150: } 151: return ($content, $response); 152: 153: } 154: 155: 156: 157: # ----------------------------------------------- Filetypes/Languages/Copyright 158: my %language; 159: my %supported_language; 160: my %supported_codes; 161: my %latex_language; # For choosing hyphenation in <transl..> 162: my %latex_language_bykey; # for choosing hyphenation from metadata 163: my %cprtag; 164: my %scprtag; 165: my %fe; my %fd; my %fm; 166: my %category_extensions; 167: 168: # ---------------------------------------------- Thesaurus variables 169: # 170: # %Keywords: 171: # A hash used by &keyword to determine if a word is considered a keyword. 172: # $thesaurus_db_file 173: # Scalar containing the full path to the thesaurus database. 174: 175: my %Keywords; 176: my $thesaurus_db_file; 177: 178: # 179: # Initialize values from language.tab, copyright.tab, filetypes.tab, 180: # thesaurus.tab, and filecategories.tab. 181: # 182: BEGIN { 183: # Variable initialization 184: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db"; 185: # 186: unless ($readit) { 187: # ------------------------------------------------------------------- languages 188: { 189: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}. 190: '/language.tab'; 191: if ( open(my $fh,"<$langtabfile") ) { 192: while (my $line = <$fh>) { 193: next if ($line=~/^\#/); 194: chomp($line); 195: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line)); 196: $language{$key}=$val.' - '.$enc; 197: if ($sup) { 198: $supported_language{$key}=$sup; 199: $supported_codes{$key} = $code; 200: } 201: if ($latex) { 202: $latex_language_bykey{$key} = $latex; 203: $latex_language{$code} = $latex; 204: } 205: } 206: close($fh); 207: } 208: } 209: # ------------------------------------------------------------------ copyrights 210: { 211: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}. 212: '/copyright.tab'; 213: if ( open (my $fh,"<$copyrightfile") ) { 214: while (my $line = <$fh>) { 215: next if ($line=~/^\#/); 216: chomp($line); 217: my ($key,$val)=(split(/\s+/,$line,2)); 218: $cprtag{$key}=$val; 219: } 220: close($fh); 221: } 222: } 223: # ----------------------------------------------------------- source copyrights 224: { 225: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}. 226: '/source_copyright.tab'; 227: if ( open (my $fh,"<$sourcecopyrightfile") ) { 228: while (my $line = <$fh>) { 229: next if ($line =~ /^\#/); 230: chomp($line); 231: my ($key,$val)=(split(/\s+/,$line,2)); 232: $scprtag{$key}=$val; 233: } 234: close($fh); 235: } 236: } 237: 238: # -------------------------------------------------------------- default domain designs 239: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; 240: my $designfile = $designdir.'/default.tab'; 241: if ( open (my $fh,"<$designfile") ) { 242: while (my $line = <$fh>) { 243: next if ($line =~ /^\#/); 244: chomp($line); 245: my ($key,$val)=(split(/\=/,$line)); 246: if ($val) { $defaultdesign{$key}=$val; } 247: } 248: close($fh); 249: } 250: 251: # ------------------------------------------------------------- file categories 252: { 253: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}. 254: '/filecategories.tab'; 255: if ( open (my $fh,"<$categoryfile") ) { 256: while (my $line = <$fh>) { 257: next if ($line =~ /^\#/); 258: chomp($line); 259: my ($extension,$category)=(split(/\s+/,$line,2)); 260: push @{$category_extensions{lc($category)}},$extension; 261: } 262: close($fh); 263: } 264: 265: } 266: # ------------------------------------------------------------------ file types 267: { 268: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}. 269: '/filetypes.tab'; 270: if ( open (my $fh,"<$typesfile") ) { 271: while (my $line = <$fh>) { 272: next if ($line =~ /^\#/); 273: chomp($line); 274: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4); 275: if ($descr ne '') { 276: $fe{$ending}=lc($emb); 277: $fd{$ending}=$descr; 278: if ($mime ne 'unk') { $fm{$ending}=$mime; } 279: } 280: } 281: close($fh); 282: } 283: } 284: &Apache::lonnet::logthis( 285: "<span style='color:yellow;'>INFO: Read file types</span>"); 286: $readit=1; 287: } # end of unless($readit) 288: 289: } 290: 291: ############################################################### 292: ## HTML and Javascript Helper Functions ## 293: ############################################################### 294: 295: =pod 296: 297: =head1 HTML and Javascript Functions 298: 299: =over 4 300: 301: =item * &browser_and_searcher_javascript() 302: 303: X<browsing, javascript>X<searching, javascript>Returns a string 304: containing javascript with two functions, C<openbrowser> and 305: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt> 306: tags. 307: 308: =item * &openbrowser(formname,elementname,only,omit) [javascript] 309: 310: inputs: formname, elementname, only, omit 311: 312: formname and elementname indicate the name of the html form and name of 313: the element that the results of the browsing selection are to be placed in. 314: 315: Specifying 'only' will restrict the browser to displaying only files 316: with the given extension. Can be a comma separated list. 317: 318: Specifying 'omit' will restrict the browser to NOT displaying files 319: with the given extension. Can be a comma separated list. 320: 321: =item * &opensearcher(formname,elementname) [javascript] 322: 323: Inputs: formname, elementname 324: 325: formname and elementname specify the name of the html form and the name 326: of the element the selection from the search results will be placed in. 327: 328: =cut 329: 330: sub browser_and_searcher_javascript { 331: my ($mode)=@_; 332: if (!defined($mode)) { $mode='edit'; } 333: my $resurl=&escape_single(&lastresurl()); 334: return <<END; 335: // <!-- BEGIN LON-CAPA Internal 336: var editbrowser = null; 337: function openbrowser(formname,elementname,only,omit,titleelement) { 338: var url = '$resurl/?'; 339: if (editbrowser == null) { 340: url += 'launch=1&'; 341: } 342: url += 'catalogmode=interactive&'; 343: url += 'mode=$mode&'; 344: url += 'inhibitmenu=yes&'; 345: url += 'form=' + formname + '&'; 346: if (only != null) { 347: url += 'only=' + only + '&'; 348: } else { 349: url += 'only=&'; 350: } 351: if (omit != null) { 352: url += 'omit=' + omit + '&'; 353: } else { 354: url += 'omit=&'; 355: } 356: if (titleelement != null) { 357: url += 'titleelement=' + titleelement + '&'; 358: } else { 359: url += 'titleelement=&'; 360: } 361: url += 'element=' + elementname + ''; 362: var title = 'Browser'; 363: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1'; 364: options += ',width=700,height=600'; 365: editbrowser = open(url,title,options,'1'); 366: editbrowser.focus(); 367: } 368: var editsearcher; 369: function opensearcher(formname,elementname,titleelement) { 370: var url = '/adm/searchcat?'; 371: if (editsearcher == null) { 372: url += 'launch=1&'; 373: } 374: url += 'catalogmode=interactive&'; 375: url += 'mode=$mode&'; 376: url += 'form=' + formname + '&'; 377: if (titleelement != null) { 378: url += 'titleelement=' + titleelement + '&'; 379: } else { 380: url += 'titleelement=&'; 381: } 382: url += 'element=' + elementname + ''; 383: var title = 'Search'; 384: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1'; 385: options += ',width=700,height=600'; 386: editsearcher = open(url,title,options,'1'); 387: editsearcher.focus(); 388: } 389: // END LON-CAPA Internal --> 390: END 391: } 392: 393: sub lastresurl { 394: if ($env{'environment.lastresurl'}) { 395: return $env{'environment.lastresurl'} 396: } else { 397: return '/res'; 398: } 399: } 400: 401: sub storeresurl { 402: my $resurl=&Apache::lonnet::clutter(shift); 403: unless ($resurl=~/^\/res/) { return 0; } 404: $resurl=~s/\/$//; 405: &Apache::lonnet::put('environment',{'lastresurl' => $resurl}); 406: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl}); 407: return 1; 408: } 409: 410: sub studentbrowser_javascript { 411: unless ( 412: (($env{'request.course.id'}) && 413: (&Apache::lonnet::allowed('srm',$env{'request.course.id'}) 414: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}. 415: '/'.$env{'request.course.sec'}) 416: )) 417: || ($env{'request.role'}=~/^(au|dc|su)/) 418: ) { return ''; } 419: return (<<'ENDSTDBRW'); 420: <script type="text/javascript" language="Javascript"> 421: // <![CDATA[ 422: var stdeditbrowser; 423: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) { 424: var url = '/adm/pickstudent?'; 425: var filter; 426: if (!ignorefilter) { 427: eval('filter=document.'+formname+'.'+uname+'.value;'); 428: } 429: if (filter != null) { 430: if (filter != '') { 431: url += 'filter='+filter+'&'; 432: } 433: } 434: url += 'form=' + formname + '&unameelement='+uname+ 435: '&udomelement='+udom+ 436: '&clicker='+clicker; 437: if (roleflag) { url+="&roles=1"; } 438: if (courseadvonly) { url+="&courseadvonly=1"; } 439: var title = 'Student_Browser'; 440: var options = 'scrollbars=1,resizable=1,menubar=0'; 441: options += ',width=700,height=600'; 442: stdeditbrowser = open(url,title,options,'1'); 443: stdeditbrowser.focus(); 444: } 445: // ]]> 446: </script> 447: ENDSTDBRW 448: } 449: 450: sub resourcebrowser_javascript { 451: unless ($env{'request.course.id'}) { return ''; } 452: return (<<'ENDRESBRW'); 453: <script type="text/javascript" language="Javascript"> 454: // <![CDATA[ 455: var reseditbrowser; 456: function openresbrowser(formname,reslink) { 457: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink; 458: var title = 'Resource_Browser'; 459: var options = 'scrollbars=1,resizable=1,menubar=0'; 460: options += ',width=700,height=500'; 461: reseditbrowser = open(url,title,options,'1'); 462: reseditbrowser.focus(); 463: } 464: // ]]> 465: </script> 466: ENDRESBRW 467: } 468: 469: sub selectstudent_link { 470: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_; 471: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". 472: &Apache::lonhtmlcommon::entity_encode($unameele)."','". 473: &Apache::lonhtmlcommon::entity_encode($udomele)."'"; 474: if ($env{'request.course.id'}) { 475: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'}) 476: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}. 477: '/'.$env{'request.course.sec'})) { 478: return ''; 479: } 480: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'"; 481: if ($courseadvonly) { 482: $callargs .= ",'',1,1"; 483: } 484: return '<span class="LC_nobreak">'. 485: '<a href="javascript:openstdbrowser('.$callargs.');">'. 486: &mt('Select User').'</a></span>'; 487: } 488: if ($env{'request.role'}=~/^(au|dc|su)/) { 489: $callargs .= ",'',1"; 490: return '<span class="LC_nobreak">'. 491: '<a href="javascript:openstdbrowser('.$callargs.');">'. 492: &mt('Select User').'</a></span>'; 493: } 494: return ''; 495: } 496: 497: sub selectresource_link { 498: my ($form,$reslink,$arg)=@_; 499: 500: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','". 501: &Apache::lonhtmlcommon::entity_encode($reslink)."'"; 502: unless ($env{'request.course.id'}) { return $arg; } 503: return '<span class="LC_nobreak">'. 504: '<a href="javascript:openresbrowser('.$callargs.');">'. 505: $arg.'</a></span>'; 506: } 507: 508: 509: 510: sub authorbrowser_javascript { 511: return <<"ENDAUTHORBRW"; 512: <script type="text/javascript" language="JavaScript"> 513: // <![CDATA[ 514: var stdeditbrowser; 515: 516: function openauthorbrowser(formname,udom) { 517: var url = '/adm/pickauthor?'; 518: url += 'form='+formname+'&roledom='+udom; 519: var title = 'Author_Browser'; 520: var options = 'scrollbars=1,resizable=1,menubar=0'; 521: options += ',width=700,height=600'; 522: stdeditbrowser = open(url,title,options,'1'); 523: stdeditbrowser.focus(); 524: } 525: 526: // ]]> 527: </script> 528: ENDAUTHORBRW 529: } 530: 531: sub coursebrowser_javascript { 532: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_; 533: my $wintitle = 'Course_Browser'; 534: if ($crstype eq 'Community') { 535: $wintitle = 'Community_Browser'; 536: } 537: my $id_functions = &javascript_index_functions(); 538: my $output = ' 539: <script type="text/javascript" language="JavaScript"> 540: // <![CDATA[ 541: var stdeditbrowser;'."\n"; 542: 543: $output .= <<"ENDSTDBRW"; 544: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) { 545: var url = '/adm/pickcourse?'; 546: var formid = getFormIdByName(formname); 547: var domainfilter = getDomainFromSelectbox(formname,udom); 548: if (domainfilter != null) { 549: if (domainfilter != '') { 550: url += 'domainfilter='+domainfilter+'&'; 551: } 552: } 553: url += 'form=' + formname + '&cnumelement='+uname+ 554: '&cdomelement='+udom+ 555: '&cnameelement='+desc; 556: if (extra_element !=null && extra_element != '') { 557: if (formname == 'rolechoice' || formname == 'studentform') { 558: url += '&roleelement='+extra_element; 559: if (domainfilter == null || domainfilter == '') { 560: url += '&domainfilter='+extra_element; 561: } 562: } 563: else { 564: if (formname == 'portform') { 565: url += '&setroles='+extra_element; 566: } else { 567: if (formname == 'rules') { 568: url += '&fixeddom='+extra_element; 569: } 570: } 571: } 572: } 573: if (type != null && type != '') { 574: url += '&type='+type; 575: } 576: if (type_elem != null && type_elem != '') { 577: url += '&typeelement='+type_elem; 578: } 579: if (formname == 'ccrs') { 580: var ownername = document.forms[formid].ccuname.value; 581: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value; 582: url += '&cloner='+ownername+':'+ownerdom; 583: } 584: if (multflag !=null && multflag != '') { 585: url += '&multiple='+multflag; 586: } 587: var title = '$wintitle'; 588: var options = 'scrollbars=1,resizable=1,menubar=0'; 589: options += ',width=700,height=600'; 590: stdeditbrowser = open(url,title,options,'1'); 591: stdeditbrowser.focus(); 592: } 593: $id_functions 594: ENDSTDBRW 595: if (($sec_element ne '') || ($role_element ne '')) { 596: $output .= &setsec_javascript($sec_element,$formname,$role_element); 597: } 598: $output .= ' 599: // ]]> 600: </script>'; 601: return $output; 602: } 603: 604: sub javascript_index_functions { 605: return <<"ENDJS"; 606: 607: function getFormIdByName(formname) { 608: for (var i=0;i<document.forms.length;i++) { 609: if (document.forms[i].name == formname) { 610: return i; 611: } 612: } 613: return -1; 614: } 615: 616: function getIndexByName(formid,item) { 617: for (var i=0;i<document.forms[formid].elements.length;i++) { 618: if (document.forms[formid].elements[i].name == item) { 619: return i; 620: } 621: } 622: return -1; 623: } 624: 625: function getDomainFromSelectbox(formname,udom) { 626: var userdom; 627: var formid = getFormIdByName(formname); 628: if (formid > -1) { 629: var domid = getIndexByName(formid,udom); 630: if (domid > -1) { 631: if (document.forms[formid].elements[domid].type == 'select-one') { 632: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value; 633: } 634: if (document.forms[formid].elements[domid].type == 'hidden') { 635: userdom=document.forms[formid].elements[domid].value; 636: } 637: } 638: } 639: return userdom; 640: } 641: 642: ENDJS 643: 644: } 645: 646: sub javascript_array_indexof { 647: return <<ENDJS; 648: <script type="text/javascript" language="JavaScript"> 649: // <![CDATA[ 650: 651: if (!Array.prototype.indexOf) { 652: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { 653: "use strict"; 654: if (this === void 0 || this === null) { 655: throw new TypeError(); 656: } 657: var t = Object(this); 658: var len = t.length >>> 0; 659: if (len === 0) { 660: return -1; 661: } 662: var n = 0; 663: if (arguments.length > 0) { 664: n = Number(arguments[1]); 665: if (n !== n) { // shortcut for verifying if it is NaN 666: n = 0; 667: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { 668: n = (n > 0 || -1) * Math.floor(Math.abs(n)); 669: } 670: } 671: if (n >= len) { 672: return -1; 673: } 674: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); 675: for (; k < len; k++) { 676: if (k in t && t[k] === searchElement) { 677: return k; 678: } 679: } 680: return -1; 681: } 682: } 683: 684: // ]]> 685: </script> 686: 687: ENDJS 688: 689: } 690: 691: sub userbrowser_javascript { 692: my $id_functions = &javascript_index_functions(); 693: return <<"ENDUSERBRW"; 694: 695: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) { 696: var url = '/adm/pickuser?'; 697: var userdom = getDomainFromSelectbox(formname,udom); 698: if (userdom != null) { 699: if (userdom != '') { 700: url += 'srchdom='+userdom+'&'; 701: } 702: } 703: url += 'form=' + formname + '&unameelement='+uname+ 704: '&udomelement='+udom+ 705: '&ulastelement='+ulast+ 706: '&ufirstelement='+ufirst+ 707: '&uemailelement='+uemail+ 708: '&hideudomelement='+hideudom+ 709: '&coursedom='+crsdom; 710: if ((caller != null) && (caller != undefined)) { 711: url += '&caller='+caller; 712: } 713: var title = 'User_Browser'; 714: var options = 'scrollbars=1,resizable=1,menubar=0'; 715: options += ',width=700,height=600'; 716: var stdeditbrowser = open(url,title,options,'1'); 717: stdeditbrowser.focus(); 718: } 719: 720: function fix_domain (formname,udom,origdom,uname) { 721: var formid = getFormIdByName(formname); 722: if (formid > -1) { 723: var unameid = getIndexByName(formid,uname); 724: var domid = getIndexByName(formid,udom); 725: var hidedomid = getIndexByName(formid,origdom); 726: if (hidedomid > -1) { 727: var fixeddom = document.forms[formid].elements[hidedomid].value; 728: var unameval = document.forms[formid].elements[unameid].value; 729: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) { 730: if (domid > -1) { 731: var slct = document.forms[formid].elements[domid]; 732: if (slct.type == 'select-one') { 733: var i; 734: for (i=0;i<slct.length;i++) { 735: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; } 736: } 737: } 738: if (slct.type == 'hidden') { 739: slct.value = fixeddom; 740: } 741: } 742: } 743: } 744: } 745: return; 746: } 747: 748: $id_functions 749: ENDUSERBRW 750: } 751: 752: sub setsec_javascript { 753: my ($sec_element,$formname,$role_element) = @_; 754: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr, 755: $communityrolestr); 756: if ($role_element ne '') { 757: my @allroles = ('st','ta','ep','in','ad'); 758: foreach my $crstype ('Course','Community') { 759: if ($crstype eq 'Community') { 760: foreach my $role (@allroles) { 761: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype)); 762: } 763: push(@communityrolenames,&Apache::lonnet::plaintext('co')); 764: } else { 765: foreach my $role (@allroles) { 766: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype)); 767: } 768: push(@courserolenames,&Apache::lonnet::plaintext('cc')); 769: } 770: } 771: $rolestr = '"'.join('","',@allroles).'"'; 772: $courserolestr = '"'.join('","',@courserolenames).'"'; 773: $communityrolestr = '"'.join('","',@communityrolenames).'"'; 774: } 775: my $setsections = qq| 776: function setSect(sectionlist) { 777: var sectionsArray = new Array(); 778: if ((sectionlist != '') && (typeof sectionlist != "undefined")) { 779: sectionsArray = sectionlist.split(","); 780: } 781: var numSections = sectionsArray.length; 782: document.$formname.$sec_element.length = 0; 783: if (numSections == 0) { 784: document.$formname.$sec_element.multiple=false; 785: document.$formname.$sec_element.size=1; 786: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false) 787: } else { 788: if (numSections == 1) { 789: document.$formname.$sec_element.multiple=false; 790: document.$formname.$sec_element.size=1; 791: document.$formname.$sec_element.options[0] = new Option('Select','',true,true); 792: document.$formname.$sec_element.options[1] = new Option('No section','',false,false) 793: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false); 794: } else { 795: for (var i=0; i<numSections; i++) { 796: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false) 797: } 798: document.$formname.$sec_element.multiple=true 799: if (numSections < 3) { 800: document.$formname.$sec_element.size=numSections; 801: } else { 802: document.$formname.$sec_element.size=3; 803: } 804: document.$formname.$sec_element.options[0].selected = false 805: } 806: } 807: } 808: 809: function setRole(crstype) { 810: |; 811: if ($role_element eq '') { 812: $setsections .= ' return; 813: } 814: '; 815: } else { 816: $setsections .= qq| 817: var elementLength = document.$formname.$role_element.length; 818: var allroles = Array($rolestr); 819: var courserolenames = Array($courserolestr); 820: var communityrolenames = Array($communityrolestr); 821: if (elementLength != undefined) { 822: if (document.$formname.$role_element.options[5].value == 'cc') { 823: if (crstype == 'Course') { 824: return; 825: } else { 826: allroles[5] = 'co'; 827: for (var i=0; i<6; i++) { 828: document.$formname.$role_element.options[i].value = allroles[i]; 829: document.$formname.$role_element.options[i].text = communityrolenames[i]; 830: } 831: } 832: } else { 833: if (crstype == 'Community') { 834: return; 835: } else { 836: allroles[5] = 'cc'; 837: for (var i=0; i<6; i++) { 838: document.$formname.$role_element.options[i].value = allroles[i]; 839: document.$formname.$role_element.options[i].text = courserolenames[i]; 840: } 841: } 842: } 843: } 844: return; 845: } 846: |; 847: } 848: return $setsections; 849: } 850: 851: sub selectcourse_link { 852: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype, 853: $typeelement) = @_; 854: my $type = $selecttype; 855: my $linktext = &mt('Select Course'); 856: if ($selecttype eq 'Community') { 857: $linktext = &mt('Select Community'); 858: } elsif ($selecttype eq 'Course/Community') { 859: $linktext = &mt('Select Course/Community'); 860: $type = ''; 861: } elsif ($selecttype eq 'Select') { 862: $linktext = &mt('Select'); 863: $type = ''; 864: } 865: return '<span class="LC_nobreak">' 866: ."<a href='" 867: .'javascript:opencrsbrowser("'.$form.'","'.$unameele 868: .'","'.$udomele.'","'.$desc.'","'.$extra_element 869: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");' 870: ."'>".$linktext.'</a>' 871: .'</span>'; 872: } 873: 874: sub selectauthor_link { 875: my ($form,$udom)=@_; 876: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'. 877: &mt('Select Author').'</a>'; 878: } 879: 880: sub selectuser_link { 881: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem, 882: $coursedom,$linktext,$caller) = @_; 883: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',". 884: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'". 885: ');">'.$linktext.'</a>'; 886: } 887: 888: sub check_uncheck_jscript { 889: my $jscript = <<"ENDSCRT"; 890: function checkAll(field) { 891: if (field.length > 0) { 892: for (i = 0; i < field.length; i++) { 893: if (!field[i].disabled) { 894: field[i].checked = true; 895: } 896: } 897: } else { 898: if (!field.disabled) { 899: field.checked = true; 900: } 901: } 902: } 903: 904: function uncheckAll(field) { 905: if (field.length > 0) { 906: for (i = 0; i < field.length; i++) { 907: field[i].checked = false ; 908: } 909: } else { 910: field.checked = false ; 911: } 912: } 913: ENDSCRT 914: return $jscript; 915: } 916: 917: sub select_timezone { 918: my ($name,$selected,$onchange,$includeempty)=@_; 919: my $output='<select name="'.$name.'" '.$onchange.'>'."\n"; 920: if ($includeempty) { 921: $output .= '<option value=""'; 922: if (($selected eq '') || ($selected eq 'local')) { 923: $output .= ' selected="selected" '; 924: } 925: $output .= '> </option>'; 926: } 927: my @timezones = DateTime::TimeZone->all_names; 928: foreach my $tzone (@timezones) { 929: $output.= '<option value="'.$tzone.'"'; 930: if ($tzone eq $selected) { 931: $output.=' selected="selected"'; 932: } 933: $output.=">$tzone</option>\n"; 934: } 935: $output.="</select>"; 936: return $output; 937: } 938: 939: sub select_datelocale { 940: my ($name,$selected,$onchange,$includeempty)=@_; 941: my $output='<select name="'.$name.'" '.$onchange.'>'."\n"; 942: if ($includeempty) { 943: $output .= '<option value=""'; 944: if ($selected eq '') { 945: $output .= ' selected="selected" '; 946: } 947: $output .= '> </option>'; 948: } 949: my (@possibles,%locale_names); 950: my @locales = DateTime::Locale::Catalog::Locales; 951: foreach my $locale (@locales) { 952: if (ref($locale) eq 'HASH') { 953: my $id = $locale->{'id'}; 954: if ($id ne '') { 955: my $en_terr = $locale->{'en_territory'}; 956: my $native_terr = $locale->{'native_territory'}; 957: my @languages = &Apache::lonlocal::preferred_languages(); 958: if (grep(/^en$/,@languages) || !@languages) { 959: if ($en_terr ne '') { 960: $locale_names{$id} = '('.$en_terr.')'; 961: } elsif ($native_terr ne '') { 962: $locale_names{$id} = $native_terr; 963: } 964: } else { 965: if ($native_terr ne '') { 966: $locale_names{$id} = $native_terr.' '; 967: } elsif ($en_terr ne '') { 968: $locale_names{$id} = '('.$en_terr.')'; 969: } 970: } 971: push (@possibles,$id); 972: } 973: } 974: } 975: foreach my $item (sort(@possibles)) { 976: $output.= '<option value="'.$item.'"'; 977: if ($item eq $selected) { 978: $output.=' selected="selected"'; 979: } 980: $output.=">$item"; 981: if ($locale_names{$item} ne '') { 982: $output.=" $locale_names{$item}</option>\n"; 983: } 984: $output.="</option>\n"; 985: } 986: $output.="</select>"; 987: return $output; 988: } 989: 990: sub select_language { 991: my ($name,$selected,$includeempty) = @_; 992: my %langchoices; 993: if ($includeempty) { 994: %langchoices = ('' => 'No language preference'); 995: } 996: foreach my $id (&languageids()) { 997: my $code = &supportedlanguagecode($id); 998: if ($code) { 999: $langchoices{$code} = &plainlanguagedescription($id); 1000: } 1001: } 1002: return &select_form($selected,$name,\%langchoices); 1003: } 1004: 1005: =pod 1006: 1007: 1008: =item * &list_languages() 1009: 1010: Returns an array reference that is suitable for use in language prompters. 1011: Each array element is itself a two element array. The first element 1012: is the language code. The second element a descsriptiuon of the 1013: language itself. This is suitable for use in e.g. 1014: &Apache::edit::select_arg (once dereferenced that is). 1015: 1016: =cut 1017: 1018: sub list_languages { 1019: my @lang_choices; 1020: 1021: foreach my $id (&languageids()) { 1022: my $code = &supportedlanguagecode($id); 1023: if ($code) { 1024: my $selector = $supported_codes{$id}; 1025: my $description = &plainlanguagedescription($id); 1026: push (@lang_choices, [$selector, $description]); 1027: } 1028: } 1029: return \@lang_choices; 1030: } 1031: 1032: =pod 1033: 1034: =item * &linked_select_forms(...) 1035: 1036: linked_select_forms returns a string containing a <script></script> block 1037: and html for two <select> menus. The select menus will be linked in that 1038: changing the value of the first menu will result in new values being placed 1039: in the second menu. The values in the select menu will appear in alphabetical 1040: order unless a defined order is provided. 1041: 1042: linked_select_forms takes the following ordered inputs: 1043: 1044: =over 4 1045: 1046: =item * $formname, the name of the <form> tag 1047: 1048: =item * $middletext, the text which appears between the <select> tags 1049: 1050: =item * $firstdefault, the default value for the first menu 1051: 1052: =item * $firstselectname, the name of the first <select> tag 1053: 1054: =item * $secondselectname, the name of the second <select> tag 1055: 1056: =item * $hashref, a reference to a hash containing the data for the menus. 1057: 1058: =item * $menuorder, the order of values in the first menu 1059: 1060: =back 1061: 1062: Below is an example of such a hash. Only the 'text', 'default', and 1063: 'select2' keys must appear as stated. keys(%menu) are the possible 1064: values for the first select menu. The text that coincides with the 1065: first menu value is given in $menu{$choice1}->{'text'}. The values 1066: and text for the second menu are given in the hash pointed to by 1067: $menu{$choice1}->{'select2'}. 1068: 1069: my %menu = ( A1 => { text =>"Choice A1" , 1070: default => "B3", 1071: select2 => { 1072: B1 => "Choice B1", 1073: B2 => "Choice B2", 1074: B3 => "Choice B3", 1075: B4 => "Choice B4" 1076: }, 1077: order => ['B4','B3','B1','B2'], 1078: }, 1079: A2 => { text =>"Choice A2" , 1080: default => "C2", 1081: select2 => { 1082: C1 => "Choice C1", 1083: C2 => "Choice C2", 1084: C3 => "Choice C3" 1085: }, 1086: order => ['C2','C1','C3'], 1087: }, 1088: A3 => { text =>"Choice A3" , 1089: default => "D6", 1090: select2 => { 1091: D1 => "Choice D1", 1092: D2 => "Choice D2", 1093: D3 => "Choice D3", 1094: D4 => "Choice D4", 1095: D5 => "Choice D5", 1096: D6 => "Choice D6", 1097: D7 => "Choice D7" 1098: }, 1099: order => ['D4','D3','D2','D1','D7','D6','D5'], 1100: } 1101: ); 1102: 1103: =cut 1104: 1105: sub linked_select_forms { 1106: my ($formname, 1107: $middletext, 1108: $firstdefault, 1109: $firstselectname, 1110: $secondselectname, 1111: $hashref, 1112: $menuorder, 1113: ) = @_; 1114: my $second = "document.$formname.$secondselectname"; 1115: my $first = "document.$formname.$firstselectname"; 1116: # output the javascript to do the changing 1117: my $result = ''; 1118: $result.='<script type="text/javascript" language="JavaScript">'."\n"; 1119: $result.="// <![CDATA[\n"; 1120: $result.="var select2data = new Object();\n"; 1121: $" = '","'; 1122: my $debug = ''; 1123: foreach my $s1 (sort(keys(%$hashref))) { 1124: $result.="select2data.d_$s1 = new Object();\n"; 1125: $result.="select2data.d_$s1.def = new String('". 1126: $hashref->{$s1}->{'default'}."');\n"; 1127: $result.="select2data.d_$s1.values = new Array("; 1128: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } )); 1129: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') { 1130: @s2values = @{$hashref->{$s1}->{'order'}}; 1131: } 1132: $result.="\"@s2values\");\n"; 1133: $result.="select2data.d_$s1.texts = new Array("; 1134: my @s2texts; 1135: foreach my $value (@s2values) { 1136: push @s2texts, $hashref->{$s1}->{'select2'}->{$value}; 1137: } 1138: $result.="\"@s2texts\");\n"; 1139: } 1140: $"=' '; 1141: $result.= <<"END"; 1142: 1143: function select1_changed() { 1144: // Determine new choice 1145: var newvalue = "d_" + $first.value; 1146: // update select2 1147: var values = select2data[newvalue].values; 1148: var texts = select2data[newvalue].texts; 1149: var select2def = select2data[newvalue].def; 1150: var i; 1151: // out with the old 1152: for (i = 0; i < $second.options.length; i++) { 1153: $second.options[i] = null; 1154: } 1155: // in with the nuclear 1156: for (i=0;i<values.length; i++) { 1157: $second.options[i] = new Option(values[i]); 1158: $second.options[i].value = values[i]; 1159: $second.options[i].text = texts[i]; 1160: if (values[i] == select2def) { 1161: $second.options[i].selected = true; 1162: } 1163: } 1164: } 1165: // ]]> 1166: </script> 1167: END 1168: # output the initial values for the selection lists 1169: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n"; 1170: my @order = sort(keys(%{$hashref})); 1171: if (ref($menuorder) eq 'ARRAY') { 1172: @order = @{$menuorder}; 1173: } 1174: foreach my $value (@order) { 1175: $result.=" <option value=\"$value\" "; 1176: $result.=" selected=\"selected\" " if ($value eq $firstdefault); 1177: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n"; 1178: } 1179: $result .= "</select>\n"; 1180: my %select2 = %{$hashref->{$firstdefault}->{'select2'}}; 1181: $result .= $middletext; 1182: $result .= "<select size=\"1\" name=\"$secondselectname\">\n"; 1183: my $seconddefault = $hashref->{$firstdefault}->{'default'}; 1184: 1185: my @secondorder = sort(keys(%select2)); 1186: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') { 1187: @secondorder = @{$hashref->{$firstdefault}->{'order'}}; 1188: } 1189: foreach my $value (@secondorder) { 1190: $result.=" <option value=\"$value\" "; 1191: $result.=" selected=\"selected\" " if ($value eq $seconddefault); 1192: $result.=">".&mt($select2{$value})."</option>\n"; 1193: } 1194: $result .= "</select>\n"; 1195: # return $debug; 1196: return $result; 1197: } # end of sub linked_select_forms { 1198: 1199: =pod 1200: 1201: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid) 1202: 1203: Returns a string corresponding to an HTML link to the given help 1204: $topic, where $topic corresponds to the name of a .tex file in 1205: /home/httpd/html/adm/help/tex, with underscores replaced by 1206: spaces. 1207: 1208: $text will optionally be linked to the same topic, allowing you to 1209: link text in addition to the graphic. If you do not want to link 1210: text, but wish to specify one of the later parameters, pass an 1211: empty string. 1212: 1213: $stayOnPage is a value that will be interpreted as a boolean. If true, 1214: the link will not open a new window. If false, the link will open 1215: a new window using Javascript. (Default is false.) 1216: 1217: $width and $height are optional numerical parameters that will 1218: override the width and height of the popped up window, which may 1219: be useful for certain help topics with big pictures included. 1220: 1221: $imgid is the id of the img tag used for the help icon. This may be 1222: used in a javascript call to switch the image src. See 1223: lonhtmlcommon::htmlareaselectactive() for an example. 1224: 1225: =cut 1226: 1227: sub help_open_topic { 1228: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_; 1229: $text = "" if (not defined $text); 1230: $stayOnPage = 0 if (not defined $stayOnPage); 1231: $width = 500 if (not defined $width); 1232: $height = 400 if (not defined $height); 1233: my $filename = $topic; 1234: $filename =~ s/ /_/g; 1235: 1236: my $template = ""; 1237: my $link; 1238: 1239: $topic=~s/\W/\_/g; 1240: 1241: if (!$stayOnPage) { 1242: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');"; 1243: } elsif ($stayOnPage eq 'popup') { 1244: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1245: } else { 1246: $link = "/adm/help/${filename}.hlp"; 1247: } 1248: 1249: # Add the text 1250: if ($text ne "") { 1251: $template.='<span class="LC_help_open_topic">' 1252: .'<a target="_top" href="'.$link.'">' 1253: .$text.'</a>'; 1254: } 1255: 1256: # (Always) Add the graphic 1257: my $title = &mt('Online Help'); 1258: my $helpicon=&lonhttpdurl("/adm/help/help.png"); 1259: if ($imgid ne '') { 1260: $imgid = ' id="'.$imgid.'"'; 1261: } 1262: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">' 1263: .'<img src="'.$helpicon.'" border="0"' 1264: .' alt="'.&mt('Help: [_1]',$topic).'"' 1265: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 1266: .' /></a>'; 1267: if ($text ne "") { 1268: $template.='</span>'; 1269: } 1270: return $template; 1271: 1272: } 1273: 1274: # This is a quicky function for Latex cheatsheet editing, since it 1275: # appears in at least four places 1276: sub helpLatexCheatsheet { 1277: my ($topic,$text,$not_author,$stayOnPage) = @_; 1278: my $out; 1279: my $addOther = ''; 1280: if ($topic) { 1281: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> '; 1282: } 1283: $out = '<span>' # Start cheatsheet 1284: .$addOther 1285: .'<span>' 1286: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600) 1287: .'</span> <span>' 1288: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600) 1289: .'</span>'; 1290: unless ($not_author) { 1291: $out .= ' <span>' 1292: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600) 1293: .'</span>'; 1294: } 1295: $out .= '</span>'; # End cheatsheet 1296: return $out; 1297: } 1298: 1299: sub general_help { 1300: my $helptopic='Student_Intro'; 1301: if ($env{'request.role'}=~/^(ca|au)/) { 1302: $helptopic='Authoring_Intro'; 1303: } elsif ($env{'request.role'}=~/^(cc|co)/) { 1304: $helptopic='Course_Coordination_Intro'; 1305: } elsif ($env{'request.role'}=~/^dc/) { 1306: $helptopic='Domain_Coordination_Intro'; 1307: } 1308: return $helptopic; 1309: } 1310: 1311: sub update_help_link { 1312: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_; 1313: my $origurl = $ENV{'REQUEST_URI'}; 1314: $origurl=~s|^/~|/priv/|; 1315: my $timestamp = time; 1316: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) { 1317: $$datum = &escape($$datum); 1318: } 1319: 1320: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage"; 1321: my $output .= <<"ENDOUTPUT"; 1322: <script type="text/javascript"> 1323: // <![CDATA[ 1324: banner_link = '$banner_link'; 1325: // ]]> 1326: </script> 1327: ENDOUTPUT 1328: return $output; 1329: } 1330: 1331: # now just updates the help link and generates a blue icon 1332: sub help_open_menu { 1333: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 1334: = @_; 1335: $stayOnPage = 1; 1336: my $output; 1337: if ($component_help) { 1338: if (!$text) { 1339: $output=&help_open_topic($component_help,undef,$stayOnPage, 1340: $width,$height); 1341: } else { 1342: my $help_text; 1343: $help_text=&unescape($topic); 1344: $output='<table><tr><td>'. 1345: &help_open_topic($component_help,$help_text,$stayOnPage, 1346: $width,$height).'</td></tr></table>'; 1347: } 1348: } 1349: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage); 1350: return $output.$banner_link; 1351: } 1352: 1353: sub top_nav_help { 1354: my ($text) = @_; 1355: $text = &mt($text); 1356: my $stay_on_page = 1; 1357: 1358: my $link = ($stay_on_page) ? "javascript:helpMenu('display')" 1359: : "javascript:helpMenu('open')"; 1360: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page); 1361: 1362: my $title = &mt('Get help'); 1363: 1364: return <<"END"; 1365: $banner_link 1366: <a href="$link" title="$title">$text</a> 1367: END 1368: } 1369: 1370: sub help_menu_js { 1371: my ($text) = @_; 1372: my $stayOnPage = 1; 1373: my $width = 620; 1374: my $height = 600; 1375: my $helptopic=&general_help(); 1376: my $details_link = '/adm/help/'.$helptopic.'.hlp'; 1377: my $nothing=&Apache::lonhtmlcommon::javascript_nothing(); 1378: my $start_page = 1379: &Apache::loncommon::start_page('Help Menu', undef, 1380: {'frameset' => 1, 1381: 'js_ready' => 1, 1382: 'add_entries' => { 1383: 'border' => '0', 1384: 'rows' => "110,*",},}); 1385: my $end_page = 1386: &Apache::loncommon::end_page({'frameset' => 1, 1387: 'js_ready' => 1,}); 1388: 1389: my $template .= <<"ENDTEMPLATE"; 1390: <script type="text/javascript"> 1391: // <![CDATA[ 1392: // <!-- BEGIN LON-CAPA Internal 1393: var banner_link = ''; 1394: function helpMenu(target) { 1395: var caller = this; 1396: if (target == 'open') { 1397: var newWindow = null; 1398: try { 1399: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" ) 1400: } 1401: catch(error) { 1402: writeHelp(caller); 1403: return; 1404: } 1405: if (newWindow) { 1406: caller = newWindow; 1407: } 1408: } 1409: writeHelp(caller); 1410: return; 1411: } 1412: function writeHelp(caller) { 1413: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page') 1414: caller.document.close() 1415: caller.focus() 1416: } 1417: // END LON-CAPA Internal --> 1418: // ]]> 1419: </script> 1420: ENDTEMPLATE 1421: return $template; 1422: } 1423: 1424: sub help_open_bug { 1425: my ($topic, $text, $stayOnPage, $width, $height) = @_; 1426: unless ($env{'user.adv'}) { return ''; } 1427: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; } 1428: $text = "" if (not defined $text); 1429: $stayOnPage=1; 1430: $width = 600 if (not defined $width); 1431: $height = 600 if (not defined $height); 1432: 1433: $topic=~s/\W+/\+/g; 1434: my $link=''; 1435: my $template=''; 1436: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='. 1437: &escape($ENV{'REQUEST_URI'}).'&component='.$topic; 1438: if (!$stayOnPage) 1439: { 1440: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1441: } 1442: else 1443: { 1444: $link = $url; 1445: } 1446: # Add the text 1447: if ($text ne "") 1448: { 1449: $template .= 1450: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>". 1451: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>"; 1452: } 1453: 1454: # Add the graphic 1455: my $title = &mt('Report a Bug'); 1456: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif"); 1457: $template .= <<"ENDTEMPLATE"; 1458: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a> 1459: ENDTEMPLATE 1460: if ($text ne '') { $template.='</td></tr></table>' }; 1461: return $template; 1462: 1463: } 1464: 1465: sub help_open_faq { 1466: my ($topic, $text, $stayOnPage, $width, $height) = @_; 1467: unless ($env{'user.adv'}) { return ''; } 1468: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; } 1469: $text = "" if (not defined $text); 1470: $stayOnPage=1; 1471: $width = 350 if (not defined $width); 1472: $height = 400 if (not defined $height); 1473: 1474: $topic=~s/\W+/\+/g; 1475: my $link=''; 1476: my $template=''; 1477: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html'; 1478: if (!$stayOnPage) 1479: { 1480: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))"; 1481: } 1482: else 1483: { 1484: $link = $url; 1485: } 1486: 1487: # Add the text 1488: if ($text ne "") 1489: { 1490: $template .= 1491: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>". 1492: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>"; 1493: } 1494: 1495: # Add the graphic 1496: my $title = &mt('View the FAQ'); 1497: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif"); 1498: $template .= <<"ENDTEMPLATE"; 1499: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a> 1500: ENDTEMPLATE 1501: if ($text ne '') { $template.='</td></tr></table>' }; 1502: return $template; 1503: 1504: } 1505: 1506: ############################################################### 1507: ############################################################### 1508: 1509: =pod 1510: 1511: =item * &change_content_javascript(): 1512: 1513: This and the next function allow you to create small sections of an 1514: otherwise static HTML page that you can update on the fly with 1515: Javascript, even in Netscape 4. 1516: 1517: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag) 1518: must be written to the HTML page once. It will prove the Javascript 1519: function "change(name, content)". Calling the change function with the 1520: name of the section 1521: you want to update, matching the name passed to C<changable_area>, and 1522: the new content you want to put in there, will put the content into 1523: that area. 1524: 1525: B<Note>: Netscape 4 only reserves enough space for the changable area 1526: to contain room for the original contents. You need to "make space" 1527: for whatever changes you wish to make, and be B<sure> to check your 1528: code in Netscape 4. This feature in Netscape 4 is B<not> powerful; 1529: it's adequate for updating a one-line status display, but little more. 1530: This script will set the space to 100% width, so you only need to 1531: worry about height in Netscape 4. 1532: 1533: Modern browsers are much less limiting, and if you can commit to the 1534: user not using Netscape 4, this feature may be used freely with 1535: pretty much any HTML. 1536: 1537: =cut 1538: 1539: sub change_content_javascript { 1540: # If we're on Netscape 4, we need to use Layer-based code 1541: if ($env{'browser.type'} eq 'netscape' && 1542: $env{'browser.version'} =~ /^4\./) { 1543: return (<<NETSCAPE4); 1544: function change(name, content) { 1545: doc = document.layers[name+"___escape"].layers[0].document; 1546: doc.open(); 1547: doc.write(content); 1548: doc.close(); 1549: } 1550: NETSCAPE4 1551: } else { 1552: # Otherwise, we need to use semi-standards-compliant code 1553: # (technically, "innerHTML" isn't standard but the equivalent 1554: # is really scary, and every useful browser supports it 1555: return (<<DOMBASED); 1556: function change(name, content) { 1557: element = document.getElementById(name); 1558: element.innerHTML = content; 1559: } 1560: DOMBASED 1561: } 1562: } 1563: 1564: =pod 1565: 1566: =item * &changable_area($name,$origContent): 1567: 1568: This provides a "changable area" that can be modified on the fly via 1569: the Javascript code provided in C<change_content_javascript>. $name is 1570: the name you will use to reference the area later; do not repeat the 1571: same name on a given HTML page more then once. $origContent is what 1572: the area will originally contain, which can be left blank. 1573: 1574: =cut 1575: 1576: sub changable_area { 1577: my ($name, $origContent) = @_; 1578: 1579: if ($env{'browser.type'} eq 'netscape' && 1580: $env{'browser.version'} =~ /^4\./) { 1581: # If this is netscape 4, we need to use the Layer tag 1582: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>"; 1583: } else { 1584: return "<span id='$name'>$origContent</span>"; 1585: } 1586: } 1587: 1588: =pod 1589: 1590: =item * &viewport_geometry_js 1591: 1592: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser. 1593: 1594: =cut 1595: 1596: 1597: sub viewport_geometry_js { 1598: return <<"GEOMETRY"; 1599: var Geometry = {}; 1600: function init_geometry() { 1601: if (Geometry.init) { return }; 1602: Geometry.init=1; 1603: if (window.innerHeight) { 1604: Geometry.getViewportHeight = function() { return window.innerHeight; }; 1605: Geometry.getViewportWidth = function() { return window.innerWidth; }; 1606: Geometry.getHorizontalScroll = function() { return window.pageXOffset; }; 1607: Geometry.getVerticalScroll = function() { return window.pageYOffset; }; 1608: } 1609: else if (document.documentElement && document.documentElement.clientHeight) { 1610: Geometry.getViewportHeight = 1611: function() { return document.documentElement.clientHeight; }; 1612: Geometry.getViewportWidth = 1613: function() { return document.documentElement.clientWidth; }; 1614: 1615: Geometry.getHorizontalScroll = 1616: function() { return document.documentElement.scrollLeft; }; 1617: Geometry.getVerticalScroll = 1618: function() { return document.documentElement.scrollTop; }; 1619: } 1620: else if (document.body.clientHeight) { 1621: Geometry.getViewportHeight = 1622: function() { return document.body.clientHeight; }; 1623: Geometry.getViewportWidth = 1624: function() { return document.body.clientWidth; }; 1625: Geometry.getHorizontalScroll = 1626: function() { return document.body.scrollLeft; }; 1627: Geometry.getVerticalScroll = 1628: function() { return document.body.scrollTop; }; 1629: } 1630: } 1631: 1632: GEOMETRY 1633: } 1634: 1635: =pod 1636: 1637: =item * &viewport_size_js() 1638: 1639: 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. 1640: 1641: =cut 1642: 1643: sub viewport_size_js { 1644: my $geometry = &viewport_geometry_js(); 1645: return <<"DIMS"; 1646: 1647: $geometry 1648: 1649: function getViewportDims(width,height) { 1650: init_geometry(); 1651: width.value = Geometry.getViewportWidth(); 1652: height.value = Geometry.getViewportHeight(); 1653: return; 1654: } 1655: 1656: DIMS 1657: } 1658: 1659: =pod 1660: 1661: =item * &resize_textarea_js() 1662: 1663: emits the needed javascript to resize a textarea to be as big as possible 1664: 1665: creates a function resize_textrea that takes two IDs first should be 1666: the id of the element to resize, second should be the id of a div that 1667: surrounds everything that comes after the textarea, this routine needs 1668: to be attached to the <body> for the onload and onresize events. 1669: 1670: =back 1671: 1672: =cut 1673: 1674: sub resize_textarea_js { 1675: my $geometry = &viewport_geometry_js(); 1676: return <<"RESIZE"; 1677: <script type="text/javascript"> 1678: // <![CDATA[ 1679: $geometry 1680: 1681: function getX(element) { 1682: var x = 0; 1683: while (element) { 1684: x += element.offsetLeft; 1685: element = element.offsetParent; 1686: } 1687: return x; 1688: } 1689: function getY(element) { 1690: var y = 0; 1691: while (element) { 1692: y += element.offsetTop; 1693: element = element.offsetParent; 1694: } 1695: return y; 1696: } 1697: 1698: 1699: function resize_textarea(textarea_id,bottom_id) { 1700: init_geometry(); 1701: var textarea = document.getElementById(textarea_id); 1702: //alert(textarea); 1703: 1704: var textarea_top = getY(textarea); 1705: var textarea_height = textarea.offsetHeight; 1706: var bottom = document.getElementById(bottom_id); 1707: var bottom_top = getY(bottom); 1708: var bottom_height = bottom.offsetHeight; 1709: var window_height = Geometry.getViewportHeight(); 1710: var fudge = 23; 1711: var new_height = window_height-fudge-textarea_top-bottom_height; 1712: if (new_height < 300) { 1713: new_height = 300; 1714: } 1715: textarea.style.height=new_height+'px'; 1716: } 1717: // ]]> 1718: </script> 1719: RESIZE 1720: 1721: } 1722: 1723: =pod 1724: 1725: =head1 Excel and CSV file utility routines 1726: 1727: =over 4 1728: 1729: =cut 1730: 1731: ############################################################### 1732: ############################################################### 1733: 1734: =pod 1735: 1736: =item * &csv_translate($text) 1737: 1738: Translate $text to allow it to be output as a 'comma separated values' 1739: format. 1740: 1741: =cut 1742: 1743: ############################################################### 1744: ############################################################### 1745: sub csv_translate { 1746: my $text = shift; 1747: $text =~ s/\"/\"\"/g; 1748: $text =~ s/\n/ /g; 1749: return $text; 1750: } 1751: 1752: ############################################################### 1753: ############################################################### 1754: 1755: =pod 1756: 1757: =item * &define_excel_formats() 1758: 1759: Define some commonly used Excel cell formats. 1760: 1761: Currently supported formats: 1762: 1763: =over 4 1764: 1765: =item header 1766: 1767: =item bold 1768: 1769: =item h1 1770: 1771: =item h2 1772: 1773: =item h3 1774: 1775: =item h4 1776: 1777: =item i 1778: 1779: =item date 1780: 1781: =back 1782: 1783: Inputs: $workbook 1784: 1785: Returns: $format, a hash reference. 1786: 1787: 1788: =cut 1789: 1790: ############################################################### 1791: ############################################################### 1792: sub define_excel_formats { 1793: my ($workbook) = @_; 1794: my $format; 1795: $format->{'header'} = $workbook->add_format(bold => 1, 1796: bottom => 1, 1797: align => 'center'); 1798: $format->{'bold'} = $workbook->add_format(bold=>1); 1799: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18); 1800: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16); 1801: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14); 1802: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12); 1803: $format->{'i'} = $workbook->add_format(italic=>1); 1804: $format->{'date'} = $workbook->add_format(num_format=> 1805: 'mm/dd/yyyy hh:mm:ss'); 1806: return $format; 1807: } 1808: 1809: ############################################################### 1810: ############################################################### 1811: 1812: =pod 1813: 1814: =item * &create_workbook() 1815: 1816: Create an Excel worksheet. If it fails, output message on the 1817: request object and return undefs. 1818: 1819: Inputs: Apache request object 1820: 1821: Returns (undef) on failure, 1822: Excel worksheet object, scalar with filename, and formats 1823: from &Apache::loncommon::define_excel_formats on success 1824: 1825: =cut 1826: 1827: ############################################################### 1828: ############################################################### 1829: sub create_workbook { 1830: my ($r) = @_; 1831: # 1832: # Create the excel spreadsheet 1833: my $filename = '/prtspool/'. 1834: $env{'user.name'}.'_'.$env{'user.domain'}.'_'. 1835: time.'_'.rand(1000000000).'.xls'; 1836: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename); 1837: if (! defined($workbook)) { 1838: $r->log_error("Error creating excel spreadsheet $filename: $!"); 1839: $r->print( 1840: '<p class="LC_error">' 1841: .&mt('Problems occurred in creating the new Excel file.') 1842: .' '.&mt('This error has been logged.') 1843: .' '.&mt('Please alert your LON-CAPA administrator.') 1844: .'</p>' 1845: ); 1846: return (undef); 1847: } 1848: # 1849: $workbook->set_tempdir(LONCAPA::tempdir()); 1850: # 1851: my $format = &Apache::loncommon::define_excel_formats($workbook); 1852: return ($workbook,$filename,$format); 1853: } 1854: 1855: ############################################################### 1856: ############################################################### 1857: 1858: =pod 1859: 1860: =item * &create_text_file() 1861: 1862: Create a file to write to and eventually make available to the user. 1863: If file creation fails, outputs an error message on the request object and 1864: return undefs. 1865: 1866: Inputs: Apache request object, and file suffix 1867: 1868: Returns (undef) on failure, 1869: Filehandle and filename on success. 1870: 1871: =cut 1872: 1873: ############################################################### 1874: ############################################################### 1875: sub create_text_file { 1876: my ($r,$suffix) = @_; 1877: if (! defined($suffix)) { $suffix = 'txt'; }; 1878: my $fh; 1879: my $filename = '/prtspool/'. 1880: $env{'user.name'}.'_'.$env{'user.domain'}.'_'. 1881: time.'_'.rand(1000000000).'.'.$suffix; 1882: $fh = Apache::File->new('>/home/httpd'.$filename); 1883: if (! defined($fh)) { 1884: $r->log_error("Couldn't open $filename for output $!"); 1885: $r->print( 1886: '<p class="LC_error">' 1887: .&mt('Problems occurred in creating the output file.') 1888: .' '.&mt('This error has been logged.') 1889: .' '.&mt('Please alert your LON-CAPA administrator.') 1890: .'</p>' 1891: ); 1892: } 1893: return ($fh,$filename) 1894: } 1895: 1896: 1897: =pod 1898: 1899: =back 1900: 1901: =cut 1902: 1903: ############################################################### 1904: ## Home server <option> list generating code ## 1905: ############################################################### 1906: 1907: # ------------------------------------------ 1908: 1909: sub domain_select { 1910: my ($name,$value,$multiple)=@_; 1911: my %domains=map { 1912: $_ => $_.' '. &Apache::lonnet::domain($_,'description') 1913: } &Apache::lonnet::all_domains(); 1914: if ($multiple) { 1915: $domains{''}=&mt('Any domain'); 1916: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))]; 1917: return &multiple_select_form($name,$value,4,\%domains); 1918: } else { 1919: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))]; 1920: return &select_form($name,$value,\%domains); 1921: } 1922: } 1923: 1924: #------------------------------------------- 1925: 1926: =pod 1927: 1928: =head1 Routines for form select boxes 1929: 1930: =over 4 1931: 1932: =item * &multiple_select_form($name,$value,$size,$hash,$order) 1933: 1934: Returns a string containing a <select> element int multiple mode 1935: 1936: 1937: Args: 1938: $name - name of the <select> element 1939: $value - scalar or array ref of values that should already be selected 1940: $size - number of rows long the select element is 1941: $hash - the elements should be 'option' => 'shown text' 1942: (shown text should already have been &mt()) 1943: $order - (optional) array ref of the order to show the elements in 1944: 1945: =cut 1946: 1947: #------------------------------------------- 1948: sub multiple_select_form { 1949: my ($name,$value,$size,$hash,$order)=@_; 1950: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value); 1951: my $output=''; 1952: if (! defined($size)) { 1953: $size = 4; 1954: if (scalar(keys(%$hash))<4) { 1955: $size = scalar(keys(%$hash)); 1956: } 1957: } 1958: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">'; 1959: my @order; 1960: if (ref($order) eq 'ARRAY') { 1961: @order = @{$order}; 1962: } else { 1963: @order = sort(keys(%$hash)); 1964: } 1965: if (exists($$hash{'select_form_order'})) { 1966: @order = @{$$hash{'select_form_order'}}; 1967: } 1968: 1969: foreach my $key (@order) { 1970: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" '; 1971: $output.='selected="selected" ' if ($selected{$key}); 1972: $output.='>'.$hash->{$key}."</option>\n"; 1973: } 1974: $output.="</select>\n"; 1975: return $output; 1976: } 1977: 1978: #------------------------------------------- 1979: 1980: =pod 1981: 1982: =item * &select_form($defdom,$name,$hashref,$onchange) 1983: 1984: Returns a string containing a <select name='$name' size='1'> form to 1985: allow a user to select options from a ref to a hash containing: 1986: option_name => displayed text. An optional $onchange can include 1987: a javascript onchange item, e.g., onchange="this.form.submit();" 1988: 1989: See lonrights.pm for an example invocation and use. 1990: 1991: =cut 1992: 1993: #------------------------------------------- 1994: sub select_form { 1995: my ($def,$name,$hashref,$onchange) = @_; 1996: return unless (ref($hashref) eq 'HASH'); 1997: if ($onchange) { 1998: $onchange = ' onchange="'.$onchange.'"'; 1999: } 2000: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n"; 2001: my @keys; 2002: if (exists($hashref->{'select_form_order'})) { 2003: @keys=@{$hashref->{'select_form_order'}}; 2004: } else { 2005: @keys=sort(keys(%{$hashref})); 2006: } 2007: foreach my $key (@keys) { 2008: $selectform.= 2009: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '. 2010: ($key eq $def ? 'selected="selected" ' : ''). 2011: ">".$hashref->{$key}."</option>\n"; 2012: } 2013: $selectform.="</select>"; 2014: return $selectform; 2015: } 2016: 2017: # For display filters 2018: 2019: sub display_filter { 2020: my ($context) = @_; 2021: if (!$env{'form.show'}) { $env{'form.show'}=10; } 2022: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; } 2023: my $phraseinput = 'hidden'; 2024: my $includeinput = 'hidden'; 2025: my ($checked,$includetypestext); 2026: if ($env{'form.displayfilter'} eq 'containing') { 2027: $phraseinput = 'text'; 2028: if ($context eq 'parmslog') { 2029: $includeinput = 'checkbox'; 2030: if ($env{'form.includetypes'}) { 2031: $checked = ' checked="checked"'; 2032: } 2033: $includetypestext = &mt('Include parameter types'); 2034: } 2035: } else { 2036: $includetypestext = ' '; 2037: } 2038: my ($additional,$secondid,$thirdid); 2039: if ($context eq 'parmslog') { 2040: $additional = 2041: '<label><input type="'.$includeinput.'" name="includetypes"'. 2042: $checked.' name="includetypes" value="1" id="includetypes" />'. 2043: ' <span id="includetypestext">'.$includetypestext.'</span>'. 2044: '</label>'; 2045: $secondid = 'includetypes'; 2046: $thirdid = 'includetypestext'; 2047: } 2048: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context', 2049: '$secondid','$thirdid')"; 2050: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]', 2051: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef, 2052: (&mt('all'),10,20,50,100,1000,10000))). 2053: '</label></span> <span class="LC_nobreak">'. 2054: &mt('Filter: [_1]', 2055: &select_form($env{'form.displayfilter'}, 2056: 'displayfilter', 2057: {'currentfolder' => 'Current folder/page', 2058: 'containing' => 'Containing phrase', 2059: 'none' => 'None'},$onchange)).' '. 2060: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'. 2061: &HTML::Entities::encode($env{'form.containingphrase'}). 2062: '" />'.$additional; 2063: } 2064: 2065: sub display_filter_js { 2066: my $includetext = &mt('Include parameter types'); 2067: return <<"ENDJS"; 2068: 2069: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) { 2070: var firstType = 'hidden'; 2071: if (setter.options[setter.selectedIndex].value == 'containing') { 2072: firstType = 'text'; 2073: } 2074: firstObject = document.getElementById(firstid); 2075: if (typeof(firstObject) == 'object') { 2076: if (firstObject.type != firstType) { 2077: changeInputType(firstObject,firstType); 2078: } 2079: } 2080: if (context == 'parmslog') { 2081: var secondType = 'hidden'; 2082: if (firstType == 'text') { 2083: secondType = 'checkbox'; 2084: } 2085: secondObject = document.getElementById(secondid); 2086: if (typeof(secondObject) == 'object') { 2087: if (secondObject.type != secondType) { 2088: changeInputType(secondObject,secondType); 2089: } 2090: } 2091: var textItem = document.getElementById(thirdid); 2092: var currtext = textItem.innerHTML; 2093: var newtext; 2094: if (firstType == 'text') { 2095: newtext = '$includetext'; 2096: } else { 2097: newtext = ' '; 2098: } 2099: if (currtext != newtext) { 2100: textItem.innerHTML = newtext; 2101: } 2102: } 2103: return; 2104: } 2105: 2106: function changeInputType(oldObject,newType) { 2107: var newObject = document.createElement('input'); 2108: newObject.type = newType; 2109: if (oldObject.size) { 2110: newObject.size = oldObject.size; 2111: } 2112: if (oldObject.value) { 2113: newObject.value = oldObject.value; 2114: } 2115: if (oldObject.name) { 2116: newObject.name = oldObject.name; 2117: } 2118: if (oldObject.id) { 2119: newObject.id = oldObject.id; 2120: } 2121: oldObject.parentNode.replaceChild(newObject,oldObject); 2122: return; 2123: } 2124: 2125: ENDJS 2126: } 2127: 2128: sub gradeleveldescription { 2129: my $gradelevel=shift; 2130: my %gradelevels=(0 => 'Not specified', 2131: 1 => 'Grade 1', 2132: 2 => 'Grade 2', 2133: 3 => 'Grade 3', 2134: 4 => 'Grade 4', 2135: 5 => 'Grade 5', 2136: 6 => 'Grade 6', 2137: 7 => 'Grade 7', 2138: 8 => 'Grade 8', 2139: 9 => 'Grade 9', 2140: 10 => 'Grade 10', 2141: 11 => 'Grade 11', 2142: 12 => 'Grade 12', 2143: 13 => 'Grade 13', 2144: 14 => '100 Level', 2145: 15 => '200 Level', 2146: 16 => '300 Level', 2147: 17 => '400 Level', 2148: 18 => 'Graduate Level'); 2149: return &mt($gradelevels{$gradelevel}); 2150: } 2151: 2152: sub select_level_form { 2153: my ($deflevel,$name)=@_; 2154: unless ($deflevel) { $deflevel=0; } 2155: my $selectform = "<select name=\"$name\" size=\"1\">\n"; 2156: for (my $i=0; $i<=18; $i++) { 2157: $selectform.="<option value=\"$i\" ". 2158: ($i==$deflevel ? 'selected="selected" ' : ''). 2159: ">".&gradeleveldescription($i)."</option>\n"; 2160: } 2161: $selectform.="</select>"; 2162: return $selectform; 2163: } 2164: 2165: #------------------------------------------- 2166: 2167: =pod 2168: 2169: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) 2170: 2171: Returns a string containing a <select name='$name' size='1'> form to 2172: allow a user to select the domain to preform an operation in. 2173: See loncreateuser.pm for an example invocation and use. 2174: 2175: If the $includeempty flag is set, it also includes an empty choice ("no domain 2176: selected"); 2177: 2178: If the $showdomdesc flag is set, the domain name is followed by the domain description. 2179: 2180: 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. 2181: 2182: The optional $incdoms is a reference to an array of domains which will be the only available options. 2183: 2184: =cut 2185: 2186: #------------------------------------------- 2187: sub select_dom_form { 2188: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_; 2189: if ($onchange) { 2190: $onchange = ' onchange="'.$onchange.'"'; 2191: } 2192: my @domains; 2193: if (ref($incdoms) eq 'ARRAY') { 2194: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms}); 2195: } else { 2196: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains()); 2197: } 2198: if ($includeempty) { @domains=('',@domains); } 2199: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n"; 2200: foreach my $dom (@domains) { 2201: $selectdomain.="<option value=\"$dom\" ". 2202: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom; 2203: if ($showdomdesc) { 2204: if ($dom ne '') { 2205: my $domdesc = &Apache::lonnet::domain($dom,'description'); 2206: if ($domdesc ne '') { 2207: $selectdomain .= ' ('.$domdesc.')'; 2208: } 2209: } 2210: } 2211: $selectdomain .= "</option>\n"; 2212: } 2213: $selectdomain.="</select>"; 2214: return $selectdomain; 2215: } 2216: 2217: #------------------------------------------- 2218: 2219: =pod 2220: 2221: =item * &home_server_form_item($domain,$name,$defaultflag) 2222: 2223: input: 4 arguments (two required, two optional) - 2224: $domain - domain of new user 2225: $name - name of form element 2226: $default - Value of 'default' causes a default item to be first 2227: option, and selected by default. 2228: $hide - Value of 'hide' causes hiding of the name of the server, 2229: if 1 server found, or default, if 0 found. 2230: output: returns 2 items: 2231: (a) form element which contains either: 2232: (i) <select name="$name"> 2233: <option value="$hostid1">$hostid $servers{$hostid}</option> 2234: <option value="$hostid2">$hostid $servers{$hostid}</option> 2235: </select> 2236: form item if there are multiple library servers in $domain, or 2237: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 2238: if there is only one library server in $domain. 2239: 2240: (b) number of library servers found. 2241: 2242: See loncreateuser.pm for example of use. 2243: 2244: =cut 2245: 2246: #------------------------------------------- 2247: sub home_server_form_item { 2248: my ($domain,$name,$default,$hide) = @_; 2249: my %servers = &Apache::lonnet::get_servers($domain,'library'); 2250: my $result; 2251: my $numlib = keys(%servers); 2252: if ($numlib > 1) { 2253: $result .= '<select name="'.$name.'" />'."\n"; 2254: if ($default) { 2255: $result .= '<option value="default" selected="selected">'.&mt('default'). 2256: '</option>'."\n"; 2257: } 2258: foreach my $hostid (sort(keys(%servers))) { 2259: $result.= '<option value="'.$hostid.'">'. 2260: $hostid.' '.$servers{$hostid}."</option>\n"; 2261: } 2262: $result .= '</select>'."\n"; 2263: } elsif ($numlib == 1) { 2264: my $hostid; 2265: foreach my $item (keys(%servers)) { 2266: $hostid = $item; 2267: } 2268: $result .= '<input type="hidden" name="'.$name.'" value="'. 2269: $hostid.'" />'; 2270: if (!$hide) { 2271: $result .= $hostid.' '.$servers{$hostid}; 2272: } 2273: $result .= "\n"; 2274: } elsif ($default) { 2275: $result .= '<input type="hidden" name="'.$name. 2276: '" value="default" />'; 2277: if (!$hide) { 2278: $result .= &mt('default'); 2279: } 2280: $result .= "\n"; 2281: } 2282: return ($result,$numlib); 2283: } 2284: 2285: =pod 2286: 2287: =back 2288: 2289: =cut 2290: 2291: ############################################################### 2292: ## Decoding User Agent ## 2293: ############################################################### 2294: 2295: =pod 2296: 2297: =head1 Decoding the User Agent 2298: 2299: =over 4 2300: 2301: =item * &decode_user_agent() 2302: 2303: Inputs: $r 2304: 2305: Outputs: 2306: 2307: =over 4 2308: 2309: =item * $httpbrowser 2310: 2311: =item * $clientbrowser 2312: 2313: =item * $clientversion 2314: 2315: =item * $clientmathml 2316: 2317: =item * $clientunicode 2318: 2319: =item * $clientos 2320: 2321: =back 2322: 2323: =back 2324: 2325: =cut 2326: 2327: ############################################################### 2328: ############################################################### 2329: sub decode_user_agent { 2330: my ($r)=@_; 2331: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"}); 2332: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"}); 2333: my $httpbrowser=$ENV{"HTTP_USER_AGENT"}; 2334: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); } 2335: my $clientbrowser='unknown'; 2336: my $clientversion='0'; 2337: my $clientmathml=''; 2338: my $clientunicode='0'; 2339: for (my $i=0;$i<=$#browsertype;$i++) { 2340: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]); 2341: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) { 2342: $clientbrowser=$bname; 2343: $httpbrowser=~/$vreg/i; 2344: $clientversion=$1; 2345: $clientmathml=($clientversion>=$minv); 2346: $clientunicode=($clientversion>=$univ); 2347: } 2348: } 2349: my $clientos='unknown'; 2350: if (($httpbrowser=~/linux/i) || 2351: ($httpbrowser=~/unix/i) || 2352: ($httpbrowser=~/ux/i) || 2353: ($httpbrowser=~/solaris/i)) { $clientos='unix'; } 2354: if (($httpbrowser=~/vax/i) || 2355: ($httpbrowser=~/vms/i)) { $clientos='vms'; } 2356: if ($httpbrowser=~/next/i) { $clientos='next'; } 2357: if (($httpbrowser=~/mac/i) || 2358: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; } 2359: if ($httpbrowser=~/win/i) { $clientos='win'; } 2360: if ($httpbrowser=~/embed/i) { $clientos='pda'; } 2361: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, 2362: $clientunicode,$clientos,); 2363: } 2364: 2365: ############################################################### 2366: ## Authentication changing form generation subroutines ## 2367: ############################################################### 2368: ## 2369: ## All of the authform_xxxxxxx subroutines take their inputs in a 2370: ## hash, and have reasonable default values. 2371: ## 2372: ## formname = the name given in the <form> tag. 2373: #------------------------------------------- 2374: 2375: =pod 2376: 2377: =head1 Authentication Routines 2378: 2379: =over 4 2380: 2381: =item * &authform_xxxxxx() 2382: 2383: The authform_xxxxxx subroutines provide javascript and html forms which 2384: handle some of the conveniences required for authentication forms. 2385: This is not an optimal method, but it works. 2386: 2387: =over 4 2388: 2389: =item * authform_header 2390: 2391: =item * authform_authorwarning 2392: 2393: =item * authform_nochange 2394: 2395: =item * authform_kerberos 2396: 2397: =item * authform_internal 2398: 2399: =item * authform_filesystem 2400: 2401: =back 2402: 2403: See loncreateuser.pm for invocation and use examples. 2404: 2405: =cut 2406: 2407: #------------------------------------------- 2408: sub authform_header{ 2409: my %in = ( 2410: formname => 'cu', 2411: kerb_def_dom => '', 2412: @_, 2413: ); 2414: $in{'formname'} = 'document.' . $in{'formname'}; 2415: my $result=''; 2416: 2417: #---------------------------------------------- Code for upper case translation 2418: my $Javascript_toUpperCase; 2419: unless ($in{kerb_def_dom}) { 2420: $Javascript_toUpperCase =<<"END"; 2421: switch (choice) { 2422: case 'krb': currentform.elements[choicearg].value = 2423: currentform.elements[choicearg].value.toUpperCase(); 2424: break; 2425: default: 2426: } 2427: END 2428: } else { 2429: $Javascript_toUpperCase = ""; 2430: } 2431: 2432: my $radioval = "'nochange'"; 2433: if (defined($in{'curr_authtype'})) { 2434: if ($in{'curr_authtype'} ne '') { 2435: $radioval = "'".$in{'curr_authtype'}."arg'"; 2436: } 2437: } 2438: my $argfield = 'null'; 2439: if (defined($in{'mode'})) { 2440: if ($in{'mode'} eq 'modifycourse') { 2441: if (defined($in{'curr_autharg'})) { 2442: if ($in{'curr_autharg'} ne '') { 2443: $argfield = "'$in{'curr_autharg'}'"; 2444: } 2445: } 2446: } 2447: } 2448: 2449: $result.=<<"END"; 2450: var current = new Object(); 2451: current.radiovalue = $radioval; 2452: current.argfield = $argfield; 2453: 2454: function changed_radio(choice,currentform) { 2455: var choicearg = choice + 'arg'; 2456: // If a radio button in changed, we need to change the argfield 2457: if (current.radiovalue != choice) { 2458: current.radiovalue = choice; 2459: if (current.argfield != null) { 2460: currentform.elements[current.argfield].value = ''; 2461: } 2462: if (choice == 'nochange') { 2463: current.argfield = null; 2464: } else { 2465: current.argfield = choicearg; 2466: switch(choice) { 2467: case 'krb': 2468: currentform.elements[current.argfield].value = 2469: "$in{'kerb_def_dom'}"; 2470: break; 2471: default: 2472: break; 2473: } 2474: } 2475: } 2476: return; 2477: } 2478: 2479: function changed_text(choice,currentform) { 2480: var choicearg = choice + 'arg'; 2481: if (currentform.elements[choicearg].value !='') { 2482: $Javascript_toUpperCase 2483: // clear old field 2484: if ((current.argfield != choicearg) && (current.argfield != null)) { 2485: currentform.elements[current.argfield].value = ''; 2486: } 2487: current.argfield = choicearg; 2488: } 2489: set_auth_radio_buttons(choice,currentform); 2490: return; 2491: } 2492: 2493: function set_auth_radio_buttons(newvalue,currentform) { 2494: var numauthchoices = currentform.login.length; 2495: if (typeof numauthchoices == "undefined") { 2496: return; 2497: } 2498: var i=0; 2499: while (i < numauthchoices) { 2500: if (currentform.login[i].value == newvalue) { break; } 2501: i++; 2502: } 2503: if (i == numauthchoices) { 2504: return; 2505: } 2506: current.radiovalue = newvalue; 2507: currentform.login[i].checked = true; 2508: return; 2509: } 2510: END 2511: return $result; 2512: } 2513: 2514: sub authform_authorwarning{ 2515: my $result=''; 2516: $result='<i>'. 2517: &mt('As a general rule, only authors or co-authors should be '. 2518: 'filesystem authenticated '. 2519: '(which allows access to the server filesystem).')."</i>\n"; 2520: return $result; 2521: } 2522: 2523: sub authform_nochange{ 2524: my %in = ( 2525: formname => 'document.cu', 2526: kerb_def_dom => 'MSU.EDU', 2527: @_, 2528: ); 2529: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2530: my $result; 2531: if (keys(%can_assign) == 0) { 2532: $result = &mt('Under you current role you are not permitted to change login settings for this user'); 2533: } else { 2534: $result = '<label>'.&mt('[_1] Do not change login data', 2535: '<input type="radio" name="login" value="nochange" '. 2536: 'checked="checked" onclick="'. 2537: "javascript:changed_radio('nochange',$in{'formname'});".'" />'). 2538: '</label>'; 2539: } 2540: return $result; 2541: } 2542: 2543: sub authform_kerberos { 2544: my %in = ( 2545: formname => 'document.cu', 2546: kerb_def_dom => 'MSU.EDU', 2547: kerb_def_auth => 'krb4', 2548: @_, 2549: ); 2550: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype, 2551: $autharg,$jscall); 2552: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2553: if ($in{'kerb_def_auth'} eq 'krb5') { 2554: $check5 = ' checked="checked"'; 2555: } else { 2556: $check4 = ' checked="checked"'; 2557: } 2558: $krbarg = $in{'kerb_def_dom'}; 2559: if (defined($in{'curr_authtype'})) { 2560: if ($in{'curr_authtype'} eq 'krb') { 2561: $krbcheck = ' checked="checked"'; 2562: if (defined($in{'mode'})) { 2563: if ($in{'mode'} eq 'modifyuser') { 2564: $krbcheck = ''; 2565: } 2566: } 2567: if (defined($in{'curr_kerb_ver'})) { 2568: if ($in{'curr_krb_ver'} eq '5') { 2569: $check5 = ' checked="checked"'; 2570: $check4 = ''; 2571: } else { 2572: $check4 = ' checked="checked"'; 2573: $check5 = ''; 2574: } 2575: } 2576: if (defined($in{'curr_autharg'})) { 2577: $krbarg = $in{'curr_autharg'}; 2578: } 2579: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) { 2580: if (defined($in{'curr_autharg'})) { 2581: $result = 2582: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].', 2583: $in{'curr_autharg'},$krbver); 2584: } else { 2585: $result = 2586: &mt('Currently Kerberos authenticated, Version [_1].',$krbver); 2587: } 2588: return $result; 2589: } 2590: } 2591: } else { 2592: if ($authnum == 1) { 2593: $authtype = '<input type="hidden" name="login" value="krb" />'; 2594: } 2595: } 2596: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) { 2597: return; 2598: } elsif ($authtype eq '') { 2599: if (defined($in{'mode'})) { 2600: if ($in{'mode'} eq 'modifycourse') { 2601: if ($authnum == 1) { 2602: $authtype = '<input type="hidden" name="login" value="krb" />'; 2603: } 2604: } 2605: } 2606: } 2607: $jscall = "javascript:changed_radio('krb',$in{'formname'});"; 2608: if ($authtype eq '') { 2609: $authtype = '<input type="radio" name="login" value="krb" '. 2610: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'. 2611: $krbcheck.' />'; 2612: } 2613: if (($can_assign{'krb4'} && $can_assign{'krb5'}) || 2614: ($can_assign{'krb4'} && !$can_assign{'krb5'} && 2615: $in{'curr_authtype'} eq 'krb5') || 2616: (!$can_assign{'krb4'} && $can_assign{'krb5'} && 2617: $in{'curr_authtype'} eq 'krb4')) { 2618: $result .= &mt 2619: ('[_1] Kerberos authenticated with domain [_2] '. 2620: '[_3] Version 4 [_4] Version 5 [_5]', 2621: '<label>'.$authtype, 2622: '</label><input type="text" size="10" name="krbarg" '. 2623: 'value="'.$krbarg.'" '. 2624: 'onchange="'.$jscall.'" />', 2625: '<label><input type="radio" name="krbver" value="4" '.$check4.' />', 2626: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />', 2627: '</label>'); 2628: } elsif ($can_assign{'krb4'}) { 2629: $result .= &mt 2630: ('[_1] Kerberos authenticated with domain [_2] '. 2631: '[_3] Version 4 [_4]', 2632: '<label>'.$authtype, 2633: '</label><input type="text" size="10" name="krbarg" '. 2634: 'value="'.$krbarg.'" '. 2635: 'onchange="'.$jscall.'" />', 2636: '<label><input type="hidden" name="krbver" value="4" />', 2637: '</label>'); 2638: } elsif ($can_assign{'krb5'}) { 2639: $result .= &mt 2640: ('[_1] Kerberos authenticated with domain [_2] '. 2641: '[_3] Version 5 [_4]', 2642: '<label>'.$authtype, 2643: '</label><input type="text" size="10" name="krbarg" '. 2644: 'value="'.$krbarg.'" '. 2645: 'onchange="'.$jscall.'" />', 2646: '<label><input type="hidden" name="krbver" value="5" />', 2647: '</label>'); 2648: } 2649: return $result; 2650: } 2651: 2652: sub authform_internal{ 2653: my %in = ( 2654: formname => 'document.cu', 2655: kerb_def_dom => 'MSU.EDU', 2656: @_, 2657: ); 2658: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall); 2659: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2660: if (defined($in{'curr_authtype'})) { 2661: if ($in{'curr_authtype'} eq 'int') { 2662: if ($can_assign{'int'}) { 2663: $intcheck = 'checked="checked" '; 2664: if (defined($in{'mode'})) { 2665: if ($in{'mode'} eq 'modifyuser') { 2666: $intcheck = ''; 2667: } 2668: } 2669: if (defined($in{'curr_autharg'})) { 2670: $intarg = $in{'curr_autharg'}; 2671: } 2672: } else { 2673: $result = &mt('Currently internally authenticated.'); 2674: return $result; 2675: } 2676: } 2677: } else { 2678: if ($authnum == 1) { 2679: $authtype = '<input type="hidden" name="login" value="int" />'; 2680: } 2681: } 2682: if (!$can_assign{'int'}) { 2683: return; 2684: } elsif ($authtype eq '') { 2685: if (defined($in{'mode'})) { 2686: if ($in{'mode'} eq 'modifycourse') { 2687: if ($authnum == 1) { 2688: $authtype = '<input type="hidden" name="login" value="int" />'; 2689: } 2690: } 2691: } 2692: } 2693: $jscall = "javascript:changed_radio('int',$in{'formname'});"; 2694: if ($authtype eq '') { 2695: $authtype = '<input type="radio" name="login" value="int" '.$intcheck. 2696: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />'; 2697: } 2698: $autharg = '<input type="password" size="10" name="intarg" value="'. 2699: $intarg.'" onchange="'.$jscall.'" />'; 2700: $result = &mt 2701: ('[_1] Internally authenticated (with initial password [_2])', 2702: '<label>'.$authtype,'</label>'.$autharg); 2703: $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>'; 2704: return $result; 2705: } 2706: 2707: sub authform_local{ 2708: my %in = ( 2709: formname => 'document.cu', 2710: kerb_def_dom => 'MSU.EDU', 2711: @_, 2712: ); 2713: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall); 2714: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2715: if (defined($in{'curr_authtype'})) { 2716: if ($in{'curr_authtype'} eq 'loc') { 2717: if ($can_assign{'loc'}) { 2718: $loccheck = 'checked="checked" '; 2719: if (defined($in{'mode'})) { 2720: if ($in{'mode'} eq 'modifyuser') { 2721: $loccheck = ''; 2722: } 2723: } 2724: if (defined($in{'curr_autharg'})) { 2725: $locarg = $in{'curr_autharg'}; 2726: } 2727: } else { 2728: $result = &mt('Currently using local (institutional) authentication.'); 2729: return $result; 2730: } 2731: } 2732: } else { 2733: if ($authnum == 1) { 2734: $authtype = '<input type="hidden" name="login" value="loc" />'; 2735: } 2736: } 2737: if (!$can_assign{'loc'}) { 2738: return; 2739: } elsif ($authtype eq '') { 2740: if (defined($in{'mode'})) { 2741: if ($in{'mode'} eq 'modifycourse') { 2742: if ($authnum == 1) { 2743: $authtype = '<input type="hidden" name="login" value="loc" />'; 2744: } 2745: } 2746: } 2747: } 2748: $jscall = "javascript:changed_radio('loc',$in{'formname'});"; 2749: if ($authtype eq '') { 2750: $authtype = '<input type="radio" name="login" value="loc" '. 2751: $loccheck.' onchange="'.$jscall.'" onclick="'. 2752: $jscall.'" />'; 2753: } 2754: $autharg = '<input type="text" size="10" name="locarg" value="'. 2755: $locarg.'" onchange="'.$jscall.'" />'; 2756: $result = &mt('[_1] Local Authentication with argument [_2]', 2757: '<label>'.$authtype,'</label>'.$autharg); 2758: return $result; 2759: } 2760: 2761: sub authform_filesystem{ 2762: my %in = ( 2763: formname => 'document.cu', 2764: kerb_def_dom => 'MSU.EDU', 2765: @_, 2766: ); 2767: my ($fsyscheck,$result,$authtype,$autharg,$jscall); 2768: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 2769: if (defined($in{'curr_authtype'})) { 2770: if ($in{'curr_authtype'} eq 'fsys') { 2771: if ($can_assign{'fsys'}) { 2772: $fsyscheck = 'checked="checked" '; 2773: if (defined($in{'mode'})) { 2774: if ($in{'mode'} eq 'modifyuser') { 2775: $fsyscheck = ''; 2776: } 2777: } 2778: } else { 2779: $result = &mt('Currently Filesystem Authenticated.'); 2780: return $result; 2781: } 2782: } 2783: } else { 2784: if ($authnum == 1) { 2785: $authtype = '<input type="hidden" name="login" value="fsys" />'; 2786: } 2787: } 2788: if (!$can_assign{'fsys'}) { 2789: return; 2790: } elsif ($authtype eq '') { 2791: if (defined($in{'mode'})) { 2792: if ($in{'mode'} eq 'modifycourse') { 2793: if ($authnum == 1) { 2794: $authtype = '<input type="hidden" name="login" value="fsys" />'; 2795: } 2796: } 2797: } 2798: } 2799: $jscall = "javascript:changed_radio('fsys',$in{'formname'});"; 2800: if ($authtype eq '') { 2801: $authtype = '<input type="radio" name="login" value="fsys" '. 2802: $fsyscheck.' onchange="'.$jscall.'" onclick="'. 2803: $jscall.'" />'; 2804: } 2805: $autharg = '<input type="text" size="10" name="fsysarg" value=""'. 2806: ' onchange="'.$jscall.'" />'; 2807: $result = &mt 2808: ('[_1] Filesystem Authenticated (with initial password [_2])', 2809: '<label><input type="radio" name="login" value="fsys" '. 2810: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />', 2811: '</label><input type="password" size="10" name="fsysarg" value="" '. 2812: 'onchange="'.$jscall.'" />'); 2813: return $result; 2814: } 2815: 2816: sub get_assignable_auth { 2817: my ($dom) = @_; 2818: if ($dom eq '') { 2819: $dom = $env{'request.role.domain'}; 2820: } 2821: my %can_assign = ( 2822: krb4 => 1, 2823: krb5 => 1, 2824: int => 1, 2825: loc => 1, 2826: ); 2827: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom); 2828: if (ref($domconfig{'usercreation'}) eq 'HASH') { 2829: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') { 2830: my $authhash = $domconfig{'usercreation'}{'authtypes'}; 2831: my $context; 2832: if ($env{'request.role'} =~ /^au/) { 2833: $context = 'author'; 2834: } elsif ($env{'request.role'} =~ /^dc/) { 2835: $context = 'domain'; 2836: } elsif ($env{'request.course.id'}) { 2837: $context = 'course'; 2838: } 2839: if ($context) { 2840: if (ref($authhash->{$context}) eq 'HASH') { 2841: %can_assign = %{$authhash->{$context}}; 2842: } 2843: } 2844: } 2845: } 2846: my $authnum = 0; 2847: foreach my $key (keys(%can_assign)) { 2848: if ($can_assign{$key}) { 2849: $authnum ++; 2850: } 2851: } 2852: if ($can_assign{'krb4'} && $can_assign{'krb5'}) { 2853: $authnum --; 2854: } 2855: return ($authnum,%can_assign); 2856: } 2857: 2858: ############################################################### 2859: ## Get Kerberos Defaults for Domain ## 2860: ############################################################### 2861: ## 2862: ## Returns default kerberos version and an associated argument 2863: ## as listed in file domain.tab. If not listed, provides 2864: ## appropriate default domain and kerberos version. 2865: ## 2866: #------------------------------------------- 2867: 2868: =pod 2869: 2870: =item * &get_kerberos_defaults() 2871: 2872: get_kerberos_defaults($target_domain) returns the default kerberos 2873: version and domain. If not found, it defaults to version 4 and the 2874: domain of the server. 2875: 2876: =over 4 2877: 2878: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain); 2879: 2880: =back 2881: 2882: =back 2883: 2884: =cut 2885: 2886: #------------------------------------------- 2887: sub get_kerberos_defaults { 2888: my $domain=shift; 2889: my ($krbdef,$krbdefdom); 2890: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain); 2891: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) { 2892: $krbdef = $domdefaults{'auth_def'}; 2893: $krbdefdom = $domdefaults{'auth_arg_def'}; 2894: } else { 2895: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/; 2896: my $krbdefdom=$1; 2897: $krbdefdom=~tr/a-z/A-Z/; 2898: $krbdef = "krb4"; 2899: } 2900: return ($krbdef,$krbdefdom); 2901: } 2902: 2903: 2904: ############################################################### 2905: ## Thesaurus Functions ## 2906: ############################################################### 2907: 2908: =pod 2909: 2910: =head1 Thesaurus Functions 2911: 2912: =over 4 2913: 2914: =item * &initialize_keywords() 2915: 2916: Initializes the package variable %Keywords if it is empty. Uses the 2917: package variable $thesaurus_db_file. 2918: 2919: =cut 2920: 2921: ################################################### 2922: 2923: sub initialize_keywords { 2924: return 1 if (scalar keys(%Keywords)); 2925: # If we are here, %Keywords is empty, so fill it up 2926: # Make sure the file we need exists... 2927: if (! -e $thesaurus_db_file) { 2928: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file". 2929: " failed because it does not exist"); 2930: return 0; 2931: } 2932: # Set up the hash as a database 2933: my %thesaurus_db; 2934: if (! tie(%thesaurus_db,'GDBM_File', 2935: $thesaurus_db_file,&GDBM_READER(),0640)){ 2936: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ". 2937: $thesaurus_db_file); 2938: return 0; 2939: } 2940: # Get the average number of appearances of a word. 2941: my $avecount = $thesaurus_db{'average.count'}; 2942: # Put keywords (those that appear > average) into %Keywords 2943: while (my ($word,$data)=each (%thesaurus_db)) { 2944: my ($count,undef) = split /:/,$data; 2945: $Keywords{$word}++ if ($count > $avecount); 2946: } 2947: untie %thesaurus_db; 2948: # Remove special values from %Keywords. 2949: foreach my $value ('total.count','average.count') { 2950: delete($Keywords{$value}) if (exists($Keywords{$value})); 2951: } 2952: return 1; 2953: } 2954: 2955: ################################################### 2956: 2957: =pod 2958: 2959: =item * &keyword($word) 2960: 2961: Returns true if $word is a keyword. A keyword is a word that appears more 2962: than the average number of times in the thesaurus database. Calls 2963: &initialize_keywords 2964: 2965: =cut 2966: 2967: ################################################### 2968: 2969: sub keyword { 2970: return if (!&initialize_keywords()); 2971: my $word=lc(shift()); 2972: $word=~s/\W//g; 2973: return exists($Keywords{$word}); 2974: } 2975: 2976: ############################################################### 2977: 2978: =pod 2979: 2980: =item * &get_related_words() 2981: 2982: Look up a word in the thesaurus. Takes a scalar argument and returns 2983: an array of words. If the keyword is not in the thesaurus, an empty array 2984: will be returned. The order of the words returned is determined by the 2985: database which holds them. 2986: 2987: Uses global $thesaurus_db_file. 2988: 2989: 2990: =cut 2991: 2992: ############################################################### 2993: sub get_related_words { 2994: my $keyword = shift; 2995: my %thesaurus_db; 2996: if (! -e $thesaurus_db_file) { 2997: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ". 2998: "failed because the file does not exist"); 2999: return (); 3000: } 3001: if (! tie(%thesaurus_db,'GDBM_File', 3002: $thesaurus_db_file,&GDBM_READER(),0640)){ 3003: return (); 3004: } 3005: my @Words=(); 3006: my $count=0; 3007: if (exists($thesaurus_db{$keyword})) { 3008: # The first element is the number of times 3009: # the word appears. We do not need it now. 3010: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword})); 3011: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]); 3012: my $threshold=$mostfrequentcount/10; 3013: foreach my $possibleword (@RelatedWords) { 3014: my ($word,$wordcount)=split(/\,/,$possibleword); 3015: if ($wordcount>$threshold) { 3016: push(@Words,$word); 3017: $count++; 3018: if ($count>10) { last; } 3019: } 3020: } 3021: } 3022: untie %thesaurus_db; 3023: return @Words; 3024: } 3025: ############################################################### 3026: # 3027: # Spell checking 3028: # 3029: 3030: =pod 3031: 3032: =head1 Spell checking 3033: 3034: =over 4 3035: 3036: =item * &check_spelling($wordlist $language) 3037: 3038: Takes a string containing words and feeds it to an external 3039: spellcheck program via a pipeline. Returns a string containing 3040: them mis-spelled words. 3041: 3042: Parameters: 3043: 3044: =over 4 3045: 3046: =item - $wordlist 3047: 3048: String that will be fed into the spellcheck program. 3049: 3050: =item - $language 3051: 3052: Language string that specifies the language for which the spell 3053: check will be performed. 3054: 3055: =back 3056: 3057: =back 3058: 3059: Note: This sub assumes that aspell is installed. 3060: 3061: 3062: =cut 3063: 3064: 3065: =pod 3066: 3067: =back 3068: 3069: =cut 3070: 3071: sub check_spelling { 3072: my ($wordlist, $language) = @_; 3073: my @misspellings; 3074: 3075: # Generate the speller and set the langauge. 3076: # if explicitly selected: 3077: 3078: my $speller = Text::Aspell->new; 3079: if ($language) { 3080: $speller->set_option('lang', $language); 3081: } 3082: 3083: # Turn the word list into an array of words by splittingon whitespace 3084: 3085: my @words = split(/\s+/, $wordlist); 3086: 3087: foreach my $word (@words) { 3088: if(! $speller->check($word)) { 3089: push(@misspellings, $word); 3090: } 3091: } 3092: return join(' ', @misspellings); 3093: 3094: } 3095: 3096: # -------------------------------------------------------------- Plaintext name 3097: =pod 3098: 3099: =head1 User Name Functions 3100: 3101: =over 4 3102: 3103: =item * &plainname($uname,$udom,$first) 3104: 3105: Takes a users logon name and returns it as a string in 3106: "first middle last generation" form 3107: if $first is set to 'lastname' then it returns it as 3108: 'lastname generation, firstname middlename' if their is a lastname 3109: 3110: =cut 3111: 3112: 3113: ############################################################### 3114: sub plainname { 3115: my ($uname,$udom,$first)=@_; 3116: return if (!defined($uname) || !defined($udom)); 3117: my %names=&getnames($uname,$udom); 3118: my $name=&Apache::lonnet::format_name($names{'firstname'}, 3119: $names{'middlename'}, 3120: $names{'lastname'}, 3121: $names{'generation'},$first); 3122: $name=~s/^\s+//; 3123: $name=~s/\s+$//; 3124: $name=~s/\s+/ /g; 3125: if ($name !~ /\S/) { $name=$uname.':'.$udom; } 3126: return $name; 3127: } 3128: 3129: # -------------------------------------------------------------------- Nickname 3130: =pod 3131: 3132: =item * &nickname($uname,$udom) 3133: 3134: Gets a users name and returns it as a string as 3135: 3136: ""nickname"" 3137: 3138: if the user has a nickname or 3139: 3140: "first middle last generation" 3141: 3142: if the user does not 3143: 3144: =cut 3145: 3146: sub nickname { 3147: my ($uname,$udom)=@_; 3148: return if (!defined($uname) || !defined($udom)); 3149: my %names=&getnames($uname,$udom); 3150: my $name=$names{'nickname'}; 3151: if ($name) { 3152: $name='"'.$name.'"'; 3153: } else { 3154: $name=$names{'firstname'}.' '.$names{'middlename'}.' '. 3155: $names{'lastname'}.' '.$names{'generation'}; 3156: $name=~s/\s+$//; 3157: $name=~s/\s+/ /g; 3158: } 3159: return $name; 3160: } 3161: 3162: sub getnames { 3163: my ($uname,$udom)=@_; 3164: return if (!defined($uname) || !defined($udom)); 3165: if ($udom eq 'public' && $uname eq 'public') { 3166: return ('lastname' => &mt('Public')); 3167: } 3168: my $id=$uname.':'.$udom; 3169: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id); 3170: if ($cached) { 3171: return %{$names}; 3172: } else { 3173: my %loadnames=&Apache::lonnet::get('environment', 3174: ['firstname','middlename','lastname','generation','nickname'], 3175: $udom,$uname); 3176: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames); 3177: return %loadnames; 3178: } 3179: } 3180: 3181: # -------------------------------------------------------------------- getemails 3182: 3183: =pod 3184: 3185: =item * &getemails($uname,$udom) 3186: 3187: Gets a user's email information and returns it as a hash with keys: 3188: notification, critnotification, permanentemail 3189: 3190: For notification and critnotification, values are comma-separated lists 3191: of e-mail addresses; for permanentemail, value is a single e-mail address. 3192: 3193: 3194: =cut 3195: 3196: 3197: sub getemails { 3198: my ($uname,$udom)=@_; 3199: if ($udom eq 'public' && $uname eq 'public') { 3200: return; 3201: } 3202: if (!$udom) { $udom=$env{'user.domain'}; } 3203: if (!$uname) { $uname=$env{'user.name'}; } 3204: my $id=$uname.':'.$udom; 3205: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id); 3206: if ($cached) { 3207: return %{$names}; 3208: } else { 3209: my %loadnames=&Apache::lonnet::get('environment', 3210: ['notification','critnotification', 3211: 'permanentemail'], 3212: $udom,$uname); 3213: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames); 3214: return %loadnames; 3215: } 3216: } 3217: 3218: sub flush_email_cache { 3219: my ($uname,$udom)=@_; 3220: if (!$udom) { $udom =$env{'user.domain'}; } 3221: if (!$uname) { $uname=$env{'user.name'}; } 3222: return if ($udom eq 'public' && $uname eq 'public'); 3223: my $id=$uname.':'.$udom; 3224: &Apache::lonnet::devalidate_cache_new('emailscache',$id); 3225: } 3226: 3227: # -------------------------------------------------------------------- getlangs 3228: 3229: =pod 3230: 3231: =item * &getlangs($uname,$udom) 3232: 3233: Gets a user's language preference and returns it as a hash with key: 3234: language. 3235: 3236: =cut 3237: 3238: 3239: sub getlangs { 3240: my ($uname,$udom) = @_; 3241: if (!$udom) { $udom =$env{'user.domain'}; } 3242: if (!$uname) { $uname=$env{'user.name'}; } 3243: my $id=$uname.':'.$udom; 3244: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id); 3245: if ($cached) { 3246: return %{$langs}; 3247: } else { 3248: my %loadlangs=&Apache::lonnet::get('environment',['languages'], 3249: $udom,$uname); 3250: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs); 3251: return %loadlangs; 3252: } 3253: } 3254: 3255: sub flush_langs_cache { 3256: my ($uname,$udom)=@_; 3257: if (!$udom) { $udom =$env{'user.domain'}; } 3258: if (!$uname) { $uname=$env{'user.name'}; } 3259: return if ($udom eq 'public' && $uname eq 'public'); 3260: my $id=$uname.':'.$udom; 3261: &Apache::lonnet::devalidate_cache_new('userlangs',$id); 3262: } 3263: 3264: # ------------------------------------------------------------------ Screenname 3265: 3266: =pod 3267: 3268: =item * &screenname($uname,$udom) 3269: 3270: Gets a users screenname and returns it as a string 3271: 3272: =cut 3273: 3274: sub screenname { 3275: my ($uname,$udom)=@_; 3276: if ($uname eq $env{'user.name'} && 3277: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};} 3278: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname); 3279: return $names{'screenname'}; 3280: } 3281: 3282: 3283: # ------------------------------------------------------------- Confirm Wrapper 3284: =pod 3285: 3286: =item confirmwrapper 3287: 3288: Wrap messages about completion of operation in box 3289: 3290: =cut 3291: 3292: sub confirmwrapper { 3293: my ($message)=@_; 3294: if ($message) { 3295: return "\n".'<div class="LC_confirm_box">'."\n" 3296: .$message."\n" 3297: .'</div>'."\n"; 3298: } else { 3299: return $message; 3300: } 3301: } 3302: 3303: # ------------------------------------------------------------- Message Wrapper 3304: 3305: sub messagewrapper { 3306: my ($link,$username,$domain,$subject,$text)=@_; 3307: return 3308: '<a href="/adm/email?compose=individual&'. 3309: 'recname='.$username.'&recdom='.$domain. 3310: '&subject='.&escape($subject).'&text='.&escape($text).'" '. 3311: 'title="'.&mt('Send message').'">'.$link.'</a>'; 3312: } 3313: 3314: # --------------------------------------------------------------- Notes Wrapper 3315: 3316: sub noteswrapper { 3317: my ($link,$un,$do)=@_; 3318: return 3319: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>"; 3320: } 3321: 3322: # ------------------------------------------------------------- Aboutme Wrapper 3323: 3324: sub aboutmewrapper { 3325: my ($link,$username,$domain,$target,$class)=@_; 3326: if (!defined($username) && !defined($domain)) { 3327: return; 3328: } 3329: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'. 3330: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>'; 3331: } 3332: 3333: # ------------------------------------------------------------ Syllabus Wrapper 3334: 3335: sub syllabuswrapper { 3336: my ($linktext,$coursedir,$domain)=@_; 3337: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>}; 3338: } 3339: 3340: # ----------------------------------------------------------------------------- 3341: 3342: sub track_student_link { 3343: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_; 3344: my $link ="/adm/trackstudent?"; 3345: my $title = 'View recent activity'; 3346: if (defined($sname) && $sname !~ /^\s*$/ && 3347: defined($sdom) && $sdom !~ /^\s*$/) { 3348: $link .= "selected_student=$sname:$sdom"; 3349: $title .= ' of this student'; 3350: } 3351: if (defined($target) && $target !~ /^\s*$/) { 3352: $target = qq{target="$target"}; 3353: } else { 3354: $target = ''; 3355: } 3356: if ($start) { $link.='&start='.$start; } 3357: if ($only_body) { $link .= '&only_body=1'; } 3358: $title = &mt($title); 3359: $linktext = &mt($linktext); 3360: return qq{<a href="$link" title="$title" $target>$linktext</a>}. 3361: &help_open_topic('View_recent_activity'); 3362: } 3363: 3364: sub slot_reservations_link { 3365: my ($linktext,$sname,$sdom,$target) = @_; 3366: my $link ="/adm/slotrequest?command=showresv&origin=aboutme"; 3367: my $title = 'View slot reservation history'; 3368: if (defined($sname) && $sname !~ /^\s*$/ && 3369: defined($sdom) && $sdom !~ /^\s*$/) { 3370: $link .= "&uname=$sname&udom=$sdom"; 3371: $title .= ' of this student'; 3372: } 3373: if (defined($target) && $target !~ /^\s*$/) { 3374: $target = qq{target="$target"}; 3375: } else { 3376: $target = ''; 3377: } 3378: $title = &mt($title); 3379: $linktext = &mt($linktext); 3380: return qq{<a href="$link" title="$title" $target>$linktext</a>}; 3381: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History'); 3382: 3383: } 3384: 3385: # ===================================================== Display a student photo 3386: 3387: 3388: sub student_image_tag { 3389: my ($domain,$user)=@_; 3390: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg'); 3391: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) { 3392: return '<img src="'.$imgsrc.'" align="right" />'; 3393: } else { 3394: return ''; 3395: } 3396: } 3397: 3398: =pod 3399: 3400: =back 3401: 3402: =head1 Access .tab File Data 3403: 3404: =over 4 3405: 3406: =item * &languageids() 3407: 3408: returns list of all language ids 3409: 3410: =cut 3411: 3412: sub languageids { 3413: return sort(keys(%language)); 3414: } 3415: 3416: =pod 3417: 3418: =item * &languagedescription() 3419: 3420: returns description of a specified language id 3421: 3422: =cut 3423: 3424: sub languagedescription { 3425: my $code=shift; 3426: return ($supported_language{$code}?'* ':''). 3427: $language{$code}. 3428: ($supported_language{$code}?' ('.&mt('interface available').')':''); 3429: } 3430: 3431: =pod 3432: 3433: =item * &plainlanguagedescription 3434: 3435: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)') 3436: and the language character encoding (e.g. ISO) separated by a ' - ' string. 3437: 3438: =cut 3439: 3440: sub plainlanguagedescription { 3441: my $code=shift; 3442: return $language{$code}; 3443: } 3444: 3445: =pod 3446: 3447: =item * &supportedlanguagecode 3448: 3449: Returns the supported language code (e.g. sptutf maps to pt) given a language 3450: code. 3451: 3452: =cut 3453: 3454: sub supportedlanguagecode { 3455: my $code=shift; 3456: return $supported_language{$code}; 3457: } 3458: 3459: =pod 3460: 3461: =item * &latexlanguage() 3462: 3463: Given a language key code returns the correspondnig language to use 3464: to select the correct hyphenation on LaTeX printouts. This is undef if there 3465: is no supported hyphenation for the language code. 3466: 3467: =cut 3468: 3469: sub latexlanguage { 3470: my $code = shift; 3471: return $latex_language{$code}; 3472: } 3473: 3474: =pod 3475: 3476: =item * &latexhyphenation() 3477: 3478: Same as above but what's supplied is the language as it might be stored 3479: in the metadata. 3480: 3481: =cut 3482: 3483: sub latexhyphenation { 3484: my $key = shift; 3485: return $latex_language_bykey{$key}; 3486: } 3487: 3488: =pod 3489: 3490: =item * ©rightids() 3491: 3492: returns list of all copyrights 3493: 3494: =cut 3495: 3496: sub copyrightids { 3497: return sort(keys(%cprtag)); 3498: } 3499: 3500: =pod 3501: 3502: =item * ©rightdescription() 3503: 3504: returns description of a specified copyright id 3505: 3506: =cut 3507: 3508: sub copyrightdescription { 3509: return &mt($cprtag{shift(@_)}); 3510: } 3511: 3512: =pod 3513: 3514: =item * &source_copyrightids() 3515: 3516: returns list of all source copyrights 3517: 3518: =cut 3519: 3520: sub source_copyrightids { 3521: return sort(keys(%scprtag)); 3522: } 3523: 3524: =pod 3525: 3526: =item * &source_copyrightdescription() 3527: 3528: returns description of a specified source copyright id 3529: 3530: =cut 3531: 3532: sub source_copyrightdescription { 3533: return &mt($scprtag{shift(@_)}); 3534: } 3535: 3536: =pod 3537: 3538: =item * &filecategories() 3539: 3540: returns list of all file categories 3541: 3542: =cut 3543: 3544: sub filecategories { 3545: return sort(keys(%category_extensions)); 3546: } 3547: 3548: =pod 3549: 3550: =item * &filecategorytypes() 3551: 3552: returns list of file types belonging to a given file 3553: category 3554: 3555: =cut 3556: 3557: sub filecategorytypes { 3558: my ($cat) = @_; 3559: return @{$category_extensions{lc($cat)}}; 3560: } 3561: 3562: =pod 3563: 3564: =item * &fileembstyle() 3565: 3566: returns embedding style for a specified file type 3567: 3568: =cut 3569: 3570: sub fileembstyle { 3571: return $fe{lc(shift(@_))}; 3572: } 3573: 3574: sub filemimetype { 3575: return $fm{lc(shift(@_))}; 3576: } 3577: 3578: 3579: sub filecategoryselect { 3580: my ($name,$value)=@_; 3581: return &select_form($value,$name, 3582: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))}); 3583: } 3584: 3585: =pod 3586: 3587: =item * &filedescription() 3588: 3589: returns description for a specified file type 3590: 3591: =cut 3592: 3593: sub filedescription { 3594: my $file_description = $fd{lc(shift())}; 3595: $file_description =~ s:([\[\]]):~$1:g; 3596: return &mt($file_description); 3597: } 3598: 3599: =pod 3600: 3601: =item * &filedescriptionex() 3602: 3603: returns description for a specified file type with 3604: extra formatting 3605: 3606: =cut 3607: 3608: sub filedescriptionex { 3609: my $ex=shift; 3610: my $file_description = $fd{lc($ex)}; 3611: $file_description =~ s:([\[\]]):~$1:g; 3612: return '.'.$ex.' '.&mt($file_description); 3613: } 3614: 3615: # End of .tab access 3616: =pod 3617: 3618: =back 3619: 3620: =cut 3621: 3622: # ------------------------------------------------------------------ File Types 3623: sub fileextensions { 3624: return sort(keys(%fe)); 3625: } 3626: 3627: # ----------------------------------------------------------- Display Languages 3628: # returns a hash with all desired display languages 3629: # 3630: 3631: sub display_languages { 3632: my %languages=(); 3633: foreach my $lang (&Apache::lonlocal::preferred_languages()) { 3634: $languages{$lang}=1; 3635: } 3636: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']); 3637: if ($env{'form.displaylanguage'}) { 3638: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) { 3639: $languages{$lang}=1; 3640: } 3641: } 3642: return %languages; 3643: } 3644: 3645: sub languages { 3646: my ($possible_langs) = @_; 3647: my @preferred_langs = &Apache::lonlocal::preferred_languages(); 3648: if (!ref($possible_langs)) { 3649: if( wantarray ) { 3650: return @preferred_langs; 3651: } else { 3652: return $preferred_langs[0]; 3653: } 3654: } 3655: my %possibilities = map { $_ => 1 } (@$possible_langs); 3656: my @preferred_possibilities; 3657: foreach my $preferred_lang (@preferred_langs) { 3658: if (exists($possibilities{$preferred_lang})) { 3659: push(@preferred_possibilities, $preferred_lang); 3660: } 3661: } 3662: if( wantarray ) { 3663: return @preferred_possibilities; 3664: } 3665: return $preferred_possibilities[0]; 3666: } 3667: 3668: sub user_lang { 3669: my ($touname,$toudom,$fromcid) = @_; 3670: my @userlangs; 3671: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) { 3672: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/, 3673: $env{'course.'.$fromcid.'.languages'})); 3674: } else { 3675: my %langhash = &getlangs($touname,$toudom); 3676: if ($langhash{'languages'} ne '') { 3677: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'}); 3678: } else { 3679: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom); 3680: if ($domdefs{'lang_def'} ne '') { 3681: @userlangs = ($domdefs{'lang_def'}); 3682: } 3683: } 3684: } 3685: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs); 3686: my $user_lh = Apache::localize->get_handle(@languages); 3687: return $user_lh; 3688: } 3689: 3690: 3691: ############################################################### 3692: ## Student Answer Attempts ## 3693: ############################################################### 3694: 3695: =pod 3696: 3697: =head1 Alternate Problem Views 3698: 3699: =over 4 3700: 3701: =item * &get_previous_attempt($symb, $username, $domain, $course, 3702: $getattempt, $regexp, $gradesub) 3703: 3704: Return string with previous attempt on problem. Arguments: 3705: 3706: =over 4 3707: 3708: =item * $symb: Problem, including path 3709: 3710: =item * $username: username of the desired student 3711: 3712: =item * $domain: domain of the desired student 3713: 3714: =item * $course: Course ID 3715: 3716: =item * $getattempt: Leave blank for all attempts, otherwise put 3717: something 3718: 3719: =item * $regexp: if string matches this regexp, the string will be 3720: sent to $gradesub 3721: 3722: =item * $gradesub: routine that processes the string if it matches $regexp 3723: 3724: =back 3725: 3726: The output string is a table containing all desired attempts, if any. 3727: 3728: =cut 3729: 3730: sub get_previous_attempt { 3731: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_; 3732: my $prevattempts=''; 3733: no strict 'refs'; 3734: if ($symb) { 3735: my (%returnhash)= 3736: &Apache::lonnet::restore($symb,$course,$domain,$username); 3737: if ($returnhash{'version'}) { 3738: my %lasthash=(); 3739: my $version; 3740: for ($version=1;$version<=$returnhash{'version'};$version++) { 3741: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) { 3742: $lasthash{$key}=$returnhash{$version.':'.$key}; 3743: } 3744: } 3745: $prevattempts=&start_data_table().&start_data_table_header_row(); 3746: $prevattempts.='<th>'.&mt('History').'</th>'; 3747: my (%typeparts,%lasthidden); 3748: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'}); 3749: foreach my $key (sort(keys(%lasthash))) { 3750: my ($ign,@parts) = split(/\./,$key); 3751: if ($#parts > 0) { 3752: my $data=$parts[-1]; 3753: next if ($data eq 'foilorder'); 3754: pop(@parts); 3755: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>'; 3756: if ($data eq 'type') { 3757: unless ($showsurv) { 3758: my $id = join(',',@parts); 3759: $typeparts{$ign.'.'.$id} = $lasthash{$key}; 3760: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) { 3761: $lasthidden{$ign.'.'.$id} = 1; 3762: } 3763: } 3764: } 3765: } else { 3766: if ($#parts == 0) { 3767: $prevattempts.='<th>'.$parts[0].'</th>'; 3768: } else { 3769: $prevattempts.='<th>'.$ign.'</th>'; 3770: } 3771: } 3772: } 3773: $prevattempts.=&end_data_table_header_row(); 3774: if ($getattempt eq '') { 3775: for ($version=1;$version<=$returnhash{'version'};$version++) { 3776: my @hidden; 3777: if (%typeparts) { 3778: foreach my $id (keys(%typeparts)) { 3779: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) { 3780: push(@hidden,$id); 3781: } 3782: } 3783: } 3784: $prevattempts.=&start_data_table_row(). 3785: '<td>'.&mt('Transaction [_1]',$version).'</td>'; 3786: if (@hidden) { 3787: foreach my $key (sort(keys(%lasthash))) { 3788: next if ($key =~ /\.foilorder$/); 3789: my $hide; 3790: foreach my $id (@hidden) { 3791: if ($key =~ /^\Q$id\E/) { 3792: $hide = 1; 3793: last; 3794: } 3795: } 3796: if ($hide) { 3797: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/); 3798: if (($data eq 'award') || ($data eq 'awarddetail')) { 3799: my $value = &format_previous_attempt_value($key, 3800: $returnhash{$version.':'.$key}); 3801: $prevattempts.='<td>'.$value.' </td>'; 3802: } else { 3803: $prevattempts.='<td> </td>'; 3804: } 3805: } else { 3806: if ($key =~ /\./) { 3807: my $value = &format_previous_attempt_value($key, 3808: $returnhash{$version.':'.$key}); 3809: $prevattempts.='<td>'.$value.' </td>'; 3810: } else { 3811: $prevattempts.='<td> </td>'; 3812: } 3813: } 3814: } 3815: } else { 3816: foreach my $key (sort(keys(%lasthash))) { 3817: next if ($key =~ /\.foilorder$/); 3818: my $value = &format_previous_attempt_value($key, 3819: $returnhash{$version.':'.$key}); 3820: $prevattempts.='<td>'.$value.' </td>'; 3821: } 3822: } 3823: $prevattempts.=&end_data_table_row(); 3824: } 3825: } 3826: my @currhidden = keys(%lasthidden); 3827: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>'; 3828: foreach my $key (sort(keys(%lasthash))) { 3829: next if ($key =~ /\.foilorder$/); 3830: if (%typeparts) { 3831: my $hidden; 3832: foreach my $id (@currhidden) { 3833: if ($key =~ /^\Q$id\E/) { 3834: $hidden = 1; 3835: last; 3836: } 3837: } 3838: if ($hidden) { 3839: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/); 3840: if (($data eq 'award') || ($data eq 'awarddetail')) { 3841: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3842: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3843: $value = &$gradesub($value); 3844: } 3845: $prevattempts.='<td>'.$value.' </td>'; 3846: } else { 3847: $prevattempts.='<td> </td>'; 3848: } 3849: } else { 3850: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3851: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3852: $value = &$gradesub($value); 3853: } 3854: $prevattempts.='<td>'.$value.' </td>'; 3855: } 3856: } else { 3857: my $value = &format_previous_attempt_value($key,$lasthash{$key}); 3858: if ($key =~/$regexp$/ && (defined &$gradesub)) { 3859: $value = &$gradesub($value); 3860: } 3861: $prevattempts.='<td>'.$value.' </td>'; 3862: } 3863: } 3864: $prevattempts.= &end_data_table_row().&end_data_table(); 3865: } else { 3866: $prevattempts= 3867: &start_data_table().&start_data_table_row(). 3868: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'. 3869: &end_data_table_row().&end_data_table(); 3870: } 3871: } else { 3872: $prevattempts= 3873: &start_data_table().&start_data_table_row(). 3874: '<td>'.&mt('No data.').'</td>'. 3875: &end_data_table_row().&end_data_table(); 3876: } 3877: } 3878: 3879: sub format_previous_attempt_value { 3880: my ($key,$value) = @_; 3881: if (($key =~ /timestamp/) || ($key=~/duedate/)) { 3882: $value = &Apache::lonlocal::locallocaltime($value); 3883: } elsif (ref($value) eq 'ARRAY') { 3884: $value = '('.join(', ', @{ $value }).')'; 3885: } elsif ($key =~ /answerstring$/) { 3886: my %answers = &Apache::lonnet::str2hash($value); 3887: my @anskeys = sort(keys(%answers)); 3888: if (@anskeys == 1) { 3889: my $answer = $answers{$anskeys[0]}; 3890: if ($answer =~ m{\0}) { 3891: $answer =~ s{\0}{,}g; 3892: } 3893: my $tag_internal_answer_name = 'INTERNAL'; 3894: if ($anskeys[0] eq $tag_internal_answer_name) { 3895: $value = $answer; 3896: } else { 3897: $value = $anskeys[0].'='.$answer; 3898: } 3899: } else { 3900: foreach my $ans (@anskeys) { 3901: my $answer = $answers{$ans}; 3902: if ($answer =~ m{\0}) { 3903: $answer =~ s{\0}{,}g; 3904: } 3905: $value .= $ans.'='.$answer.'<br />';; 3906: } 3907: } 3908: } else { 3909: $value = &unescape($value); 3910: } 3911: return $value; 3912: } 3913: 3914: 3915: sub relative_to_absolute { 3916: my ($url,$output)=@_; 3917: my $parser=HTML::TokeParser->new(\$output); 3918: my $token; 3919: my $thisdir=$url; 3920: my @rlinks=(); 3921: while ($token=$parser->get_token) { 3922: if ($token->[0] eq 'S') { 3923: if ($token->[1] eq 'a') { 3924: if ($token->[2]->{'href'}) { 3925: $rlinks[$#rlinks+1]=$token->[2]->{'href'}; 3926: } 3927: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) { 3928: $rlinks[$#rlinks+1]=$token->[2]->{'src'}; 3929: } elsif ($token->[1] eq 'base') { 3930: $thisdir=$token->[2]->{'href'}; 3931: } 3932: } 3933: } 3934: $thisdir=~s-/[^/]*$--; 3935: foreach my $link (@rlinks) { 3936: unless (($link=~/^https?\:\/\//i) || 3937: ($link=~/^\//) || 3938: ($link=~/^javascript:/i) || 3939: ($link=~/^mailto:/i) || 3940: ($link=~/^\#/)) { 3941: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link); 3942: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/; 3943: } 3944: } 3945: # -------------------------------------------------- Deal with Applet codebases 3946: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei; 3947: return $output; 3948: } 3949: 3950: =pod 3951: 3952: =item * &get_student_view() 3953: 3954: show a snapshot of what student was looking at 3955: 3956: =cut 3957: 3958: sub get_student_view { 3959: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_; 3960: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb); 3961: my (%form); 3962: my @elements=('symb','courseid','domain','username'); 3963: foreach my $element (@elements) { 3964: $form{'grade_'.$element}=eval '$'.$element #' 3965: } 3966: if (defined($moreenv)) { 3967: %form=(%form,%{$moreenv}); 3968: } 3969: if (defined($target)) { $form{'grade_target'} = $target; } 3970: $feedurl=&Apache::lonnet::clutter($feedurl); 3971: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form); 3972: $userview=~s/\<body[^\>]*\>//gi; 3973: $userview=~s/\<\/body\>//gi; 3974: $userview=~s/\<html\>//gi; 3975: $userview=~s/\<\/html\>//gi; 3976: $userview=~s/\<head\>//gi; 3977: $userview=~s/\<\/head\>//gi; 3978: $userview=~s/action\s*\=/would_be_action\=/gi; 3979: $userview=&relative_to_absolute($feedurl,$userview); 3980: if (wantarray) { 3981: return ($userview,$response); 3982: } else { 3983: return $userview; 3984: } 3985: } 3986: 3987: sub get_student_view_with_retries { 3988: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_; 3989: 3990: my $ok = 0; # True if we got a good response. 3991: my $content; 3992: my $response; 3993: 3994: # Try to get the student_view done. within the retries count: 3995: 3996: do { 3997: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv); 3998: $ok = $response->is_success; 3999: if (!$ok) { 4000: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message); 4001: } 4002: $retries--; 4003: } while (!$ok && ($retries > 0)); 4004: 4005: if (!$ok) { 4006: $content = ''; # On error return an empty content. 4007: } 4008: if (wantarray) { 4009: return ($content, $response); 4010: } else { 4011: return $content; 4012: } 4013: } 4014: 4015: =pod 4016: 4017: =item * &get_student_answers() 4018: 4019: show a snapshot of how student was answering problem 4020: 4021: =cut 4022: 4023: sub get_student_answers { 4024: my ($symb,$username,$domain,$courseid,%form) = @_; 4025: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb); 4026: my (%moreenv); 4027: my @elements=('symb','courseid','domain','username'); 4028: foreach my $element (@elements) { 4029: $moreenv{'grade_'.$element}=eval '$'.$element #' 4030: } 4031: $moreenv{'grade_target'}='answer'; 4032: %moreenv=(%form,%moreenv); 4033: $feedurl = &Apache::lonnet::clutter($feedurl); 4034: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv); 4035: return $userview; 4036: } 4037: 4038: =pod 4039: 4040: =item * &submlink() 4041: 4042: Inputs: $text $uname $udom $symb $target 4043: 4044: Returns: A link to grades.pm such as to see the SUBM view of a student 4045: 4046: =cut 4047: 4048: ############################################### 4049: sub submlink { 4050: my ($text,$uname,$udom,$symb,$target)=@_; 4051: if (!($uname && $udom)) { 4052: (my $cursymb, my $courseid,$udom,$uname)= 4053: &Apache::lonnet::whichuser($symb); 4054: if (!$symb) { $symb=$cursymb; } 4055: } 4056: if (!$symb) { $symb=&Apache::lonnet::symbread(); } 4057: $symb=&escape($symb); 4058: if ($target) { $target=" target=\"$target\""; } 4059: return 4060: '<a href="/adm/grades?command=submission'. 4061: '&symb='.$symb. 4062: '&student='.$uname. 4063: '&userdom='.$udom.'"'. 4064: $target.'>'.$text.'</a>'; 4065: } 4066: ############################################## 4067: 4068: =pod 4069: 4070: =item * &pgrdlink() 4071: 4072: Inputs: $text $uname $udom $symb $target 4073: 4074: Returns: A link to grades.pm such as to see the PGRD view of a student 4075: 4076: =cut 4077: 4078: ############################################### 4079: sub pgrdlink { 4080: my $link=&submlink(@_); 4081: $link=~s/(&command=submission)/$1&showgrading=yes/; 4082: return $link; 4083: } 4084: ############################################## 4085: 4086: =pod 4087: 4088: =item * &pprmlink() 4089: 4090: Inputs: $text $uname $udom $symb $target 4091: 4092: Returns: A link to parmset.pm such as to see the PPRM view of a 4093: student and a specific resource 4094: 4095: =cut 4096: 4097: ############################################### 4098: sub pprmlink { 4099: my ($text,$uname,$udom,$symb,$target)=@_; 4100: if (!($uname && $udom)) { 4101: (my $cursymb, my $courseid,$udom,$uname)= 4102: &Apache::lonnet::whichuser($symb); 4103: if (!$symb) { $symb=$cursymb; } 4104: } 4105: if (!$symb) { $symb=&Apache::lonnet::symbread(); } 4106: $symb=&escape($symb); 4107: if ($target) { $target="target=\"$target\""; } 4108: return '<a href="/adm/parmset?command=set&'. 4109: 'symb='.$symb.'&uname='.$uname. 4110: '&udom='.$udom.'" '.$target.'>'.$text.'</a>'; 4111: } 4112: ############################################## 4113: 4114: =pod 4115: 4116: =back 4117: 4118: =cut 4119: 4120: ############################################### 4121: 4122: 4123: sub timehash { 4124: my ($thistime) = @_; 4125: my $timezone = &Apache::lonlocal::gettimezone(); 4126: my $dt = DateTime->from_epoch(epoch => $thistime) 4127: ->set_time_zone($timezone); 4128: my $wday = $dt->day_of_week(); 4129: if ($wday == 7) { $wday = 0; } 4130: return ( 'second' => $dt->second(), 4131: 'minute' => $dt->minute(), 4132: 'hour' => $dt->hour(), 4133: 'day' => $dt->day_of_month(), 4134: 'month' => $dt->month(), 4135: 'year' => $dt->year(), 4136: 'weekday' => $wday, 4137: 'dayyear' => $dt->day_of_year(), 4138: 'dlsav' => $dt->is_dst() ); 4139: } 4140: 4141: sub utc_string { 4142: my ($date)=@_; 4143: return strftime("%Y%m%dT%H%M%SZ",gmtime($date)); 4144: } 4145: 4146: sub maketime { 4147: my %th=@_; 4148: my ($epoch_time,$timezone,$dt); 4149: $timezone = &Apache::lonlocal::gettimezone(); 4150: eval { 4151: $dt = DateTime->new( year => $th{'year'}, 4152: month => $th{'month'}, 4153: day => $th{'day'}, 4154: hour => $th{'hour'}, 4155: minute => $th{'minute'}, 4156: second => $th{'second'}, 4157: time_zone => $timezone, 4158: ); 4159: }; 4160: if (!$@) { 4161: $epoch_time = $dt->epoch; 4162: if ($epoch_time) { 4163: return $epoch_time; 4164: } 4165: } 4166: return POSIX::mktime( 4167: ($th{'seconds'},$th{'minutes'},$th{'hours'}, 4168: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1)); 4169: } 4170: 4171: ######################################### 4172: 4173: sub findallcourses { 4174: my ($roles,$uname,$udom) = @_; 4175: my %roles; 4176: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; } 4177: my %courses; 4178: my $now=time; 4179: if (!defined($uname)) { 4180: $uname = $env{'user.name'}; 4181: } 4182: if (!defined($udom)) { 4183: $udom = $env{'user.domain'}; 4184: } 4185: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) { 4186: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname); 4187: if (!%roles) { 4188: %roles = ( 4189: cc => 1, 4190: co => 1, 4191: in => 1, 4192: ep => 1, 4193: ta => 1, 4194: cr => 1, 4195: st => 1, 4196: ); 4197: } 4198: foreach my $entry (keys(%roleshash)) { 4199: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry}); 4200: if ($trole =~ /^cr/) { 4201: next if (!exists($roles{$trole}) && !exists($roles{'cr'})); 4202: } else { 4203: next if (!exists($roles{$trole})); 4204: } 4205: if ($tend) { 4206: next if ($tend < $now); 4207: } 4208: if ($tstart) { 4209: next if ($tstart > $now); 4210: } 4211: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role); 4212: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry); 4213: my $value = $trole.'/'.$cdom.'/'; 4214: if ($secpart eq '') { 4215: ($cnum,$role) = split(/_/,$cnumpart); 4216: $sec = 'none'; 4217: $value .= $cnum.'/'; 4218: } else { 4219: $cnum = $cnumpart; 4220: ($sec,$role) = split(/_/,$secpart); 4221: $value .= $cnum.'/'.$sec; 4222: } 4223: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') { 4224: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) { 4225: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value); 4226: } 4227: } else { 4228: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value); 4229: } 4230: } 4231: } else { 4232: foreach my $key (keys(%env)) { 4233: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} || 4234: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) { 4235: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4); 4236: next if ($role eq 'ca' || $role eq 'aa'); 4237: next if (%roles && !exists($roles{$role})); 4238: my ($starttime,$endtime)=split(/\./,$env{$key}); 4239: my $active=1; 4240: if ($starttime) { 4241: if ($now<$starttime) { $active=0; } 4242: } 4243: if ($endtime) { 4244: if ($now>$endtime) { $active=0; } 4245: } 4246: if ($active) { 4247: my $value = $role.'/'.$cdom.'/'.$cnum.'/'; 4248: if ($sec eq '') { 4249: $sec = 'none'; 4250: } else { 4251: $value .= $sec; 4252: } 4253: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') { 4254: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) { 4255: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value); 4256: } 4257: } else { 4258: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value); 4259: } 4260: } 4261: } 4262: } 4263: } 4264: return %courses; 4265: } 4266: 4267: ############################################### 4268: 4269: sub blockcheck { 4270: my ($setters,$activity,$uname,$udom,$url) = @_; 4271: 4272: if (!defined($udom)) { 4273: $udom = $env{'user.domain'}; 4274: } 4275: if (!defined($uname)) { 4276: $uname = $env{'user.name'}; 4277: } 4278: 4279: # If uname and udom are for a course, check for blocks in the course. 4280: 4281: if (&Apache::lonnet::is_course($udom,$uname)) { 4282: my ($startblock,$endblock,$triggerblock) = 4283: &get_blocks($setters,$activity,$udom,$uname,$url); 4284: return ($startblock,$endblock,$triggerblock); 4285: } 4286: 4287: my $startblock = 0; 4288: my $endblock = 0; 4289: my $triggerblock = ''; 4290: my %live_courses = &findallcourses(undef,$uname,$udom); 4291: 4292: # If uname is for a user, and activity is course-specific, i.e., 4293: # boards, chat or groups, check for blocking in current course only. 4294: 4295: if (($activity eq 'boards' || $activity eq 'chat' || 4296: $activity eq 'groups') && ($env{'request.course.id'})) { 4297: foreach my $key (keys(%live_courses)) { 4298: if ($key ne $env{'request.course.id'}) { 4299: delete($live_courses{$key}); 4300: } 4301: } 4302: } 4303: 4304: my $otheruser = 0; 4305: my %own_courses; 4306: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) { 4307: # Resource belongs to user other than current user. 4308: $otheruser = 1; 4309: # Gather courses for current user 4310: %own_courses = 4311: &findallcourses(undef,$env{'user.name'},$env{'user.domain'}); 4312: } 4313: 4314: # Gather active course roles - course coordinator, instructor, 4315: # exam proctor, ta, student, or custom role. 4316: 4317: foreach my $course (keys(%live_courses)) { 4318: my ($cdom,$cnum); 4319: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) { 4320: $cdom = $env{'course.'.$course.'.domain'}; 4321: $cnum = $env{'course.'.$course.'.num'}; 4322: } else { 4323: ($cdom,$cnum) = split(/_/,$course); 4324: } 4325: my $no_ownblock = 0; 4326: my $no_userblock = 0; 4327: if ($otheruser && $activity ne 'com') { 4328: # Check if current user has 'evb' priv for this 4329: if (defined($own_courses{$course})) { 4330: foreach my $sec (keys(%{$own_courses{$course}})) { 4331: my $checkrole = 'cm./'.$cdom.'/'.$cnum; 4332: if ($sec ne 'none') { 4333: $checkrole .= '/'.$sec; 4334: } 4335: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { 4336: $no_ownblock = 1; 4337: last; 4338: } 4339: } 4340: } 4341: # if they have 'evb' priv and are currently not playing student 4342: next if (($no_ownblock) && 4343: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})); 4344: } 4345: foreach my $sec (keys(%{$live_courses{$course}})) { 4346: my $checkrole = 'cm./'.$cdom.'/'.$cnum; 4347: if ($sec ne 'none') { 4348: $checkrole .= '/'.$sec; 4349: } 4350: if ($otheruser) { 4351: # Resource belongs to user other than current user. 4352: # Assemble privs for that user, and check for 'evb' priv. 4353: my (%allroles,%userroles); 4354: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') { 4355: foreach my $entry (@{$live_courses{$course}{$sec}}) { 4356: my ($trole,$tdom,$tnum,$tsec); 4357: if ($entry =~ /^cr/) { 4358: ($trole,$tdom,$tnum,$tsec) = 4359: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|); 4360: } else { 4361: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry); 4362: } 4363: my ($spec,$area,$trest); 4364: $area = '/'.$tdom.'/'.$tnum; 4365: $trest = $tnum; 4366: if ($tsec ne '') { 4367: $area .= '/'.$tsec; 4368: $trest .= '/'.$tsec; 4369: } 4370: $spec = $trole.'.'.$area; 4371: if ($trole =~ /^cr/) { 4372: &Apache::lonnet::custom_roleprivs(\%allroles,$trole, 4373: $tdom,$spec,$trest,$area); 4374: } else { 4375: &Apache::lonnet::standard_roleprivs(\%allroles,$trole, 4376: $tdom,$spec,$trest,$area); 4377: } 4378: } 4379: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles); 4380: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) { 4381: if ($1) { 4382: $no_userblock = 1; 4383: last; 4384: } 4385: } 4386: } 4387: } else { 4388: # Resource belongs to current user 4389: # Check for 'evb' priv via lonnet::allowed(). 4390: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) { 4391: $no_ownblock = 1; 4392: last; 4393: } 4394: } 4395: } 4396: # if they have the evb priv and are currently not playing student 4397: next if (($no_ownblock) && 4398: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E})); 4399: next if ($no_userblock); 4400: 4401: # Retrieve blocking times and identity of locker for course 4402: # of specified user, unless user has 'evb' privilege. 4403: 4404: my ($start,$end,$trigger) = 4405: &get_blocks($setters,$activity,$cdom,$cnum,$url); 4406: if (($start != 0) && 4407: (($startblock == 0) || ($startblock > $start))) { 4408: $startblock = $start; 4409: if ($trigger ne '') { 4410: $triggerblock = $trigger; 4411: } 4412: } 4413: if (($end != 0) && 4414: (($endblock == 0) || ($endblock < $end))) { 4415: $endblock = $end; 4416: if ($trigger ne '') { 4417: $triggerblock = $trigger; 4418: } 4419: } 4420: } 4421: return ($startblock,$endblock,$triggerblock); 4422: } 4423: 4424: sub get_blocks { 4425: my ($setters,$activity,$cdom,$cnum,$url) = @_; 4426: my $startblock = 0; 4427: my $endblock = 0; 4428: my $triggerblock = ''; 4429: my $course = $cdom.'_'.$cnum; 4430: $setters->{$course} = {}; 4431: $setters->{$course}{'staff'} = []; 4432: $setters->{$course}{'times'} = []; 4433: $setters->{$course}{'triggers'} = []; 4434: my (@blockers,%triggered); 4435: my $now = time; 4436: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum); 4437: if ($activity eq 'docs') { 4438: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks); 4439: foreach my $block (@blockers) { 4440: if ($block =~ /^firstaccess____(.+)$/) { 4441: my $item = $1; 4442: my $type = 'map'; 4443: my $timersymb = $item; 4444: if ($item eq 'course') { 4445: $type = 'course'; 4446: } elsif ($item =~ /___\d+___/) { 4447: $type = 'resource'; 4448: } else { 4449: $timersymb = &Apache::lonnet::symbread($item); 4450: } 4451: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb}; 4452: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 4453: $triggered{$block} = { 4454: start => $start, 4455: end => $end, 4456: type => $type, 4457: }; 4458: } 4459: } 4460: } else { 4461: foreach my $block (keys(%commblocks)) { 4462: if ($block =~ m/^(\d+)____(\d+)$/) { 4463: my ($start,$end) = ($1,$2); 4464: if ($start <= time && $end >= time) { 4465: if (ref($commblocks{$block}) eq 'HASH') { 4466: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') { 4467: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') { 4468: unless(grep(/^\Q$block\E$/,@blockers)) { 4469: push(@blockers,$block); 4470: } 4471: } 4472: } 4473: } 4474: } 4475: } elsif ($block =~ /^firstaccess____(.+)$/) { 4476: my $item = $1; 4477: my $timersymb = $item; 4478: my $type = 'map'; 4479: if ($item eq 'course') { 4480: $type = 'course'; 4481: } elsif ($item =~ /___\d+___/) { 4482: $type = 'resource'; 4483: } else { 4484: $timersymb = &Apache::lonnet::symbread($item); 4485: } 4486: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb}; 4487: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 4488: if ($start && $end) { 4489: if (($start <= time) && ($end >= time)) { 4490: unless (grep(/^\Q$block\E$/,@blockers)) { 4491: push(@blockers,$block); 4492: $triggered{$block} = { 4493: start => $start, 4494: end => $end, 4495: type => $type, 4496: }; 4497: } 4498: } 4499: } 4500: } 4501: } 4502: } 4503: foreach my $blocker (@blockers) { 4504: my ($staff_name,$staff_dom,$title,$blocks) = 4505: &parse_block_record($commblocks{$blocker}); 4506: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]); 4507: my ($start,$end,$triggertype); 4508: if ($blocker =~ m/^(\d+)____(\d+)$/) { 4509: ($start,$end) = ($1,$2); 4510: } elsif (ref($triggered{$blocker}) eq 'HASH') { 4511: $start = $triggered{$blocker}{'start'}; 4512: $end = $triggered{$blocker}{'end'}; 4513: $triggertype = $triggered{$blocker}{'type'}; 4514: } 4515: if ($start) { 4516: push(@{$$setters{$course}{'times'}}, [$start,$end]); 4517: if ($triggertype) { 4518: push(@{$$setters{$course}{'triggers'}},$triggertype); 4519: } else { 4520: push(@{$$setters{$course}{'triggers'}},0); 4521: } 4522: if ( ($startblock == 0) || ($startblock > $start) ) { 4523: $startblock = $start; 4524: if ($triggertype) { 4525: $triggerblock = $blocker; 4526: } 4527: } 4528: if ( ($endblock == 0) || ($endblock < $end) ) { 4529: $endblock = $end; 4530: if ($triggertype) { 4531: $triggerblock = $blocker; 4532: } 4533: } 4534: } 4535: } 4536: return ($startblock,$endblock,$triggerblock); 4537: } 4538: 4539: sub parse_block_record { 4540: my ($record) = @_; 4541: my ($setuname,$setudom,$title,$blocks); 4542: if (ref($record) eq 'HASH') { 4543: ($setuname,$setudom) = split(/:/,$record->{'setter'}); 4544: $title = &unescape($record->{'event'}); 4545: $blocks = $record->{'blocks'}; 4546: } else { 4547: my @data = split(/:/,$record,3); 4548: if (scalar(@data) eq 2) { 4549: $title = $data[1]; 4550: ($setuname,$setudom) = split(/@/,$data[0]); 4551: } else { 4552: ($setuname,$setudom,$title) = @data; 4553: } 4554: $blocks = { 'com' => 'on' }; 4555: } 4556: return ($setuname,$setudom,$title,$blocks); 4557: } 4558: 4559: sub blocking_status { 4560: my ($activity,$uname,$udom,$url) = @_; 4561: my %setters; 4562: 4563: # check for active blocking 4564: my ($startblock,$endblock,$triggerblock) = 4565: &blockcheck(\%setters,$activity,$uname,$udom,$url); 4566: my $blocked = 0; 4567: if ($startblock && $endblock) { 4568: $blocked = 1; 4569: } 4570: 4571: # caller just wants to know whether a block is active 4572: if (!wantarray) { return $blocked; } 4573: 4574: # build a link to a popup window containing the details 4575: my $querystring = "?activity=$activity"; 4576: # $uname and $udom decide whose portfolio the user is trying to look at 4577: if ($activity eq 'port') { 4578: $querystring .= "&udom=$udom" if $udom; 4579: $querystring .= "&uname=$uname" if $uname; 4580: } elsif ($activity eq 'docs') { 4581: $querystring .= '&url='.&HTML::Entities::encode($url,'&"'); 4582: } 4583: 4584: my $output .= <<'END_MYBLOCK'; 4585: function openWindow(url, wdwName, w, h, toolbar,scrollbar) { 4586: var options = "width=" + w + ",height=" + h + ","; 4587: options += "resizable=yes,scrollbars="+scrollbar+",status=no,"; 4588: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no"; 4589: var newWin = window.open(url, wdwName, options); 4590: newWin.focus(); 4591: } 4592: END_MYBLOCK 4593: 4594: $output = Apache::lonhtmlcommon::scripttag($output); 4595: 4596: my $popupUrl = "/adm/blockingstatus/$querystring"; 4597: my $text = &mt('Communication Blocked'); 4598: if ($activity eq 'docs') { 4599: $text = &mt('Content Access Blocked'); 4600: } elsif ($activity eq 'printout') { 4601: $text = &mt('Printing Blocked'); 4602: } 4603: $output .= <<"END_BLOCK"; 4604: <div class='LC_comblock'> 4605: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 4606: title='$text'> 4607: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a> 4608: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 4609: title='$text'>$text</a> 4610: </div> 4611: 4612: END_BLOCK 4613: 4614: return ($blocked, $output); 4615: } 4616: 4617: ############################################### 4618: 4619: sub check_ip_acc { 4620: my ($acc)=@_; 4621: &Apache::lonxml::debug("acc is $acc"); 4622: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) { 4623: return 1; 4624: } 4625: my $allowed=0; 4626: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'}; 4627: 4628: my $name; 4629: foreach my $pattern (split(',',$acc)) { 4630: $pattern =~ s/^\s*//; 4631: $pattern =~ s/\s*$//; 4632: if ($pattern =~ /\*$/) { 4633: #35.8.* 4634: $pattern=~s/\*//; 4635: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; } 4636: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) { 4637: #35.8.3.[34-56] 4638: my $low=$2; 4639: my $high=$3; 4640: $pattern=$1; 4641: if ($ip =~ /^\Q$pattern\E/) { 4642: my $last=(split(/\./,$ip))[3]; 4643: if ($last <=$high && $last >=$low) { $allowed=1; } 4644: } 4645: } elsif ($pattern =~ /^\*/) { 4646: #*.msu.edu 4647: $pattern=~s/\*//; 4648: if (!defined($name)) { 4649: use Socket; 4650: my $netaddr=inet_aton($ip); 4651: ($name)=gethostbyaddr($netaddr,AF_INET); 4652: } 4653: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; } 4654: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) { 4655: #127.0.0.1 4656: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; } 4657: } else { 4658: #some.name.com 4659: if (!defined($name)) { 4660: use Socket; 4661: my $netaddr=inet_aton($ip); 4662: ($name)=gethostbyaddr($netaddr,AF_INET); 4663: } 4664: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; } 4665: } 4666: if ($allowed) { last; } 4667: } 4668: return $allowed; 4669: } 4670: 4671: ############################################### 4672: 4673: =pod 4674: 4675: =head1 Domain Template Functions 4676: 4677: =over 4 4678: 4679: =item * &determinedomain() 4680: 4681: Inputs: $domain (usually will be undef) 4682: 4683: Returns: Determines which domain should be used for designs 4684: 4685: =cut 4686: 4687: ############################################### 4688: sub determinedomain { 4689: my $domain=shift; 4690: if (! $domain) { 4691: # Determine domain if we have not been given one 4692: $domain = &Apache::lonnet::default_login_domain(); 4693: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; } 4694: if ($env{'request.role.domain'}) { 4695: $domain=$env{'request.role.domain'}; 4696: } 4697: } 4698: return $domain; 4699: } 4700: ############################################### 4701: 4702: sub devalidate_domconfig_cache { 4703: my ($udom)=@_; 4704: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom); 4705: } 4706: 4707: # ---------------------- Get domain configuration for a domain 4708: sub get_domainconf { 4709: my ($udom) = @_; 4710: my $cachetime=1800; 4711: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom); 4712: if (defined($cached)) { return %{$result}; } 4713: 4714: my %domconfig = &Apache::lonnet::get_dom('configuration', 4715: ['login','rolecolors','autoenroll'],$udom); 4716: my (%designhash,%legacy); 4717: if (keys(%domconfig) > 0) { 4718: if (ref($domconfig{'login'}) eq 'HASH') { 4719: if (keys(%{$domconfig{'login'}})) { 4720: foreach my $key (keys(%{$domconfig{'login'}})) { 4721: if (ref($domconfig{'login'}{$key}) eq 'HASH') { 4722: if ($key eq 'loginvia') { 4723: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') { 4724: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) { 4725: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') { 4726: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) { 4727: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'}; 4728: $designhash{$udom.'.login.loginvia'} = $server; 4729: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') { 4730: 4731: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'}; 4732: } else { 4733: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'}; 4734: } 4735: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) { 4736: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}; 4737: } 4738: } 4739: } 4740: } 4741: } 4742: } else { 4743: foreach my $img (keys(%{$domconfig{'login'}{$key}})) { 4744: $designhash{$udom.'.login.'.$key.'_'.$img} = 4745: $domconfig{'login'}{$key}{$img}; 4746: } 4747: } 4748: } else { 4749: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key}; 4750: } 4751: } 4752: } else { 4753: $legacy{'login'} = 1; 4754: } 4755: } else { 4756: $legacy{'login'} = 1; 4757: } 4758: if (ref($domconfig{'rolecolors'}) eq 'HASH') { 4759: if (keys(%{$domconfig{'rolecolors'}})) { 4760: foreach my $role (keys(%{$domconfig{'rolecolors'}})) { 4761: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') { 4762: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) { 4763: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item}; 4764: } 4765: } 4766: } 4767: } else { 4768: $legacy{'rolecolors'} = 1; 4769: } 4770: } else { 4771: $legacy{'rolecolors'} = 1; 4772: } 4773: if (ref($domconfig{'autoenroll'}) eq 'HASH') { 4774: if ($domconfig{'autoenroll'}{'co-owners'}) { 4775: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'}; 4776: } 4777: } 4778: if (keys(%legacy) > 0) { 4779: my %legacyhash = &get_legacy_domconf($udom); 4780: foreach my $item (keys(%legacyhash)) { 4781: if ($item =~ /^\Q$udom\E\.login/) { 4782: if ($legacy{'login'}) { 4783: $designhash{$item} = $legacyhash{$item}; 4784: } 4785: } else { 4786: if ($legacy{'rolecolors'}) { 4787: $designhash{$item} = $legacyhash{$item}; 4788: } 4789: } 4790: } 4791: } 4792: } else { 4793: %designhash = &get_legacy_domconf($udom); 4794: } 4795: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash, 4796: $cachetime); 4797: return %designhash; 4798: } 4799: 4800: sub get_legacy_domconf { 4801: my ($udom) = @_; 4802: my %legacyhash; 4803: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors'; 4804: my $designfile = $designdir.'/'.$udom.'.tab'; 4805: if (-e $designfile) { 4806: if ( open (my $fh,"<$designfile") ) { 4807: while (my $line = <$fh>) { 4808: next if ($line =~ /^\#/); 4809: chomp($line); 4810: my ($key,$val)=(split(/\=/,$line)); 4811: if ($val) { $legacyhash{$udom.'.'.$key}=$val; } 4812: } 4813: close($fh); 4814: } 4815: } 4816: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') { 4817: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif"; 4818: } 4819: return %legacyhash; 4820: } 4821: 4822: =pod 4823: 4824: =item * &domainlogo() 4825: 4826: Inputs: $domain (usually will be undef) 4827: 4828: Returns: A link to a domain logo, if the domain logo exists. 4829: If the domain logo does not exist, a description of the domain. 4830: 4831: =cut 4832: 4833: ############################################### 4834: sub domainlogo { 4835: my $domain = &determinedomain(shift); 4836: my %designhash = &get_domainconf($domain); 4837: # See if there is a logo 4838: if ($designhash{$domain.'.login.domlogo'} ne '') { 4839: my $imgsrc = $designhash{$domain.'.login.domlogo'}; 4840: if ($imgsrc =~ m{^/(adm|res)/}) { 4841: if ($imgsrc =~ m{^/res/}) { 4842: my $local_name = &Apache::lonnet::filelocation('',$imgsrc); 4843: &Apache::lonnet::repcopy($local_name); 4844: } 4845: $imgsrc = &lonhttpdurl($imgsrc); 4846: } 4847: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />'; 4848: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) { 4849: return &Apache::lonnet::domain($domain,'description'); 4850: } else { 4851: return ''; 4852: } 4853: } 4854: ############################################## 4855: 4856: =pod 4857: 4858: =item * &designparm() 4859: 4860: Inputs: $which parameter; $domain (usually will be undef) 4861: 4862: Returns: value of designparamter $which 4863: 4864: =cut 4865: 4866: 4867: ############################################## 4868: sub designparm { 4869: my ($which,$domain)=@_; 4870: if (exists($env{'environment.color.'.$which})) { 4871: return $env{'environment.color.'.$which}; 4872: } 4873: $domain=&determinedomain($domain); 4874: my %domdesign; 4875: unless ($domain eq 'public') { 4876: %domdesign = &get_domainconf($domain); 4877: } 4878: my $output; 4879: if ($domdesign{$domain.'.'.$which} ne '') { 4880: $output = $domdesign{$domain.'.'.$which}; 4881: } else { 4882: $output = $defaultdesign{$which}; 4883: } 4884: if (($which =~ /^(student|coordinator|author|admin)\.img$/) || 4885: ($which =~ /login\.(img|logo|domlogo|login)/)) { 4886: if ($output =~ m{^/(adm|res)/}) { 4887: if ($output =~ m{^/res/}) { 4888: my $local_name = &Apache::lonnet::filelocation('',$output); 4889: &Apache::lonnet::repcopy($local_name); 4890: } 4891: $output = &lonhttpdurl($output); 4892: } 4893: } 4894: return $output; 4895: } 4896: 4897: ############################################## 4898: =pod 4899: 4900: =item * &authorspace() 4901: 4902: Inputs: $url (usually will be undef). 4903: 4904: Returns: Path to Construction Space containing the resource or 4905: directory being viewed (or for which action is being taken). 4906: If $url is provided, and begins /priv/<domain>/<uname> 4907: the path will be that portion of the $context argument. 4908: Otherwise the path will be for the author space of the current 4909: user when the current role is author, or for that of the 4910: co-author/assistant co-author space when the current role 4911: is co-author or assistant co-author. 4912: 4913: =cut 4914: 4915: sub authorspace { 4916: my ($url) = @_; 4917: if ($url ne '') { 4918: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) { 4919: return $1; 4920: } 4921: } 4922: my $caname = ''; 4923: my $cadom = ''; 4924: if ($env{'request.role'} =~ /^(?:ca|aa)/) { 4925: ($cadom,$caname) = 4926: ($env{'request.role'}=~/($match_domain)\/($match_username)$/); 4927: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) { 4928: $caname = $env{'user.name'}; 4929: $cadom = $env{'user.domain'}; 4930: } 4931: if (($caname ne '') && ($cadom ne '')) { 4932: return "/priv/$cadom/$caname/"; 4933: } 4934: return; 4935: } 4936: 4937: ############################################## 4938: =pod 4939: 4940: =item * &head_subbox() 4941: 4942: Inputs: $content (contains HTML code with page functions, etc.) 4943: 4944: Returns: HTML div with $content 4945: To be included in page header 4946: 4947: =cut 4948: 4949: sub head_subbox { 4950: my ($content)=@_; 4951: my $output = 4952: '<div class="LC_head_subbox">' 4953: .$content 4954: .'</div>' 4955: } 4956: 4957: ############################################## 4958: =pod 4959: 4960: =item * &CSTR_pageheader() 4961: 4962: Input: (optional) filename from which breadcrumb trail is built. 4963: In most cases no input as needed, as $env{'request.filename'} 4964: is appropriate for use in building the breadcrumb trail. 4965: 4966: Returns: HTML div with CSTR path and recent box 4967: To be included on Construction Space pages 4968: 4969: =cut 4970: 4971: sub CSTR_pageheader { 4972: my ($trailfile) = @_; 4973: if ($trailfile eq '') { 4974: $trailfile = $env{'request.filename'}; 4975: } 4976: 4977: # this is for resources; directories have customtitle, and crumbs 4978: # and select recent are created in lonpubdir.pm 4979: 4980: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'}; 4981: my ($udom,$uname,$thisdisfn)= 4982: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$}); 4983: my $formaction = "/priv/$udom/$uname/$thisdisfn"; 4984: $formaction =~ s{/+}{/}g; 4985: 4986: my $parentpath = ''; 4987: my $lastitem = ''; 4988: if ($thisdisfn =~ m-(.+/)([^/]*)$-) { 4989: $parentpath = $1; 4990: $lastitem = $2; 4991: } else { 4992: $lastitem = $thisdisfn; 4993: } 4994: 4995: my $output = 4996: '<div>' 4997: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it? 4998: .'<b>'.&mt('Construction Space:').'</b> ' 4999: .'<form name="dirs" method="post" action="'.$formaction 5000: .'" target="_top">' #FIXME lonpubdir: target="_parent" 5001: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef); 5002: 5003: if ($lastitem) { 5004: $output .= 5005: '<span class="LC_filename">' 5006: .$lastitem 5007: .'</span>'; 5008: } 5009: $output .= 5010: '<br />' 5011: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />" 5012: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()') 5013: .'</form>' 5014: .&Apache::lonmenu::constspaceform() 5015: .'</div>'; 5016: 5017: return $output; 5018: } 5019: 5020: ############################################### 5021: ############################################### 5022: 5023: =pod 5024: 5025: =back 5026: 5027: =head1 HTML Helpers 5028: 5029: =over 4 5030: 5031: =item * &bodytag() 5032: 5033: Returns a uniform header for LON-CAPA web pages. 5034: 5035: Inputs: 5036: 5037: =over 4 5038: 5039: =item * $title, A title to be displayed on the page. 5040: 5041: =item * $function, the current role (can be undef). 5042: 5043: =item * $addentries, extra parameters for the <body> tag. 5044: 5045: =item * $bodyonly, if defined, only return the <body> tag. 5046: 5047: =item * $domain, if defined, force a given domain. 5048: 5049: =item * $forcereg, if page should register as content page (relevant for 5050: text interface only) 5051: 5052: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the 5053: navigational links 5054: 5055: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value 5056: 5057: =item * $args, optional argument valid values are 5058: no_auto_mt_title -> prevents &mt()ing the title arg 5059: inherit_jsmath -> when creating popup window in a page, 5060: should it have jsmath forced on by the 5061: current page 5062: 5063: =item * $advtoolsref, optional argument, ref to an array containing 5064: inlineremote items to be added in "Functions" menu below 5065: breadcrumbs. 5066: 5067: =back 5068: 5069: Returns: A uniform header for LON-CAPA web pages. 5070: If $bodyonly is nonzero, a string containing a <body> tag will be returned. 5071: If $bodyonly is undef or zero, an html string containing a <body> tag and 5072: other decorations will be returned. 5073: 5074: =cut 5075: 5076: sub bodytag { 5077: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg, 5078: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_; 5079: 5080: my $public; 5081: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')) 5082: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) { 5083: $public = 1; 5084: } 5085: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } 5086: 5087: $function = &get_users_function() if (!$function); 5088: my $img = &designparm($function.'.img',$domain); 5089: my $font = &designparm($function.'.font',$domain); 5090: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain); 5091: 5092: my %design = ( 'style' => 'margin-top: 0', 5093: 'bgcolor' => $pgbg, 5094: 'text' => $font, 5095: 'alink' => &designparm($function.'.alink',$domain), 5096: 'vlink' => &designparm($function.'.vlink',$domain), 5097: 'link' => &designparm($function.'.link',$domain),); 5098: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 5099: 5100: # role and realm 5101: my ($role,$realm) = split(/\./,$env{'request.role'},2); 5102: if ($role eq 'ca') { 5103: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$}); 5104: $realm = &plainname($rname,$rdom); 5105: } 5106: # realm 5107: if ($env{'request.course.id'}) { 5108: if ($env{'request.role'} !~ /^cr/) { 5109: $role = &Apache::lonnet::plaintext($role,&course_type()); 5110: } 5111: if ($env{'request.course.sec'}) { 5112: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'}; 5113: } 5114: $realm = $env{'course.'.$env{'request.course.id'}.'.description'}; 5115: } else { 5116: $role = &Apache::lonnet::plaintext($role); 5117: } 5118: 5119: if (!$realm) { $realm=' '; } 5120: 5121: my $extra_body_attr = &make_attr_string($forcereg,\%design); 5122: 5123: # construct main body tag 5124: my $bodytag = "<body $extra_body_attr>". 5125: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'}); 5126: 5127: if ($bodyonly) { 5128: return $bodytag; 5129: } 5130: 5131: my $name = &plainname($env{'user.name'},$env{'user.domain'}); 5132: if ($public) { 5133: undef($role); 5134: } else { 5135: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'}, 5136: undef,'LC_menubuttons_link'); 5137: } 5138: 5139: my $titleinfo = '<h1>'.$title.'</h1>'; 5140: # 5141: # Extra info if you are the DC 5142: my $dc_info = ''; 5143: if ($env{'user.adv'} && exists($env{'user.role.dc./'. 5144: $env{'course.'.$env{'request.course.id'}. 5145: '.domain'}.'/'})) { 5146: my $cid = $env{'request.course.id'}; 5147: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'}; 5148: $dc_info =~ s/\s+$//; 5149: } 5150: 5151: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role; 5152: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']); 5153: 5154: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 5155: return $bodytag; 5156: } 5157: 5158: if ($env{'request.state'} eq 'construct') { $forcereg=1; } 5159: 5160: # if ($env{'request.state'} eq 'construct') { 5161: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls 5162: # } 5163: 5164: 5165: 5166: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) { 5167: if ($dc_info) { 5168: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|; 5169: } 5170: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br /> 5171: <em>$realm</em> $dc_info</div>|; 5172: return $bodytag; 5173: } 5174: 5175: unless ($env{'request.symb'} =~ m/\.page___\d+___/) { 5176: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|; 5177: } 5178: 5179: $bodytag .= Apache::lonhtmlcommon::scripttag( 5180: Apache::lonmenu::utilityfunctions(), 'start'); 5181: 5182: $bodytag .= Apache::lonmenu::primary_menu(); 5183: 5184: if ($dc_info) { 5185: $dc_info = &dc_courseid_toggle($dc_info); 5186: } 5187: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|; 5188: 5189: #don't show menus for public users 5190: if (!$public){ 5191: $bodytag .= Apache::lonmenu::secondary_menu(); 5192: $bodytag .= Apache::lonmenu::serverform(); 5193: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 5194: if ($env{'request.state'} eq 'construct') { 5195: $bodytag .= &Apache::lonmenu::innerregister($forcereg, 5196: $args->{'bread_crumbs'}); 5197: } elsif ($forcereg) { 5198: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef, 5199: $args->{'group'}); 5200: } else { 5201: $bodytag .= 5202: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'}, 5203: $forcereg,$args->{'group'}, 5204: $args->{'bread_crumbs'}, 5205: $advtoolsref); 5206: } 5207: }else{ 5208: # this is to seperate menu from content when there's no secondary 5209: # menu. Especially needed for public accessible ressources. 5210: $bodytag .= '<hr style="clear:both" />'; 5211: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 5212: } 5213: 5214: return $bodytag; 5215: } 5216: 5217: sub dc_courseid_toggle { 5218: my ($dc_info) = @_; 5219: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'. 5220: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'. 5221: &mt('(More ...)').'</a></span>'. 5222: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>'; 5223: } 5224: 5225: sub make_attr_string { 5226: my ($register,$attr_ref) = @_; 5227: 5228: if ($attr_ref && !ref($attr_ref)) { 5229: die("addentries Must be a hash ref ". 5230: join(':',caller(1))." ". 5231: join(':',caller(0))." "); 5232: } 5233: 5234: if ($register) { 5235: my ($on_load,$on_unload); 5236: foreach my $key (keys(%{$attr_ref})) { 5237: if (lc($key) eq 'onload') { 5238: $on_load.=$attr_ref->{$key}.';'; 5239: delete($attr_ref->{$key}); 5240: 5241: } elsif (lc($key) eq 'onunload') { 5242: $on_unload.=$attr_ref->{$key}.';'; 5243: delete($attr_ref->{$key}); 5244: } 5245: } 5246: $attr_ref->{'onload'} = $on_load; 5247: $attr_ref->{'onunload'}= $on_unload; 5248: } 5249: 5250: my $attr_string; 5251: foreach my $attr (keys(%$attr_ref)) { 5252: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" '; 5253: } 5254: return $attr_string; 5255: } 5256: 5257: 5258: ############################################### 5259: ############################################### 5260: 5261: =pod 5262: 5263: =item * &endbodytag() 5264: 5265: Returns a uniform footer for LON-CAPA web pages. 5266: 5267: Inputs: 1 - optional reference to an args hash 5268: If in the hash, key for noredirectlink has a value which evaluates to true, 5269: a 'Continue' link is not displayed if the page contains an 5270: internal redirect in the <head></head> section, 5271: i.e., $env{'internal.head.redirect'} exists 5272: 5273: =cut 5274: 5275: sub endbodytag { 5276: my ($args) = @_; 5277: my $endbodytag; 5278: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) { 5279: $endbodytag='</body>'; 5280: } 5281: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag; 5282: if ( exists( $env{'internal.head.redirect'} ) ) { 5283: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) { 5284: $endbodytag= 5285: "<br /><a href=\"$env{'internal.head.redirect'}\">". 5286: &mt('Continue').'</a>'. 5287: $endbodytag; 5288: } 5289: } 5290: return $endbodytag; 5291: } 5292: 5293: =pod 5294: 5295: =item * &standard_css() 5296: 5297: Returns a style sheet 5298: 5299: Inputs: (all optional) 5300: domain -> force to color decorate a page for a specific 5301: domain 5302: function -> force usage of a specific rolish color scheme 5303: bgcolor -> override the default page bgcolor 5304: 5305: =cut 5306: 5307: sub standard_css { 5308: my ($function,$domain,$bgcolor) = @_; 5309: $function = &get_users_function() if (!$function); 5310: my $img = &designparm($function.'.img', $domain); 5311: my $tabbg = &designparm($function.'.tabbg', $domain); 5312: my $font = &designparm($function.'.font', $domain); 5313: my $fontmenu = &designparm($function.'.fontmenu', $domain); 5314: #second colour for later usage 5315: my $sidebg = &designparm($function.'.sidebg',$domain); 5316: my $pgbg_or_bgcolor = 5317: $bgcolor || 5318: &designparm($function.'.pgbg', $domain); 5319: my $pgbg = &designparm($function.'.pgbg', $domain); 5320: my $alink = &designparm($function.'.alink', $domain); 5321: my $vlink = &designparm($function.'.vlink', $domain); 5322: my $link = &designparm($function.'.link', $domain); 5323: 5324: my $sans = 'Verdana,Arial,Helvetica,sans-serif'; 5325: my $mono = 'monospace'; 5326: my $data_table_head = $sidebg; 5327: my $data_table_light = '#FAFAFA'; 5328: my $data_table_dark = '#E0E0E0'; 5329: my $data_table_darker = '#CCCCCC'; 5330: my $data_table_highlight = '#FFFF00'; 5331: my $mail_new = '#FFBB77'; 5332: my $mail_new_hover = '#DD9955'; 5333: my $mail_read = '#BBBB77'; 5334: my $mail_read_hover = '#999944'; 5335: my $mail_replied = '#AAAA88'; 5336: my $mail_replied_hover = '#888855'; 5337: my $mail_other = '#99BBBB'; 5338: my $mail_other_hover = '#669999'; 5339: my $table_header = '#DDDDDD'; 5340: my $feedback_link_bg = '#BBBBBB'; 5341: my $lg_border_color = '#C8C8C8'; 5342: my $button_hover = '#BF2317'; 5343: 5344: my $border = ($env{'browser.type'} eq 'explorer' || 5345: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px' 5346: : '0 3px 0 4px'; 5347: 5348: 5349: return <<END; 5350: 5351: /* needed for iframe to allow 100% height in FF */ 5352: body, html { 5353: margin: 0; 5354: padding: 0 0.5%; 5355: height: 99%; /* to avoid scrollbars */ 5356: } 5357: 5358: body { 5359: font-family: $sans; 5360: line-height:130%; 5361: font-size:0.83em; 5362: color:$font; 5363: } 5364: 5365: a:focus, 5366: a:focus img { 5367: color: red; 5368: } 5369: 5370: form, .inline { 5371: display: inline; 5372: } 5373: 5374: .LC_right { 5375: text-align:right; 5376: } 5377: 5378: .LC_middle { 5379: vertical-align:middle; 5380: } 5381: 5382: .LC_400Box { 5383: width:400px; 5384: } 5385: 5386: .LC_iframecontainer { 5387: width: 98%; 5388: margin: 0; 5389: position: fixed; 5390: top: 8.5em; 5391: bottom: 0; 5392: } 5393: 5394: .LC_iframecontainer iframe{ 5395: border: none; 5396: width: 100%; 5397: height: 100%; 5398: } 5399: 5400: .LC_filename { 5401: font-family: $mono; 5402: white-space:pre; 5403: font-size: 120%; 5404: } 5405: 5406: .LC_fileicon { 5407: border: none; 5408: height: 1.3em; 5409: vertical-align: text-bottom; 5410: margin-right: 0.3em; 5411: text-decoration:none; 5412: } 5413: 5414: .LC_setting { 5415: text-decoration:underline; 5416: } 5417: 5418: .LC_error { 5419: color: red; 5420: } 5421: 5422: .LC_warning { 5423: color: darkorange; 5424: } 5425: 5426: .LC_diff_removed { 5427: color: red; 5428: } 5429: 5430: .LC_info, 5431: .LC_success, 5432: .LC_diff_added { 5433: color: green; 5434: } 5435: 5436: div.LC_confirm_box { 5437: background-color: #FAFAFA; 5438: border: 1px solid $lg_border_color; 5439: margin-right: 0; 5440: padding: 5px; 5441: } 5442: 5443: div.LC_confirm_box .LC_error img, 5444: div.LC_confirm_box .LC_success img { 5445: vertical-align: middle; 5446: } 5447: 5448: .LC_icon { 5449: border: none; 5450: vertical-align: middle; 5451: } 5452: 5453: .LC_docs_spacer { 5454: width: 25px; 5455: height: 1px; 5456: border: none; 5457: } 5458: 5459: .LC_internal_info { 5460: color: #999999; 5461: } 5462: 5463: .LC_discussion { 5464: background: $data_table_dark; 5465: border: 1px solid black; 5466: margin: 2px; 5467: } 5468: 5469: .LC_disc_action_left { 5470: background: $sidebg; 5471: text-align: left; 5472: padding: 4px; 5473: margin: 2px; 5474: } 5475: 5476: .LC_disc_action_right { 5477: background: $sidebg; 5478: text-align: right; 5479: padding: 4px; 5480: margin: 2px; 5481: } 5482: 5483: .LC_disc_new_item { 5484: background: white; 5485: border: 2px solid red; 5486: margin: 4px; 5487: padding: 4px; 5488: } 5489: 5490: .LC_disc_old_item { 5491: background: white; 5492: margin: 4px; 5493: padding: 4px; 5494: } 5495: 5496: table.LC_pastsubmission { 5497: border: 1px solid black; 5498: margin: 2px; 5499: } 5500: 5501: table#LC_menubuttons { 5502: width: 100%; 5503: background: $pgbg; 5504: border: 2px; 5505: border-collapse: separate; 5506: padding: 0; 5507: } 5508: 5509: table#LC_title_bar a { 5510: color: $fontmenu; 5511: } 5512: 5513: table#LC_title_bar { 5514: clear: both; 5515: display: none; 5516: } 5517: 5518: table#LC_title_bar, 5519: table.LC_breadcrumbs, /* obsolete? */ 5520: table#LC_title_bar.LC_with_remote { 5521: width: 100%; 5522: border-color: $pgbg; 5523: border-style: solid; 5524: border-width: $border; 5525: background: $pgbg; 5526: color: $fontmenu; 5527: border-collapse: collapse; 5528: padding: 0; 5529: margin: 0; 5530: } 5531: 5532: ul.LC_breadcrumb_tools_outerlist { 5533: margin: 0; 5534: padding: 0; 5535: position: relative; 5536: list-style: none; 5537: } 5538: ul.LC_breadcrumb_tools_outerlist li { 5539: display: inline; 5540: } 5541: 5542: .LC_breadcrumb_tools_navigation { 5543: padding: 0; 5544: margin: 0; 5545: float: left; 5546: } 5547: .LC_breadcrumb_tools_tools { 5548: padding: 0; 5549: margin: 0; 5550: float: right; 5551: } 5552: 5553: table#LC_title_bar td { 5554: background: $tabbg; 5555: } 5556: 5557: table#LC_menubuttons img { 5558: border: none; 5559: } 5560: 5561: .LC_breadcrumbs_component { 5562: float: right; 5563: margin: 0 1em; 5564: } 5565: .LC_breadcrumbs_component img { 5566: vertical-align: middle; 5567: } 5568: 5569: td.LC_table_cell_checkbox { 5570: text-align: center; 5571: } 5572: 5573: .LC_fontsize_small { 5574: font-size: 70%; 5575: } 5576: 5577: #LC_breadcrumbs { 5578: clear:both; 5579: background: $sidebg; 5580: border-bottom: 1px solid $lg_border_color; 5581: line-height: 2.5em; 5582: overflow: hidden; 5583: margin: 0; 5584: padding: 0; 5585: text-align: left; 5586: } 5587: 5588: .LC_head_subbox, .LC_actionbox { 5589: clear:both; 5590: background: #F8F8F8; /* $sidebg; */ 5591: border: 1px solid $sidebg; 5592: margin: 0 0 10px 0; 5593: padding: 3px; 5594: text-align: left; 5595: } 5596: 5597: .LC_fontsize_medium { 5598: font-size: 85%; 5599: } 5600: 5601: .LC_fontsize_large { 5602: font-size: 120%; 5603: } 5604: 5605: .LC_menubuttons_inline_text { 5606: color: $font; 5607: font-size: 90%; 5608: padding-left:3px; 5609: } 5610: 5611: .LC_menubuttons_inline_text img{ 5612: vertical-align: middle; 5613: } 5614: 5615: li.LC_menubuttons_inline_text img { 5616: cursor:pointer; 5617: text-decoration: none; 5618: } 5619: 5620: .LC_menubuttons_link { 5621: text-decoration: none; 5622: } 5623: 5624: .LC_menubuttons_category { 5625: color: $font; 5626: background: $pgbg; 5627: font-size: larger; 5628: font-weight: bold; 5629: } 5630: 5631: td.LC_menubuttons_text { 5632: color: $font; 5633: } 5634: 5635: .LC_current_location { 5636: background: $tabbg; 5637: } 5638: 5639: table.LC_data_table { 5640: border: 1px solid #000000; 5641: border-collapse: separate; 5642: border-spacing: 1px; 5643: background: $pgbg; 5644: } 5645: 5646: .LC_data_table_dense { 5647: font-size: small; 5648: } 5649: 5650: table.LC_nested_outer { 5651: border: 1px solid #000000; 5652: border-collapse: collapse; 5653: border-spacing: 0; 5654: width: 100%; 5655: } 5656: 5657: table.LC_innerpickbox, 5658: table.LC_nested { 5659: border: none; 5660: border-collapse: collapse; 5661: border-spacing: 0; 5662: width: 100%; 5663: } 5664: 5665: table.LC_data_table tr th, 5666: table.LC_calendar tr th, 5667: table.LC_prior_tries tr th, 5668: table.LC_innerpickbox tr th { 5669: font-weight: bold; 5670: background-color: $data_table_head; 5671: color:$fontmenu; 5672: font-size:90%; 5673: } 5674: 5675: table.LC_innerpickbox tr th, 5676: table.LC_innerpickbox tr td { 5677: vertical-align: top; 5678: } 5679: 5680: table.LC_data_table tr.LC_info_row > td { 5681: background-color: #CCCCCC; 5682: font-weight: bold; 5683: text-align: left; 5684: } 5685: 5686: table.LC_data_table tr.LC_odd_row > td { 5687: background-color: $data_table_light; 5688: padding: 2px; 5689: vertical-align: top; 5690: } 5691: 5692: table.LC_pick_box tr > td.LC_odd_row { 5693: background-color: $data_table_light; 5694: vertical-align: top; 5695: } 5696: 5697: table.LC_data_table tr.LC_even_row > td { 5698: background-color: $data_table_dark; 5699: padding: 2px; 5700: vertical-align: top; 5701: } 5702: 5703: table.LC_pick_box tr > td.LC_even_row { 5704: background-color: $data_table_dark; 5705: vertical-align: top; 5706: } 5707: 5708: table.LC_data_table tr.LC_data_table_highlight td { 5709: background-color: $data_table_darker; 5710: } 5711: 5712: table.LC_data_table tr td.LC_leftcol_header { 5713: background-color: $data_table_head; 5714: font-weight: bold; 5715: } 5716: 5717: table.LC_data_table tr.LC_empty_row td, 5718: table.LC_nested tr.LC_empty_row td { 5719: font-weight: bold; 5720: font-style: italic; 5721: text-align: center; 5722: padding: 8px; 5723: } 5724: 5725: table.LC_data_table tr.LC_empty_row td { 5726: background-color: $sidebg; 5727: } 5728: 5729: table.LC_nested tr.LC_empty_row td { 5730: background-color: #FFFFFF; 5731: } 5732: 5733: table.LC_caption { 5734: } 5735: 5736: table.LC_nested tr.LC_empty_row td { 5737: padding: 4ex 5738: } 5739: 5740: table.LC_nested_outer tr th { 5741: font-weight: bold; 5742: color:$fontmenu; 5743: background-color: $data_table_head; 5744: font-size: small; 5745: border-bottom: 1px solid #000000; 5746: } 5747: 5748: table.LC_nested_outer tr td.LC_subheader { 5749: background-color: $data_table_head; 5750: font-weight: bold; 5751: font-size: small; 5752: border-bottom: 1px solid #000000; 5753: text-align: right; 5754: } 5755: 5756: table.LC_nested tr.LC_info_row td { 5757: background-color: #CCCCCC; 5758: font-weight: bold; 5759: font-size: small; 5760: text-align: center; 5761: } 5762: 5763: table.LC_nested tr.LC_info_row td.LC_left_item, 5764: table.LC_nested_outer tr th.LC_left_item { 5765: text-align: left; 5766: } 5767: 5768: table.LC_nested td { 5769: background-color: #FFFFFF; 5770: font-size: small; 5771: } 5772: 5773: table.LC_nested_outer tr th.LC_right_item, 5774: table.LC_nested tr.LC_info_row td.LC_right_item, 5775: table.LC_nested tr.LC_odd_row td.LC_right_item, 5776: table.LC_nested tr td.LC_right_item { 5777: text-align: right; 5778: } 5779: 5780: table.LC_nested tr.LC_odd_row td { 5781: background-color: #EEEEEE; 5782: } 5783: 5784: table.LC_createuser { 5785: } 5786: 5787: table.LC_createuser tr.LC_section_row td { 5788: font-size: small; 5789: } 5790: 5791: table.LC_createuser tr.LC_info_row td { 5792: background-color: #CCCCCC; 5793: font-weight: bold; 5794: text-align: center; 5795: } 5796: 5797: table.LC_calendar { 5798: border: 1px solid #000000; 5799: border-collapse: collapse; 5800: width: 98%; 5801: } 5802: 5803: table.LC_calendar_pickdate { 5804: font-size: xx-small; 5805: } 5806: 5807: table.LC_calendar tr td { 5808: border: 1px solid #000000; 5809: vertical-align: top; 5810: width: 14%; 5811: } 5812: 5813: table.LC_calendar tr td.LC_calendar_day_empty { 5814: background-color: $data_table_dark; 5815: } 5816: 5817: table.LC_calendar tr td.LC_calendar_day_current { 5818: background-color: $data_table_highlight; 5819: } 5820: 5821: table.LC_data_table tr td.LC_mail_new { 5822: background-color: $mail_new; 5823: } 5824: 5825: table.LC_data_table tr.LC_mail_new:hover { 5826: background-color: $mail_new_hover; 5827: } 5828: 5829: table.LC_data_table tr td.LC_mail_read { 5830: background-color: $mail_read; 5831: } 5832: 5833: /* 5834: table.LC_data_table tr.LC_mail_read:hover { 5835: background-color: $mail_read_hover; 5836: } 5837: */ 5838: 5839: table.LC_data_table tr td.LC_mail_replied { 5840: background-color: $mail_replied; 5841: } 5842: 5843: /* 5844: table.LC_data_table tr.LC_mail_replied:hover { 5845: background-color: $mail_replied_hover; 5846: } 5847: */ 5848: 5849: table.LC_data_table tr td.LC_mail_other { 5850: background-color: $mail_other; 5851: } 5852: 5853: /* 5854: table.LC_data_table tr.LC_mail_other:hover { 5855: background-color: $mail_other_hover; 5856: } 5857: */ 5858: 5859: table.LC_data_table tr > td.LC_browser_file, 5860: table.LC_data_table tr > td.LC_browser_file_published { 5861: background: #AAEE77; 5862: } 5863: 5864: table.LC_data_table tr > td.LC_browser_file_locked, 5865: table.LC_data_table tr > td.LC_browser_file_unpublished { 5866: background: #FFAA99; 5867: } 5868: 5869: table.LC_data_table tr > td.LC_browser_file_obsolete { 5870: background: #888888; 5871: } 5872: 5873: table.LC_data_table tr > td.LC_browser_file_modified, 5874: table.LC_data_table tr > td.LC_browser_file_metamodified { 5875: background: #F8F866; 5876: } 5877: 5878: table.LC_data_table tr.LC_browser_folder > td { 5879: background: #E0E8FF; 5880: } 5881: 5882: table.LC_data_table tr > td.LC_roles_is { 5883: /* background: #77FF77; */ 5884: } 5885: 5886: table.LC_data_table tr > td.LC_roles_future { 5887: border-right: 8px solid #FFFF77; 5888: } 5889: 5890: table.LC_data_table tr > td.LC_roles_will { 5891: border-right: 8px solid #FFAA77; 5892: } 5893: 5894: table.LC_data_table tr > td.LC_roles_expired { 5895: border-right: 8px solid #FF7777; 5896: } 5897: 5898: table.LC_data_table tr > td.LC_roles_will_not { 5899: border-right: 8px solid #AAFF77; 5900: } 5901: 5902: table.LC_data_table tr > td.LC_roles_selected { 5903: border-right: 8px solid #11CC55; 5904: } 5905: 5906: span.LC_current_location { 5907: font-size:larger; 5908: background: $pgbg; 5909: } 5910: 5911: span.LC_current_nav_location { 5912: font-weight:bold; 5913: background: $sidebg; 5914: } 5915: 5916: span.LC_parm_menu_item { 5917: font-size: larger; 5918: } 5919: 5920: span.LC_parm_scope_all { 5921: color: red; 5922: } 5923: 5924: span.LC_parm_scope_folder { 5925: color: green; 5926: } 5927: 5928: span.LC_parm_scope_resource { 5929: color: orange; 5930: } 5931: 5932: span.LC_parm_part { 5933: color: blue; 5934: } 5935: 5936: span.LC_parm_folder, 5937: span.LC_parm_symb { 5938: font-size: x-small; 5939: font-family: $mono; 5940: color: #AAAAAA; 5941: } 5942: 5943: ul.LC_parm_parmlist li { 5944: display: inline-block; 5945: padding: 0.3em 0.8em; 5946: vertical-align: top; 5947: width: 150px; 5948: border-top:1px solid $lg_border_color; 5949: } 5950: 5951: td.LC_parm_overview_level_menu, 5952: td.LC_parm_overview_map_menu, 5953: td.LC_parm_overview_parm_selectors, 5954: td.LC_parm_overview_restrictions { 5955: border: 1px solid black; 5956: border-collapse: collapse; 5957: } 5958: 5959: table.LC_parm_overview_restrictions td { 5960: border-width: 1px 4px 1px 4px; 5961: border-style: solid; 5962: border-color: $pgbg; 5963: text-align: center; 5964: } 5965: 5966: table.LC_parm_overview_restrictions th { 5967: background: $tabbg; 5968: border-width: 1px 4px 1px 4px; 5969: border-style: solid; 5970: border-color: $pgbg; 5971: } 5972: 5973: table#LC_helpmenu { 5974: border: none; 5975: height: 55px; 5976: border-spacing: 0; 5977: } 5978: 5979: table#LC_helpmenu fieldset legend { 5980: font-size: larger; 5981: } 5982: 5983: table#LC_helpmenu_links { 5984: width: 100%; 5985: border: 1px solid black; 5986: background: $pgbg; 5987: padding: 0; 5988: border-spacing: 1px; 5989: } 5990: 5991: table#LC_helpmenu_links tr td { 5992: padding: 1px; 5993: background: $tabbg; 5994: text-align: center; 5995: font-weight: bold; 5996: } 5997: 5998: table#LC_helpmenu_links a:link, 5999: table#LC_helpmenu_links a:visited, 6000: table#LC_helpmenu_links a:active { 6001: text-decoration: none; 6002: color: $font; 6003: } 6004: 6005: table#LC_helpmenu_links a:hover { 6006: text-decoration: underline; 6007: color: $vlink; 6008: } 6009: 6010: .LC_chrt_popup_exists { 6011: border: 1px solid #339933; 6012: margin: -1px; 6013: } 6014: 6015: .LC_chrt_popup_up { 6016: border: 1px solid yellow; 6017: margin: -1px; 6018: } 6019: 6020: .LC_chrt_popup { 6021: border: 1px solid #8888FF; 6022: background: #CCCCFF; 6023: } 6024: 6025: table.LC_pick_box { 6026: border-collapse: separate; 6027: background: white; 6028: border: 1px solid black; 6029: border-spacing: 1px; 6030: } 6031: 6032: table.LC_pick_box td.LC_pick_box_title { 6033: background: $sidebg; 6034: font-weight: bold; 6035: text-align: left; 6036: vertical-align: top; 6037: width: 184px; 6038: padding: 8px; 6039: } 6040: 6041: table.LC_pick_box td.LC_pick_box_value { 6042: text-align: left; 6043: padding: 8px; 6044: } 6045: 6046: table.LC_pick_box td.LC_pick_box_select { 6047: text-align: left; 6048: padding: 8px; 6049: } 6050: 6051: table.LC_pick_box td.LC_pick_box_separator { 6052: padding: 0; 6053: height: 1px; 6054: background: black; 6055: } 6056: 6057: table.LC_pick_box td.LC_pick_box_submit { 6058: text-align: right; 6059: } 6060: 6061: table.LC_pick_box td.LC_evenrow_value { 6062: text-align: left; 6063: padding: 8px; 6064: background-color: $data_table_light; 6065: } 6066: 6067: table.LC_pick_box td.LC_oddrow_value { 6068: text-align: left; 6069: padding: 8px; 6070: background-color: $data_table_light; 6071: } 6072: 6073: span.LC_helpform_receipt_cat { 6074: font-weight: bold; 6075: } 6076: 6077: table.LC_group_priv_box { 6078: background: white; 6079: border: 1px solid black; 6080: border-spacing: 1px; 6081: } 6082: 6083: table.LC_group_priv_box td.LC_pick_box_title { 6084: background: $tabbg; 6085: font-weight: bold; 6086: text-align: right; 6087: width: 184px; 6088: } 6089: 6090: table.LC_group_priv_box td.LC_groups_fixed { 6091: background: $data_table_light; 6092: text-align: center; 6093: } 6094: 6095: table.LC_group_priv_box td.LC_groups_optional { 6096: background: $data_table_dark; 6097: text-align: center; 6098: } 6099: 6100: table.LC_group_priv_box td.LC_groups_functionality { 6101: background: $data_table_darker; 6102: text-align: center; 6103: font-weight: bold; 6104: } 6105: 6106: table.LC_group_priv td { 6107: text-align: left; 6108: padding: 0; 6109: } 6110: 6111: .LC_navbuttons { 6112: margin: 2ex 0ex 2ex 0ex; 6113: } 6114: 6115: .LC_topic_bar { 6116: font-weight: bold; 6117: background: $tabbg; 6118: margin: 1em 0em 1em 2em; 6119: padding: 3px; 6120: font-size: 1.2em; 6121: } 6122: 6123: .LC_topic_bar span { 6124: left: 0.5em; 6125: position: absolute; 6126: vertical-align: middle; 6127: font-size: 1.2em; 6128: } 6129: 6130: table.LC_course_group_status { 6131: margin: 20px; 6132: } 6133: 6134: table.LC_status_selector td { 6135: vertical-align: top; 6136: text-align: center; 6137: padding: 4px; 6138: } 6139: 6140: div.LC_feedback_link { 6141: clear: both; 6142: background: $sidebg; 6143: width: 100%; 6144: padding-bottom: 10px; 6145: border: 1px $tabbg solid; 6146: height: 22px; 6147: line-height: 22px; 6148: padding-top: 5px; 6149: } 6150: 6151: div.LC_feedback_link img { 6152: height: 22px; 6153: vertical-align:middle; 6154: } 6155: 6156: div.LC_feedback_link a { 6157: text-decoration: none; 6158: } 6159: 6160: div.LC_comblock { 6161: display:inline; 6162: color:$font; 6163: font-size:90%; 6164: } 6165: 6166: div.LC_feedback_link div.LC_comblock { 6167: padding-left:5px; 6168: } 6169: 6170: div.LC_feedback_link div.LC_comblock a { 6171: color:$font; 6172: } 6173: 6174: span.LC_feedback_link { 6175: /* background: $feedback_link_bg; */ 6176: font-size: larger; 6177: } 6178: 6179: span.LC_message_link { 6180: /* background: $feedback_link_bg; */ 6181: font-size: larger; 6182: position: absolute; 6183: right: 1em; 6184: } 6185: 6186: table.LC_prior_tries { 6187: border: 1px solid #000000; 6188: border-collapse: separate; 6189: border-spacing: 1px; 6190: } 6191: 6192: table.LC_prior_tries td { 6193: padding: 2px; 6194: } 6195: 6196: .LC_answer_correct { 6197: background: lightgreen; 6198: color: darkgreen; 6199: padding: 6px; 6200: } 6201: 6202: .LC_answer_charged_try { 6203: background: #FFAAAA; 6204: color: darkred; 6205: padding: 6px; 6206: } 6207: 6208: .LC_answer_not_charged_try, 6209: .LC_answer_no_grade, 6210: .LC_answer_late { 6211: background: lightyellow; 6212: color: black; 6213: padding: 6px; 6214: } 6215: 6216: .LC_answer_previous { 6217: background: lightblue; 6218: color: darkblue; 6219: padding: 6px; 6220: } 6221: 6222: .LC_answer_no_message { 6223: background: #FFFFFF; 6224: color: black; 6225: padding: 6px; 6226: } 6227: 6228: .LC_answer_unknown { 6229: background: orange; 6230: color: black; 6231: padding: 6px; 6232: } 6233: 6234: span.LC_prior_numerical, 6235: span.LC_prior_string, 6236: span.LC_prior_custom, 6237: span.LC_prior_reaction, 6238: span.LC_prior_math { 6239: font-family: $mono; 6240: white-space: pre; 6241: } 6242: 6243: span.LC_prior_string { 6244: font-family: $mono; 6245: white-space: pre; 6246: } 6247: 6248: table.LC_prior_option { 6249: width: 100%; 6250: border-collapse: collapse; 6251: } 6252: 6253: table.LC_prior_rank, 6254: table.LC_prior_match { 6255: border-collapse: collapse; 6256: } 6257: 6258: table.LC_prior_option tr td, 6259: table.LC_prior_rank tr td, 6260: table.LC_prior_match tr td { 6261: border: 1px solid #000000; 6262: } 6263: 6264: .LC_nobreak { 6265: white-space: nowrap; 6266: } 6267: 6268: span.LC_cusr_emph { 6269: font-style: italic; 6270: } 6271: 6272: span.LC_cusr_subheading { 6273: font-weight: normal; 6274: font-size: 85%; 6275: } 6276: 6277: div.LC_docs_entry_move { 6278: border: 1px solid #BBBBBB; 6279: background: #DDDDDD; 6280: width: 22px; 6281: padding: 1px; 6282: margin: 0; 6283: } 6284: 6285: table.LC_data_table tr > td.LC_docs_entry_commands, 6286: table.LC_data_table tr > td.LC_docs_entry_parameter { 6287: font-size: x-small; 6288: } 6289: 6290: .LC_docs_entry_parameter { 6291: white-space: nowrap; 6292: } 6293: 6294: .LC_docs_copy { 6295: color: #000099; 6296: } 6297: 6298: .LC_docs_cut { 6299: color: #550044; 6300: } 6301: 6302: .LC_docs_rename { 6303: color: #009900; 6304: } 6305: 6306: .LC_docs_remove { 6307: color: #990000; 6308: } 6309: 6310: .LC_docs_reinit_warn, 6311: .LC_docs_ext_edit { 6312: font-size: x-small; 6313: } 6314: 6315: table.LC_docs_adddocs td, 6316: table.LC_docs_adddocs th { 6317: border: 1px solid #BBBBBB; 6318: padding: 4px; 6319: background: #DDDDDD; 6320: } 6321: 6322: table.LC_sty_begin { 6323: background: #BBFFBB; 6324: } 6325: 6326: table.LC_sty_end { 6327: background: #FFBBBB; 6328: } 6329: 6330: table.LC_double_column { 6331: border-width: 0; 6332: border-collapse: collapse; 6333: width: 100%; 6334: padding: 2px; 6335: } 6336: 6337: table.LC_double_column tr td.LC_left_col { 6338: top: 2px; 6339: left: 2px; 6340: width: 47%; 6341: vertical-align: top; 6342: } 6343: 6344: table.LC_double_column tr td.LC_right_col { 6345: top: 2px; 6346: right: 2px; 6347: width: 47%; 6348: vertical-align: top; 6349: } 6350: 6351: div.LC_left_float { 6352: float: left; 6353: padding-right: 5%; 6354: padding-bottom: 4px; 6355: } 6356: 6357: div.LC_clear_float_header { 6358: padding-bottom: 2px; 6359: } 6360: 6361: div.LC_clear_float_footer { 6362: padding-top: 10px; 6363: clear: both; 6364: } 6365: 6366: div.LC_grade_show_user { 6367: /* border-left: 5px solid $sidebg; */ 6368: border-top: 5px solid #000000; 6369: margin: 50px 0 0 0; 6370: padding: 15px 0 5px 10px; 6371: } 6372: 6373: div.LC_grade_show_user_odd_row { 6374: /* border-left: 5px solid #000000; */ 6375: } 6376: 6377: div.LC_grade_show_user div.LC_Box { 6378: margin-right: 50px; 6379: } 6380: 6381: div.LC_grade_submissions, 6382: div.LC_grade_message_center, 6383: div.LC_grade_info_links { 6384: margin: 5px; 6385: width: 99%; 6386: background: #FFFFFF; 6387: } 6388: 6389: div.LC_grade_submissions_header, 6390: div.LC_grade_message_center_header { 6391: font-weight: bold; 6392: font-size: large; 6393: } 6394: 6395: div.LC_grade_submissions_body, 6396: div.LC_grade_message_center_body { 6397: border: 1px solid black; 6398: width: 99%; 6399: background: #FFFFFF; 6400: } 6401: 6402: table.LC_scantron_action { 6403: width: 100%; 6404: } 6405: 6406: table.LC_scantron_action tr th { 6407: font-weight:bold; 6408: font-style:normal; 6409: } 6410: 6411: .LC_edit_problem_header, 6412: div.LC_edit_problem_footer { 6413: font-weight: normal; 6414: font-size: medium; 6415: margin: 2px; 6416: background-color: $sidebg; 6417: } 6418: 6419: div.LC_edit_problem_header, 6420: div.LC_edit_problem_header div, 6421: div.LC_edit_problem_footer, 6422: div.LC_edit_problem_footer div, 6423: div.LC_edit_problem_editxml_header, 6424: div.LC_edit_problem_editxml_header div { 6425: margin-top: 5px; 6426: } 6427: 6428: div.LC_edit_problem_header_title { 6429: font-weight: bold; 6430: font-size: larger; 6431: background: $tabbg; 6432: padding: 3px; 6433: margin: 0 0 5px 0; 6434: } 6435: 6436: table.LC_edit_problem_header_title { 6437: width: 100%; 6438: background: $tabbg; 6439: } 6440: 6441: div.LC_edit_problem_discards { 6442: float: left; 6443: padding-bottom: 5px; 6444: } 6445: 6446: div.LC_edit_problem_saves { 6447: float: right; 6448: padding-bottom: 5px; 6449: } 6450: 6451: img.stift { 6452: border-width: 0; 6453: vertical-align: middle; 6454: } 6455: 6456: table td.LC_mainmenu_col_fieldset { 6457: vertical-align: top; 6458: } 6459: 6460: div.LC_createcourse { 6461: margin: 10px 10px 10px 10px; 6462: } 6463: 6464: .LC_dccid { 6465: margin: 0.2em 0 0 0; 6466: padding: 0; 6467: font-size: 90%; 6468: display:none; 6469: } 6470: 6471: ol.LC_primary_menu a:hover, 6472: ol#LC_MenuBreadcrumbs a:hover, 6473: ol#LC_PathBreadcrumbs a:hover, 6474: ul#LC_secondary_menu a:hover, 6475: .LC_FormSectionClearButton input:hover 6476: ul.LC_TabContent li:hover a { 6477: color:$button_hover; 6478: text-decoration:none; 6479: } 6480: 6481: h1 { 6482: padding: 0; 6483: line-height:130%; 6484: } 6485: 6486: h2, 6487: h3, 6488: h4, 6489: h5, 6490: h6 { 6491: margin: 5px 0 5px 0; 6492: padding: 0; 6493: line-height:130%; 6494: } 6495: 6496: .LC_hcell { 6497: padding:3px 15px 3px 15px; 6498: margin: 0; 6499: background-color:$tabbg; 6500: color:$fontmenu; 6501: border-bottom:solid 1px $lg_border_color; 6502: } 6503: 6504: .LC_Box > .LC_hcell { 6505: margin: 0 -10px 10px -10px; 6506: } 6507: 6508: .LC_noBorder { 6509: border: 0; 6510: } 6511: 6512: .LC_FormSectionClearButton input { 6513: background-color:transparent; 6514: border: none; 6515: cursor:pointer; 6516: text-decoration:underline; 6517: } 6518: 6519: .LC_help_open_topic { 6520: color: #FFFFFF; 6521: background-color: #EEEEFF; 6522: margin: 1px; 6523: padding: 4px; 6524: border: 1px solid #000033; 6525: white-space: nowrap; 6526: /* vertical-align: middle; */ 6527: } 6528: 6529: dl, 6530: ul, 6531: div, 6532: fieldset { 6533: margin: 10px 10px 10px 0; 6534: /* overflow: hidden; */ 6535: } 6536: 6537: fieldset > legend { 6538: font-weight: bold; 6539: padding: 0 5px 0 5px; 6540: } 6541: 6542: #LC_nav_bar { 6543: float: left; 6544: background-color: $pgbg_or_bgcolor; 6545: margin: 0 0 2px 0; 6546: } 6547: 6548: #LC_realm { 6549: margin: 0.2em 0 0 0; 6550: padding: 0; 6551: font-weight: bold; 6552: text-align: center; 6553: background-color: $pgbg_or_bgcolor; 6554: } 6555: 6556: #LC_nav_bar em { 6557: font-weight: bold; 6558: font-style: normal; 6559: } 6560: 6561: ol.LC_primary_menu { 6562: float: right; 6563: margin: 0; 6564: padding: 0; 6565: background-color: $pgbg_or_bgcolor; 6566: } 6567: 6568: ol#LC_PathBreadcrumbs { 6569: margin: 0; 6570: } 6571: 6572: ol.LC_primary_menu li { 6573: color: RGB(80, 80, 80); 6574: vertical-align: middle; 6575: text-align: left; 6576: list-style: none; 6577: float: left; 6578: } 6579: 6580: ol.LC_primary_menu li a { 6581: display: block; 6582: margin: 0; 6583: padding: 0 5px 0 10px; 6584: text-decoration: none; 6585: } 6586: 6587: ol.LC_primary_menu li ul { 6588: display: none; 6589: width: 10em; 6590: background-color: $data_table_light; 6591: } 6592: 6593: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul { 6594: display: block; 6595: position: absolute; 6596: margin: 0; 6597: padding: 0; 6598: z-index: 2; 6599: } 6600: 6601: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li { 6602: font-size: 90%; 6603: vertical-align: top; 6604: float: none; 6605: border-left: 1px solid black; 6606: border-right: 1px solid black; 6607: } 6608: 6609: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a { 6610: background-color:$data_table_light; 6611: } 6612: 6613: ol.LC_primary_menu li li a:hover { 6614: color:$button_hover; 6615: background-color:$data_table_dark; 6616: } 6617: 6618: ol.LC_primary_menu li img { 6619: vertical-align: bottom; 6620: height: 1.1em; 6621: margin: 0.2em 0 0 0; 6622: } 6623: 6624: ol.LC_primary_menu a { 6625: color: RGB(80, 80, 80); 6626: text-decoration: none; 6627: } 6628: 6629: ol.LC_primary_menu a.LC_new_message { 6630: font-weight:bold; 6631: color: darkred; 6632: } 6633: 6634: ol.LC_docs_parameters { 6635: margin-left: 0; 6636: padding: 0; 6637: list-style: none; 6638: } 6639: 6640: ol.LC_docs_parameters li { 6641: margin: 0; 6642: padding-right: 20px; 6643: display: inline; 6644: } 6645: 6646: ol.LC_docs_parameters li:before { 6647: content: "\\002022 \\0020"; 6648: } 6649: 6650: li.LC_docs_parameters_title { 6651: font-weight: bold; 6652: } 6653: 6654: ol.LC_docs_parameters li.LC_docs_parameters_title:before { 6655: content: ""; 6656: } 6657: 6658: ul#LC_secondary_menu { 6659: clear: both; 6660: color: $fontmenu; 6661: background: $tabbg; 6662: list-style: none; 6663: padding: 0; 6664: margin: 0; 6665: width: 100%; 6666: text-align: left; 6667: } 6668: 6669: ul#LC_secondary_menu li { 6670: font-weight: bold; 6671: line-height: 1.8em; 6672: padding: 0 0.8em; 6673: border-right: 1px solid black; 6674: display: inline; 6675: vertical-align: middle; 6676: } 6677: 6678: ul.LC_TabContent { 6679: display:block; 6680: background: $sidebg; 6681: border-bottom: solid 1px $lg_border_color; 6682: list-style:none; 6683: margin: -1px -10px 0 -10px; 6684: padding: 0; 6685: } 6686: 6687: ul.LC_TabContent li, 6688: ul.LC_TabContentBigger li { 6689: float:left; 6690: } 6691: 6692: ul#LC_secondary_menu li a { 6693: color: $fontmenu; 6694: text-decoration: none; 6695: } 6696: 6697: ul.LC_TabContent { 6698: min-height:20px; 6699: } 6700: 6701: ul.LC_TabContent li { 6702: vertical-align:middle; 6703: padding: 0 16px 0 10px; 6704: background-color:$tabbg; 6705: border-bottom:solid 1px $lg_border_color; 6706: border-left: solid 1px $font; 6707: } 6708: 6709: ul.LC_TabContent .right { 6710: float:right; 6711: } 6712: 6713: ul.LC_TabContent li a, 6714: ul.LC_TabContent li { 6715: color:rgb(47,47,47); 6716: text-decoration:none; 6717: font-size:95%; 6718: font-weight:bold; 6719: min-height:20px; 6720: } 6721: 6722: ul.LC_TabContent li a:hover, 6723: ul.LC_TabContent li a:focus { 6724: color: $button_hover; 6725: background:none; 6726: outline:none; 6727: } 6728: 6729: ul.LC_TabContent li:hover { 6730: color: $button_hover; 6731: cursor:pointer; 6732: } 6733: 6734: ul.LC_TabContent li.active { 6735: color: $font; 6736: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center; 6737: border-bottom:solid 1px #FFFFFF; 6738: cursor: default; 6739: } 6740: 6741: ul.LC_TabContent li.active a { 6742: color:$font; 6743: background:#FFFFFF; 6744: outline: none; 6745: } 6746: 6747: ul.LC_TabContent li.goback { 6748: float: left; 6749: border-left: none; 6750: } 6751: 6752: #maincoursedoc { 6753: clear:both; 6754: } 6755: 6756: ul.LC_TabContentBigger { 6757: display:block; 6758: list-style:none; 6759: padding: 0; 6760: } 6761: 6762: ul.LC_TabContentBigger li { 6763: vertical-align:bottom; 6764: height: 30px; 6765: font-size:110%; 6766: font-weight:bold; 6767: color: #737373; 6768: } 6769: 6770: ul.LC_TabContentBigger li.active { 6771: position: relative; 6772: top: 1px; 6773: } 6774: 6775: ul.LC_TabContentBigger li a { 6776: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat; 6777: height: 30px; 6778: line-height: 30px; 6779: text-align: center; 6780: display: block; 6781: text-decoration: none; 6782: outline: none; 6783: } 6784: 6785: ul.LC_TabContentBigger li.active a { 6786: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat; 6787: color:$font; 6788: } 6789: 6790: ul.LC_TabContentBigger li b { 6791: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom; 6792: display: block; 6793: float: left; 6794: padding: 0 30px; 6795: border-bottom: 1px solid $lg_border_color; 6796: } 6797: 6798: ul.LC_TabContentBigger li:hover b { 6799: color:$button_hover; 6800: } 6801: 6802: ul.LC_TabContentBigger li.active b { 6803: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat; 6804: color:$font; 6805: border: 0; 6806: } 6807: 6808: 6809: ul.LC_CourseBreadcrumbs { 6810: background: $sidebg; 6811: height: 2em; 6812: padding-left: 10px; 6813: margin: 0; 6814: list-style-position: inside; 6815: } 6816: 6817: ol#LC_MenuBreadcrumbs, 6818: ol#LC_PathBreadcrumbs { 6819: padding-left: 10px; 6820: margin: 0; 6821: height: 2.5em; /* equal to #LC_breadcrumbs line-height */ 6822: } 6823: 6824: ol#LC_MenuBreadcrumbs li, 6825: ol#LC_PathBreadcrumbs li, 6826: ul.LC_CourseBreadcrumbs li { 6827: display: inline; 6828: white-space: normal; 6829: } 6830: 6831: ol#LC_MenuBreadcrumbs li a, 6832: ul.LC_CourseBreadcrumbs li a { 6833: text-decoration: none; 6834: font-size:90%; 6835: } 6836: 6837: ol#LC_MenuBreadcrumbs h1 { 6838: display: inline; 6839: font-size: 90%; 6840: line-height: 2.5em; 6841: margin: 0; 6842: padding: 0; 6843: } 6844: 6845: ol#LC_PathBreadcrumbs li a { 6846: text-decoration:none; 6847: font-size:100%; 6848: font-weight:bold; 6849: } 6850: 6851: .LC_Box { 6852: border: solid 1px $lg_border_color; 6853: padding: 0 10px 10px 10px; 6854: } 6855: 6856: .LC_DocsBox { 6857: border: solid 1px $lg_border_color; 6858: padding: 0 0 10px 10px; 6859: } 6860: 6861: .LC_AboutMe_Image { 6862: float:left; 6863: margin-right:10px; 6864: } 6865: 6866: .LC_Clear_AboutMe_Image { 6867: clear:left; 6868: } 6869: 6870: dl.LC_ListStyleClean dt { 6871: padding-right: 5px; 6872: display: table-header-group; 6873: } 6874: 6875: dl.LC_ListStyleClean dd { 6876: display: table-row; 6877: } 6878: 6879: .LC_ListStyleClean, 6880: .LC_ListStyleSimple, 6881: .LC_ListStyleNormal, 6882: .LC_ListStyleSpecial { 6883: /* display:block; */ 6884: list-style-position: inside; 6885: list-style-type: none; 6886: overflow: hidden; 6887: padding: 0; 6888: } 6889: 6890: .LC_ListStyleSimple li, 6891: .LC_ListStyleSimple dd, 6892: .LC_ListStyleNormal li, 6893: .LC_ListStyleNormal dd, 6894: .LC_ListStyleSpecial li, 6895: .LC_ListStyleSpecial dd { 6896: margin: 0; 6897: padding: 5px 5px 5px 10px; 6898: clear: both; 6899: } 6900: 6901: .LC_ListStyleClean li, 6902: .LC_ListStyleClean dd { 6903: padding-top: 0; 6904: padding-bottom: 0; 6905: } 6906: 6907: .LC_ListStyleSimple dd, 6908: .LC_ListStyleSimple li { 6909: border-bottom: solid 1px $lg_border_color; 6910: } 6911: 6912: .LC_ListStyleSpecial li, 6913: .LC_ListStyleSpecial dd { 6914: list-style-type: none; 6915: background-color: RGB(220, 220, 220); 6916: margin-bottom: 4px; 6917: } 6918: 6919: table.LC_SimpleTable { 6920: margin:5px; 6921: border:solid 1px $lg_border_color; 6922: } 6923: 6924: table.LC_SimpleTable tr { 6925: padding: 0; 6926: border:solid 1px $lg_border_color; 6927: } 6928: 6929: table.LC_SimpleTable thead { 6930: background:rgb(220,220,220); 6931: } 6932: 6933: div.LC_columnSection { 6934: display: block; 6935: clear: both; 6936: overflow: hidden; 6937: margin: 0; 6938: } 6939: 6940: div.LC_columnSection>* { 6941: float: left; 6942: margin: 10px 20px 10px 0; 6943: overflow:hidden; 6944: } 6945: 6946: table em { 6947: font-weight: bold; 6948: font-style: normal; 6949: } 6950: 6951: table.LC_tableBrowseRes, 6952: table.LC_tableOfContent { 6953: border:none; 6954: border-spacing: 1px; 6955: padding: 3px; 6956: background-color: #FFFFFF; 6957: font-size: 90%; 6958: } 6959: 6960: table.LC_tableOfContent { 6961: border-collapse: collapse; 6962: } 6963: 6964: table.LC_tableBrowseRes a, 6965: table.LC_tableOfContent a { 6966: background-color: transparent; 6967: text-decoration: none; 6968: } 6969: 6970: table.LC_tableOfContent img { 6971: border: none; 6972: height: 1.3em; 6973: vertical-align: text-bottom; 6974: margin-right: 0.3em; 6975: } 6976: 6977: a#LC_content_toolbar_firsthomework { 6978: background-image:url(/res/adm/pages/open-first-problem.gif); 6979: } 6980: 6981: a#LC_content_toolbar_everything { 6982: background-image:url(/res/adm/pages/show-all.gif); 6983: } 6984: 6985: a#LC_content_toolbar_uncompleted { 6986: background-image:url(/res/adm/pages/show-incomplete-problems.gif); 6987: } 6988: 6989: #LC_content_toolbar_clearbubbles { 6990: background-image:url(/res/adm/pages/mark-discussionentries-read.gif); 6991: } 6992: 6993: a#LC_content_toolbar_changefolder { 6994: background : url(/res/adm/pages/close-all-folders.gif) top center ; 6995: } 6996: 6997: a#LC_content_toolbar_changefolder_toggled { 6998: background-image:url(/res/adm/pages/open-all-folders.gif); 6999: } 7000: 7001: a#LC_content_toolbar_edittoplevel { 7002: background-image:url(/res/adm/pages/edittoplevel.gif); 7003: } 7004: 7005: ul#LC_toolbar li a:hover { 7006: background-position: bottom center; 7007: } 7008: 7009: ul#LC_toolbar { 7010: padding: 0; 7011: margin: 2px; 7012: list-style:none; 7013: position:relative; 7014: background-color:white; 7015: overflow: auto; 7016: } 7017: 7018: ul#LC_toolbar li { 7019: border:1px solid white; 7020: padding: 0; 7021: margin: 0; 7022: float: left; 7023: display:inline; 7024: vertical-align:middle; 7025: white-space: nowrap; 7026: } 7027: 7028: 7029: a.LC_toolbarItem { 7030: display:block; 7031: padding: 0; 7032: margin: 0; 7033: height: 32px; 7034: width: 32px; 7035: color:white; 7036: border: none; 7037: background-repeat:no-repeat; 7038: background-color:transparent; 7039: } 7040: 7041: ul.LC_funclist { 7042: margin: 0; 7043: padding: 0.5em 1em 0.5em 0; 7044: } 7045: 7046: ul.LC_funclist > li:first-child { 7047: font-weight:bold; 7048: margin-left:0.8em; 7049: } 7050: 7051: ul.LC_funclist + ul.LC_funclist { 7052: /* 7053: left border as a seperator if we have more than 7054: one list 7055: */ 7056: border-left: 1px solid $sidebg; 7057: /* 7058: this hides the left border behind the border of the 7059: outer box if element is wrapped to the next 'line' 7060: */ 7061: margin-left: -1px; 7062: } 7063: 7064: ul.LC_funclist li { 7065: display: inline; 7066: white-space: nowrap; 7067: margin: 0 0 0 25px; 7068: line-height: 150%; 7069: } 7070: 7071: .LC_hidden { 7072: display: none; 7073: } 7074: 7075: .LCmodal-overlay { 7076: position:fixed; 7077: top:0; 7078: right:0; 7079: bottom:0; 7080: left:0; 7081: height:100%; 7082: width:100%; 7083: margin:0; 7084: padding:0; 7085: background:#999; 7086: opacity:.75; 7087: filter: alpha(opacity=75); 7088: -moz-opacity: 0.75; 7089: z-index:101; 7090: } 7091: 7092: * html .LCmodal-overlay { 7093: position: absolute; 7094: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); 7095: } 7096: 7097: .LCmodal-window { 7098: position:fixed; 7099: top:50%; 7100: left:50%; 7101: margin:0; 7102: padding:0; 7103: z-index:102; 7104: } 7105: 7106: * html .LCmodal-window { 7107: position:absolute; 7108: } 7109: 7110: .LCclose-window { 7111: position:absolute; 7112: width:32px; 7113: height:32px; 7114: right:8px; 7115: top:8px; 7116: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top; 7117: text-indent:-99999px; 7118: overflow:hidden; 7119: cursor:pointer; 7120: } 7121: 7122: /* 7123: styles used by TTH when "Default set of options to pass to tth/m 7124: when converting TeX" in course settings has been set 7125: 7126: option passed: -t 7127: 7128: */ 7129: 7130: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;} 7131: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;} 7132: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;} 7133: td div.norm {line-height:normal;} 7134: 7135: /* 7136: option passed -y3 7137: */ 7138: 7139: span.roman {font-family: serif; font-style: normal; font-weight: normal;} 7140: span.overacc2 {position: relative; left: .8em; top: -1.2ex;} 7141: span.overacc1 {position: relative; left: .6em; top: -1.2ex;} 7142: 7143: END 7144: } 7145: 7146: =pod 7147: 7148: =item * &headtag() 7149: 7150: Returns a uniform footer for LON-CAPA web pages. 7151: 7152: Inputs: $title - optional title for the head 7153: $head_extra - optional extra HTML to put inside the <head> 7154: $args - optional arguments 7155: force_register - if is true call registerurl so the remote is 7156: informed 7157: redirect -> array ref of 7158: 1- seconds before redirect occurs 7159: 2- url to redirect to 7160: 3- whether the side effect should occur 7161: (side effect of setting 7162: $env{'internal.head.redirect'} to the url 7163: redirected too) 7164: domain -> force to color decorate a page for a specific 7165: domain 7166: function -> force usage of a specific rolish color scheme 7167: bgcolor -> override the default page bgcolor 7168: no_auto_mt_title 7169: -> prevent &mt()ing the title arg 7170: 7171: =cut 7172: 7173: sub headtag { 7174: my ($title,$head_extra,$args) = @_; 7175: 7176: my $function = $args->{'function'} || &get_users_function(); 7177: my $domain = $args->{'domain'} || &determinedomain(); 7178: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain); 7179: my $url = join(':',$env{'user.name'},$env{'user.domain'}, 7180: $Apache::lonnet::perlvar{'lonVersion'}, 7181: #time(), 7182: $env{'environment.color.timestamp'}, 7183: $function,$domain,$bgcolor); 7184: 7185: $url = '/adm/css/'.&escape($url).'.css'; 7186: 7187: my $result = 7188: '<head>'. 7189: &font_settings(); 7190: 7191: my $inhibitprint = &print_suppression(); 7192: 7193: if (!$args->{'frameset'}) { 7194: $result .= &Apache::lonhtmlcommon::htmlareaheaders(); 7195: } 7196: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) { 7197: $result .= Apache::lonxml::display_title(); 7198: } 7199: if (!$args->{'no_nav_bar'} 7200: && !$args->{'only_body'} 7201: && !$args->{'frameset'}) { 7202: $result .= &help_menu_js(); 7203: $result.=&modal_window(); 7204: $result.=&togglebox_script(); 7205: $result.=&wishlist_window(); 7206: $result.=&LCprogressbarUpdate_script(); 7207: } else { 7208: if ($args->{'add_modal'}) { 7209: $result.=&modal_window(); 7210: } 7211: if ($args->{'add_wishlist'}) { 7212: $result.=&wishlist_window(); 7213: } 7214: if ($args->{'add_togglebox'}) { 7215: $result.=&togglebox_script(); 7216: } 7217: if ($args->{'add_progressbar'}) { 7218: $result.=&LCprogressbarUpdate_script(); 7219: } 7220: } 7221: if (ref($args->{'redirect'})) { 7222: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}}; 7223: $url = &Apache::lonenc::check_encrypt($url); 7224: if (!$inhibit_continue) { 7225: $env{'internal.head.redirect'} = $url; 7226: } 7227: $result.=<<ADDMETA 7228: <meta http-equiv="pragma" content="no-cache" /> 7229: <meta http-equiv="Refresh" content="$time; url=$url" /> 7230: ADDMETA 7231: } 7232: if (!defined($title)) { 7233: $title = 'The LearningOnline Network with CAPA'; 7234: } 7235: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); } 7236: $result .= '<title> LON-CAPA '.$title.'</title>' 7237: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />' 7238: .$inhibitprint 7239: .$head_extra; 7240: return $result.'</head>'; 7241: } 7242: 7243: =pod 7244: 7245: =item * &font_settings() 7246: 7247: Returns neccessary <meta> to set the proper encoding 7248: 7249: Inputs: none 7250: 7251: =cut 7252: 7253: sub font_settings { 7254: my $headerstring=''; 7255: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) { 7256: $headerstring.= 7257: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; 7258: } 7259: return $headerstring; 7260: } 7261: 7262: =pod 7263: 7264: =item * &print_suppression() 7265: 7266: In course context returns css which causes the body to be blank when media="print", 7267: if printout generation is unavailable for the current resource. 7268: 7269: This could be because: 7270: 7271: (a) printstartdate is in the future 7272: 7273: (b) printenddate is in the past 7274: 7275: (c) there is an active exam block with "printout" 7276: functionality blocked 7277: 7278: Users with pav, pfo or evb privileges are exempt. 7279: 7280: Inputs: none 7281: 7282: =cut 7283: 7284: 7285: sub print_suppression { 7286: my $noprint; 7287: if ($env{'request.course.id'}) { 7288: my $scope = $env{'request.course.id'}; 7289: if ((&Apache::lonnet::allowed('pav',$scope)) || 7290: (&Apache::lonnet::allowed('pfo',$scope))) { 7291: return; 7292: } 7293: if ($env{'request.course.sec'} ne '') { 7294: $scope .= "/$env{'request.course.sec'}"; 7295: if ((&Apache::lonnet::allowed('pav',$scope)) || 7296: (&Apache::lonnet::allowed('pfo',$scope))) { 7297: return; 7298: } 7299: } 7300: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 7301: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 7302: my $blocked = &blocking_status('printout',$cnum,$cdom); 7303: if ($blocked) { 7304: my $checkrole = "cm./$cdom/$cnum"; 7305: if ($env{'request.course.sec'} ne '') { 7306: $checkrole .= "/$env{'request.course.sec'}"; 7307: } 7308: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) && 7309: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) { 7310: $noprint = 1; 7311: } 7312: } 7313: unless ($noprint) { 7314: my $symb = &Apache::lonnet::symbread(); 7315: if ($symb ne '') { 7316: my $navmap = Apache::lonnavmaps::navmap->new(); 7317: if (ref($navmap)) { 7318: my $res = $navmap->getBySymb($symb); 7319: if (ref($res)) { 7320: if (!$res->resprintable()) { 7321: $noprint = 1; 7322: } 7323: } 7324: } 7325: } 7326: } 7327: if ($noprint) { 7328: return <<"ENDSTYLE"; 7329: <style type="text/css" media="print"> 7330: body { display:none } 7331: </style> 7332: ENDSTYLE 7333: } 7334: } 7335: return; 7336: } 7337: 7338: =pod 7339: 7340: =item * &xml_begin() 7341: 7342: Returns the needed doctype and <html> 7343: 7344: Inputs: none 7345: 7346: =cut 7347: 7348: sub xml_begin { 7349: my $output=''; 7350: 7351: if ($env{'browser.mathml'}) { 7352: $output='<?xml version="1.0"?>' 7353: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n" 7354: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" ' 7355: 7356: # .'<!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">] >' 7357: .'<!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">' 7358: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 7359: .'xmlns="http://www.w3.org/1999/xhtml">'; 7360: } else { 7361: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' 7362: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; 7363: } 7364: return $output; 7365: } 7366: 7367: =pod 7368: 7369: =item * &start_page() 7370: 7371: Returns a complete <html> .. <body> section for LON-CAPA web pages. 7372: 7373: Inputs: 7374: 7375: =over 4 7376: 7377: $title - optional title for the page 7378: 7379: $head_extra - optional extra HTML to incude inside the <head> 7380: 7381: $args - additional optional args supported are: 7382: 7383: =over 8 7384: 7385: only_body -> is true will set &bodytag() onlybodytag 7386: arg on 7387: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on 7388: add_entries -> additional attributes to add to the <body> 7389: domain -> force to color decorate a page for a 7390: specific domain 7391: function -> force usage of a specific rolish color 7392: scheme 7393: redirect -> see &headtag() 7394: bgcolor -> override the default page bg color 7395: js_ready -> return a string ready for being used in 7396: a javascript writeln 7397: html_encode -> return a string ready for being used in 7398: a html attribute 7399: force_register -> if is true will turn on the &bodytag() 7400: $forcereg arg 7401: frameset -> if true will start with a <frameset> 7402: rather than <body> 7403: skip_phases -> hash ref of 7404: head -> skip the <html><head> generation 7405: body -> skip all <body> generation 7406: no_auto_mt_title -> prevent &mt()ing the title arg 7407: inherit_jsmath -> when creating popup window in a page, 7408: should it have jsmath forced on by the 7409: current page 7410: bread_crumbs -> Array containing breadcrumbs 7411: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs 7412: group -> includes the current group, if page is for a 7413: specific group 7414: 7415: =back 7416: 7417: =back 7418: 7419: =cut 7420: 7421: sub start_page { 7422: my ($title,$head_extra,$args) = @_; 7423: #&Apache::lonnet::logthis("start_page ".join(':',caller(0))); 7424: 7425: $env{'internal.start_page'}++; 7426: my ($result,@advtools); 7427: 7428: if (! exists($args->{'skip_phases'}{'head'}) ) { 7429: $result .= &xml_begin() . &headtag($title, $head_extra, $args); 7430: } 7431: 7432: if (! exists($args->{'skip_phases'}{'body'}) ) { 7433: if ($args->{'frameset'}) { 7434: my $attr_string = &make_attr_string($args->{'force_register'}, 7435: $args->{'add_entries'}); 7436: $result .= "\n<frameset $attr_string>\n"; 7437: } else { 7438: $result .= 7439: &bodytag($title, 7440: $args->{'function'}, $args->{'add_entries'}, 7441: $args->{'only_body'}, $args->{'domain'}, 7442: $args->{'force_register'}, $args->{'no_nav_bar'}, 7443: $args->{'bgcolor'}, $args, 7444: \@advtools); 7445: } 7446: } 7447: 7448: if ($args->{'js_ready'}) { 7449: $result = &js_ready($result); 7450: } 7451: if ($args->{'html_encode'}) { 7452: $result = &html_encode($result); 7453: } 7454: 7455: # Preparation for new and consistent functionlist at top of screen 7456: # if ($args->{'functionlist'}) { 7457: # $result .= &build_functionlist(); 7458: #} 7459: 7460: # Don't add anything more if only_body wanted or in const space 7461: return $result if $args->{'only_body'} 7462: || $env{'request.state'} eq 'construct'; 7463: 7464: #Breadcrumbs 7465: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) { 7466: &Apache::lonhtmlcommon::clear_breadcrumbs(); 7467: #if any br links exists, add them to the breadcrumbs 7468: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') { 7469: foreach my $crumb (@{$args->{'bread_crumbs'}}){ 7470: &Apache::lonhtmlcommon::add_breadcrumb($crumb); 7471: } 7472: } 7473: # if @advtools array contains items add then to the breadcrumbs 7474: if (@advtools > 0) { 7475: &Apache::lonmenu::advtools_crumbs(@advtools); 7476: } 7477: 7478: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs 7479: if(exists($args->{'bread_crumbs_component'})){ 7480: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'}); 7481: }else{ 7482: $result .= &Apache::lonhtmlcommon::breadcrumbs(); 7483: } 7484: } 7485: return $result; 7486: } 7487: 7488: sub end_page { 7489: my ($args) = @_; 7490: $env{'internal.end_page'}++; 7491: my $result; 7492: if ($args->{'discussion'}) { 7493: my ($target,$parser); 7494: if (ref($args->{'discussion'})) { 7495: ($target,$parser) =($args->{'discussion'}{'target'}, 7496: $args->{'discussion'}{'parser'}); 7497: } 7498: $result .= &Apache::lonxml::xmlend($target,$parser); 7499: } 7500: if ($args->{'frameset'}) { 7501: $result .= '</frameset>'; 7502: } else { 7503: $result .= &endbodytag($args); 7504: } 7505: unless ($args->{'notbody'}) { 7506: $result .= "\n</html>"; 7507: } 7508: 7509: if ($args->{'js_ready'}) { 7510: $result = &js_ready($result); 7511: } 7512: 7513: if ($args->{'html_encode'}) { 7514: $result = &html_encode($result); 7515: } 7516: 7517: return $result; 7518: } 7519: 7520: sub wishlist_window { 7521: return(<<'ENDWISHLIST'); 7522: <script type="text/javascript"> 7523: // <![CDATA[ 7524: // <!-- BEGIN LON-CAPA Internal 7525: function set_wishlistlink(title, path) { 7526: if (!title) { 7527: title = document.title; 7528: title = title.replace(/^LON-CAPA /,''); 7529: } 7530: if (!path) { 7531: path = location.pathname; 7532: } 7533: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path, 7534: 'wishlistNewLink','width=560,height=350,scrollbars=0'); 7535: } 7536: // END LON-CAPA Internal --> 7537: // ]]> 7538: </script> 7539: ENDWISHLIST 7540: } 7541: 7542: sub modal_window { 7543: return(<<'ENDMODAL'); 7544: <script type="text/javascript"> 7545: // <![CDATA[ 7546: // <!-- BEGIN LON-CAPA Internal 7547: var modalWindow = { 7548: parent:"body", 7549: windowId:null, 7550: content:null, 7551: width:null, 7552: height:null, 7553: close:function() 7554: { 7555: $(".LCmodal-window").remove(); 7556: $(".LCmodal-overlay").remove(); 7557: }, 7558: open:function() 7559: { 7560: var modal = ""; 7561: modal += "<div class=\"LCmodal-overlay\"></div>"; 7562: 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;\">"; 7563: modal += this.content; 7564: modal += "</div>"; 7565: 7566: $(this.parent).append(modal); 7567: 7568: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>"); 7569: $(".LCclose-window").click(function(){modalWindow.close();}); 7570: $(".LCmodal-overlay").click(function(){modalWindow.close();}); 7571: } 7572: }; 7573: var openMyModal = function(source,width,height,scrolling) 7574: { 7575: modalWindow.windowId = "myModal"; 7576: modalWindow.width = width; 7577: modalWindow.height = height; 7578: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'></iframe>"; 7579: modalWindow.open(); 7580: }; 7581: // END LON-CAPA Internal --> 7582: // ]]> 7583: </script> 7584: ENDMODAL 7585: } 7586: 7587: sub modal_link { 7588: my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_; 7589: unless ($width) { $width=480; } 7590: unless ($height) { $height=400; } 7591: unless ($scrolling) { $scrolling='yes'; } 7592: my $target_attr; 7593: if (defined($target)) { 7594: $target_attr = 'target="'.$target.'"'; 7595: } 7596: return <<"ENDLINK"; 7597: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;"> 7598: $linktext</a> 7599: ENDLINK 7600: } 7601: 7602: sub modal_adhoc_script { 7603: my ($funcname,$width,$height,$content)=@_; 7604: return (<<ENDADHOC); 7605: <script type="text/javascript"> 7606: // <![CDATA[ 7607: var $funcname = function() 7608: { 7609: modalWindow.windowId = "myModal"; 7610: modalWindow.width = $width; 7611: modalWindow.height = $height; 7612: modalWindow.content = '$content'; 7613: modalWindow.open(); 7614: }; 7615: // ]]> 7616: </script> 7617: ENDADHOC 7618: } 7619: 7620: sub modal_adhoc_inner { 7621: my ($funcname,$width,$height,$content)=@_; 7622: my $innerwidth=$width-20; 7623: $content=&js_ready( 7624: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}). 7625: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px'). 7626: $content. 7627: &end_scrollbox(). 7628: &end_page() 7629: ); 7630: return &modal_adhoc_script($funcname,$width,$height,$content); 7631: } 7632: 7633: sub modal_adhoc_window { 7634: my ($funcname,$width,$height,$content,$linktext)=@_; 7635: return &modal_adhoc_inner($funcname,$width,$height,$content). 7636: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>"; 7637: } 7638: 7639: sub modal_adhoc_launch { 7640: my ($funcname,$width,$height,$content)=@_; 7641: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH); 7642: <script type="text/javascript"> 7643: // <![CDATA[ 7644: $funcname(); 7645: // ]]> 7646: </script> 7647: ENDLAUNCH 7648: } 7649: 7650: sub modal_adhoc_close { 7651: return (<<ENDCLOSE); 7652: <script type="text/javascript"> 7653: // <![CDATA[ 7654: modalWindow.close(); 7655: // ]]> 7656: </script> 7657: ENDCLOSE 7658: } 7659: 7660: sub togglebox_script { 7661: return(<<ENDTOGGLE); 7662: <script type="text/javascript"> 7663: // <![CDATA[ 7664: function LCtoggleDisplay(id,hidetext,showtext) { 7665: link = document.getElementById(id + "link").childNodes[0]; 7666: with (document.getElementById(id).style) { 7667: if (display == "none" ) { 7668: display = "inline"; 7669: link.nodeValue = hidetext; 7670: } else { 7671: display = "none"; 7672: link.nodeValue = showtext; 7673: } 7674: } 7675: } 7676: // ]]> 7677: </script> 7678: ENDTOGGLE 7679: } 7680: 7681: sub start_togglebox { 7682: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_; 7683: unless ($heading) { $heading=''; } else { $heading.=' '; } 7684: unless ($showtext) { $showtext=&mt('show'); } 7685: unless ($hidetext) { $hidetext=&mt('hide'); } 7686: unless ($headerbg) { $headerbg='#FFFFFF'; } 7687: return &start_data_table(). 7688: &start_data_table_header_row(). 7689: '<td bgcolor="'.$headerbg.'">'.$heading. 7690: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''. 7691: $showtext.'\')">'.$showtext.'</a>]</td>'. 7692: &end_data_table_header_row(). 7693: '<tr id="'.$id.'" style="display:none""><td>'; 7694: } 7695: 7696: sub end_togglebox { 7697: return '</td></tr>'.&end_data_table(); 7698: } 7699: 7700: sub LCprogressbar_script { 7701: my ($id)=@_; 7702: return(<<ENDPROGRESS); 7703: <script type="text/javascript"> 7704: // <![CDATA[ 7705: \$('#progressbar$id').progressbar({ 7706: value: 0, 7707: change: function(event, ui) { 7708: var newVal = \$(this).progressbar('option', 'value'); 7709: \$('.pblabel', this).text(LCprogressTxt); 7710: } 7711: }); 7712: // ]]> 7713: </script> 7714: ENDPROGRESS 7715: } 7716: 7717: sub LCprogressbarUpdate_script { 7718: return(<<ENDPROGRESSUPDATE); 7719: <style type="text/css"> 7720: .ui-progressbar { position:relative; } 7721: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; } 7722: </style> 7723: <script type="text/javascript"> 7724: // <![CDATA[ 7725: var LCprogressTxt='---'; 7726: 7727: function LCupdateProgress(percent,progresstext,id) { 7728: LCprogressTxt=progresstext; 7729: \$('#progressbar'+id).progressbar('value',percent); 7730: } 7731: // ]]> 7732: </script> 7733: ENDPROGRESSUPDATE 7734: } 7735: 7736: my $LClastpercent; 7737: my $LCidcnt; 7738: my $LCcurrentid; 7739: 7740: sub LCprogressbar { 7741: my ($r)=(@_); 7742: $LClastpercent=0; 7743: $LCidcnt++; 7744: $LCcurrentid=$$.'_'.$LCidcnt; 7745: my $starting=&mt('Starting'); 7746: my $content=(<<ENDPROGBAR); 7747: <p> 7748: <div id="progressbar$LCcurrentid"> 7749: <span class="pblabel">$starting</span> 7750: </div> 7751: </p> 7752: ENDPROGBAR 7753: &r_print($r,$content.&LCprogressbar_script($LCcurrentid)); 7754: } 7755: 7756: sub LCprogressbarUpdate { 7757: my ($r,$val,$text)=@_; 7758: unless ($val) { 7759: if ($LClastpercent) { 7760: $val=$LClastpercent; 7761: } else { 7762: $val=0; 7763: } 7764: } 7765: if ($val<0) { $val=0; } 7766: if ($val>100) { $val=0; } 7767: $LClastpercent=$val; 7768: unless ($text) { $text=$val.'%'; } 7769: $text=&js_ready($text); 7770: &r_print($r,<<ENDUPDATE); 7771: <script type="text/javascript"> 7772: // <![CDATA[ 7773: LCupdateProgress($val,'$text','$LCcurrentid'); 7774: // ]]> 7775: </script> 7776: ENDUPDATE 7777: } 7778: 7779: sub LCprogressbarClose { 7780: my ($r)=@_; 7781: $LClastpercent=0; 7782: &r_print($r,<<ENDCLOSE); 7783: <script type="text/javascript"> 7784: // <![CDATA[ 7785: \$("#progressbar$LCcurrentid").hide('slow'); 7786: // ]]> 7787: </script> 7788: ENDCLOSE 7789: } 7790: 7791: sub r_print { 7792: my ($r,$to_print)=@_; 7793: if ($r) { 7794: $r->print($to_print); 7795: $r->rflush(); 7796: } else { 7797: print($to_print); 7798: } 7799: } 7800: 7801: sub html_encode { 7802: my ($result) = @_; 7803: 7804: $result = &HTML::Entities::encode($result,'<>&"'); 7805: 7806: return $result; 7807: } 7808: 7809: sub js_ready { 7810: my ($result) = @_; 7811: 7812: $result =~ s/[\n\r]/ /xmsg; 7813: $result =~ s/\\/\\\\/xmsg; 7814: $result =~ s/'/\\'/xmsg; 7815: $result =~ s{</}{<\\/}xmsg; 7816: 7817: return $result; 7818: } 7819: 7820: sub validate_page { 7821: if ( exists($env{'internal.start_page'}) 7822: && $env{'internal.start_page'} > 1) { 7823: &Apache::lonnet::logthis('start_page called multiple times '. 7824: $env{'internal.start_page'}.' '. 7825: $ENV{'request.filename'}); 7826: } 7827: if ( exists($env{'internal.end_page'}) 7828: && $env{'internal.end_page'} > 1) { 7829: &Apache::lonnet::logthis('end_page called multiple times '. 7830: $env{'internal.end_page'}.' '. 7831: $env{'request.filename'}); 7832: } 7833: if ( exists($env{'internal.start_page'}) 7834: && ! exists($env{'internal.end_page'})) { 7835: &Apache::lonnet::logthis('start_page called without end_page '. 7836: $env{'request.filename'}); 7837: } 7838: if ( ! exists($env{'internal.start_page'}) 7839: && exists($env{'internal.end_page'})) { 7840: &Apache::lonnet::logthis('end_page called without start_page'. 7841: $env{'request.filename'}); 7842: } 7843: } 7844: 7845: 7846: sub start_scrollbox { 7847: my ($outerwidth,$width,$height,$id,$bgcolor)=@_; 7848: unless ($outerwidth) { $outerwidth='520px'; } 7849: unless ($width) { $width='500px'; } 7850: unless ($height) { $height='200px'; } 7851: my ($table_id,$div_id,$tdcol); 7852: if ($id ne '') { 7853: $table_id = " id='table_$id'"; 7854: $div_id = " id='div_$id'"; 7855: } 7856: if ($bgcolor ne '') { 7857: $tdcol = "background-color: $bgcolor;"; 7858: } 7859: return <<"END"; 7860: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id> 7861: END 7862: } 7863: 7864: sub end_scrollbox { 7865: return '</div></td></tr></table>'; 7866: } 7867: 7868: sub simple_error_page { 7869: my ($r,$title,$msg) = @_; 7870: my $page = 7871: &Apache::loncommon::start_page($title). 7872: '<p class="LC_error">'.&mt($msg).'</p>'. 7873: &Apache::loncommon::end_page(); 7874: if (ref($r)) { 7875: $r->print($page); 7876: return; 7877: } 7878: return $page; 7879: } 7880: 7881: { 7882: my @row_count; 7883: 7884: sub start_data_table_count { 7885: unshift(@row_count, 0); 7886: return; 7887: } 7888: 7889: sub end_data_table_count { 7890: shift(@row_count); 7891: return; 7892: } 7893: 7894: sub start_data_table { 7895: my ($add_class,$id) = @_; 7896: my $css_class = (join(' ','LC_data_table',$add_class)); 7897: my $table_id; 7898: if (defined($id)) { 7899: $table_id = ' id="'.$id.'"'; 7900: } 7901: &start_data_table_count(); 7902: return '<table class="'.$css_class.'"'.$table_id.'>'."\n"; 7903: } 7904: 7905: sub end_data_table { 7906: &end_data_table_count(); 7907: return '</table>'."\n";; 7908: } 7909: 7910: sub start_data_table_row { 7911: my ($add_class, $id) = @_; 7912: $row_count[0]++; 7913: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row'; 7914: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq ''); 7915: $id = (' id="'.$id.'"') unless ($id eq ''); 7916: return '<tr class="'.$css_class.'"'.$id.'>'."\n"; 7917: } 7918: 7919: sub continue_data_table_row { 7920: my ($add_class, $id) = @_; 7921: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row'; 7922: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq ''); 7923: $id = (' id="'.$id.'"') unless ($id eq ''); 7924: return '<tr class="'.$css_class.'"'.$id.'>'."\n"; 7925: } 7926: 7927: sub end_data_table_row { 7928: return '</tr>'."\n";; 7929: } 7930: 7931: sub start_data_table_empty_row { 7932: # $row_count[0]++; 7933: return '<tr class="LC_empty_row" >'."\n";; 7934: } 7935: 7936: sub end_data_table_empty_row { 7937: return '</tr>'."\n";; 7938: } 7939: 7940: sub start_data_table_header_row { 7941: return '<tr class="LC_header_row">'."\n";; 7942: } 7943: 7944: sub end_data_table_header_row { 7945: return '</tr>'."\n";; 7946: } 7947: 7948: sub data_table_caption { 7949: my $caption = shift; 7950: return "<caption class=\"LC_caption\">$caption</caption>"; 7951: } 7952: } 7953: 7954: =pod 7955: 7956: =item * &inhibit_menu_check($arg) 7957: 7958: Checks for a inhibitmenu state and generates output to preserve it 7959: 7960: Inputs: $arg - can be any of 7961: - undef - in which case the return value is a string 7962: to add into arguments list of a uri 7963: - 'input' - in which case the return value is a HTML 7964: <form> <input> field of type hidden to 7965: preserve the value 7966: - a url - in which case the return value is the url with 7967: the neccesary cgi args added to preserve the 7968: inhibitmenu state 7969: - a ref to a url - no return value, but the string is 7970: updated to include the neccessary cgi 7971: args to preserve the inhibitmenu state 7972: 7973: =cut 7974: 7975: sub inhibit_menu_check { 7976: my ($arg) = @_; 7977: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']); 7978: if ($arg eq 'input') { 7979: if ($env{'form.inhibitmenu'}) { 7980: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />'; 7981: } else { 7982: return 7983: } 7984: } 7985: if ($env{'form.inhibitmenu'}) { 7986: if (ref($arg)) { 7987: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; 7988: } elsif ($arg eq '') { 7989: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'}; 7990: } else { 7991: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'}; 7992: } 7993: } 7994: if (!ref($arg)) { 7995: return $arg; 7996: } 7997: } 7998: 7999: ############################################### 8000: 8001: =pod 8002: 8003: =back 8004: 8005: =head1 User Information Routines 8006: 8007: =over 4 8008: 8009: =item * &get_users_function() 8010: 8011: Used by &bodytag to determine the current users primary role. 8012: Returns either 'student','coordinator','admin', or 'author'. 8013: 8014: =cut 8015: 8016: ############################################### 8017: sub get_users_function { 8018: my $function = 'norole'; 8019: if ($env{'request.role'}=~/^(st)/) { 8020: $function='student'; 8021: } 8022: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) { 8023: $function='coordinator'; 8024: } 8025: if ($env{'request.role'}=~/^(su|dc|ad|li)/) { 8026: $function='admin'; 8027: } 8028: if (($env{'request.role'}=~/^(au|ca|aa)/) || 8029: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) { 8030: $function='author'; 8031: } 8032: return $function; 8033: } 8034: 8035: ############################################### 8036: 8037: =pod 8038: 8039: =item * &show_course() 8040: 8041: Used by lonmenu.pm and lonroles.pm to determine whether to use the word 8042: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles. 8043: 8044: Inputs: 8045: None 8046: 8047: Outputs: 8048: Scalar: 1 if 'Course' to be used, 0 otherwise. 8049: 8050: =cut 8051: 8052: ############################################### 8053: sub show_course { 8054: my $course = !$env{'user.adv'}; 8055: if (!$env{'user.adv'}) { 8056: foreach my $env (keys(%env)) { 8057: next if ($env !~ m/^user\.priv\./); 8058: if ($env !~ m/^user\.priv\.(?:st|cm)/) { 8059: $course = 0; 8060: last; 8061: } 8062: } 8063: } 8064: return $course; 8065: } 8066: 8067: ############################################### 8068: 8069: =pod 8070: 8071: =item * &check_user_status() 8072: 8073: Determines current status of supplied role for a 8074: specific user. Roles can be active, previous or future. 8075: 8076: Inputs: 8077: user's domain, user's username, course's domain, 8078: course's number, optional section ID. 8079: 8080: Outputs: 8081: role status: active, previous or future. 8082: 8083: =cut 8084: 8085: sub check_user_status { 8086: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_; 8087: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname); 8088: my @uroles = keys %userinfo; 8089: my $srchstr; 8090: my $active_chk = 'none'; 8091: my $now = time; 8092: if (@uroles > 0) { 8093: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) { 8094: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role; 8095: } else { 8096: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role; 8097: } 8098: if (grep/^\Q$srchstr\E$/,@uroles) { 8099: my $role_end = 0; 8100: my $role_start = 0; 8101: $active_chk = 'active'; 8102: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) { 8103: $role_end = $1; 8104: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) { 8105: $role_start = $1; 8106: } 8107: } 8108: if ($role_start > 0) { 8109: if ($now < $role_start) { 8110: $active_chk = 'future'; 8111: } 8112: } 8113: if ($role_end > 0) { 8114: if ($now > $role_end) { 8115: $active_chk = 'previous'; 8116: } 8117: } 8118: } 8119: } 8120: return $active_chk; 8121: } 8122: 8123: ############################################### 8124: 8125: =pod 8126: 8127: =item * &get_sections() 8128: 8129: Determines all the sections for a course including 8130: sections with students and sections containing other roles. 8131: Incoming parameters: 8132: 8133: 1. domain 8134: 2. course number 8135: 3. reference to array containing roles for which sections should 8136: be gathered (optional). 8137: 4. reference to array containing status types for which sections 8138: should be gathered (optional). 8139: 8140: If the third argument is undefined, sections are gathered for any role. 8141: If the fourth argument is undefined, sections are gathered for any status. 8142: Permissible values are 'active' or 'future' or 'previous'. 8143: 8144: Returns section hash (keys are section IDs, values are 8145: number of users in each section), subject to the 8146: optional roles filter, optional status filter 8147: 8148: =cut 8149: 8150: ############################################### 8151: sub get_sections { 8152: my ($cdom,$cnum,$possible_roles,$possible_status) = @_; 8153: if (!defined($cdom) || !defined($cnum)) { 8154: my $cid = $env{'request.course.id'}; 8155: 8156: return if (!defined($cid)); 8157: 8158: $cdom = $env{'course.'.$cid.'.domain'}; 8159: $cnum = $env{'course.'.$cid.'.num'}; 8160: } 8161: 8162: my %sectioncount; 8163: my $now = time; 8164: 8165: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) { 8166: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum); 8167: my $sec_index = &Apache::loncoursedata::CL_SECTION(); 8168: my $status_index = &Apache::loncoursedata::CL_STATUS(); 8169: my $start_index = &Apache::loncoursedata::CL_START(); 8170: my $end_index = &Apache::loncoursedata::CL_END(); 8171: my $status; 8172: while (my ($student,$data) = each(%$classlist)) { 8173: my ($section,$stu_status,$start,$end) = ($data->[$sec_index], 8174: $data->[$status_index], 8175: $data->[$start_index], 8176: $data->[$end_index]); 8177: if ($stu_status eq 'Active') { 8178: $status = 'active'; 8179: } elsif ($end < $now) { 8180: $status = 'previous'; 8181: } elsif ($start > $now) { 8182: $status = 'future'; 8183: } 8184: if ($section ne '-1' && $section !~ /^\s*$/) { 8185: if ((!defined($possible_status)) || (($status ne '') && 8186: (grep/^\Q$status\E$/,@{$possible_status}))) { 8187: $sectioncount{$section}++; 8188: } 8189: } 8190: } 8191: } 8192: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 8193: foreach my $user (sort(keys(%courseroles))) { 8194: if ($user !~ /^(\w{2})/) { next; } 8195: my ($role) = ($user =~ /^(\w{2})/); 8196: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; } 8197: my ($section,$status); 8198: if ($role eq 'cr' && 8199: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) { 8200: $section=$1; 8201: } 8202: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; } 8203: if (!defined($section) || $section eq '-1') { next; } 8204: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/); 8205: if ($end == -1 && $start == -1) { 8206: next; #deleted role 8207: } 8208: if (!defined($possible_status)) { 8209: $sectioncount{$section}++; 8210: } else { 8211: if ((!$end || $end >= $now) && (!$start || $start <= $now)) { 8212: $status = 'active'; 8213: } elsif ($end < $now) { 8214: $status = 'future'; 8215: } elsif ($start > $now) { 8216: $status = 'previous'; 8217: } 8218: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) { 8219: $sectioncount{$section}++; 8220: } 8221: } 8222: } 8223: return %sectioncount; 8224: } 8225: 8226: ############################################### 8227: 8228: =pod 8229: 8230: =item * &get_course_users() 8231: 8232: Retrieves usernames:domains for users in the specified course 8233: with specific role(s), and access status. 8234: 8235: Incoming parameters: 8236: 1. course domain 8237: 2. course number 8238: 3. access status: users must have - either active, 8239: previous, future, or all. 8240: 4. reference to array of permissible roles 8241: 5. reference to array of section restrictions (optional) 8242: 6. reference to results object (hash of hashes). 8243: 7. reference to optional userdata hash 8244: 8. reference to optional statushash 8245: 9. flag if privileged users (except those set to unhide in 8246: course settings) should be excluded 8247: Keys of top level results hash are roles. 8248: Keys of inner hashes are username:domain, with 8249: values set to access type. 8250: Optional userdata hash returns an array with arguments in the 8251: same order as loncoursedata::get_classlist() for student data. 8252: 8253: Optional statushash returns 8254: 8255: Entries for end, start, section and status are blank because 8256: of the possibility of multiple values for non-student roles. 8257: 8258: =cut 8259: 8260: ############################################### 8261: 8262: sub get_course_users { 8263: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_; 8264: my %idx = (); 8265: my %seclists; 8266: 8267: $idx{udom} = &Apache::loncoursedata::CL_SDOM(); 8268: $idx{uname} = &Apache::loncoursedata::CL_SNAME(); 8269: $idx{end} = &Apache::loncoursedata::CL_END(); 8270: $idx{start} = &Apache::loncoursedata::CL_START(); 8271: $idx{id} = &Apache::loncoursedata::CL_ID(); 8272: $idx{section} = &Apache::loncoursedata::CL_SECTION(); 8273: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME(); 8274: $idx{status} = &Apache::loncoursedata::CL_STATUS(); 8275: 8276: if (grep(/^st$/,@{$roles})) { 8277: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum); 8278: my $now = time; 8279: foreach my $student (keys(%{$classlist})) { 8280: my $match = 0; 8281: my $secmatch = 0; 8282: my $section = $$classlist{$student}[$idx{section}]; 8283: my $status = $$classlist{$student}[$idx{status}]; 8284: if ($section eq '') { 8285: $section = 'none'; 8286: } 8287: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) { 8288: if (grep(/^all$/,@{$sections})) { 8289: $secmatch = 1; 8290: } elsif ($$classlist{$student}[$idx{section}] eq '') { 8291: if (grep(/^none$/,@{$sections})) { 8292: $secmatch = 1; 8293: } 8294: } else { 8295: if (grep(/^\Q$section\E$/,@{$sections})) { 8296: $secmatch = 1; 8297: } 8298: } 8299: if (!$secmatch) { 8300: next; 8301: } 8302: } 8303: if (defined($$types{'active'})) { 8304: if ($$classlist{$student}[$idx{status}] eq 'Active') { 8305: push(@{$$users{st}{$student}},'active'); 8306: $match = 1; 8307: } 8308: } 8309: if (defined($$types{'previous'})) { 8310: if ($$classlist{$student}[$idx{status}] eq 'Expired') { 8311: push(@{$$users{st}{$student}},'previous'); 8312: $match = 1; 8313: } 8314: } 8315: if (defined($$types{'future'})) { 8316: if ($$classlist{$student}[$idx{status}] eq 'Future') { 8317: push(@{$$users{st}{$student}},'future'); 8318: $match = 1; 8319: } 8320: } 8321: if ($match) { 8322: push(@{$seclists{$student}},$section); 8323: if (ref($userdata) eq 'HASH') { 8324: $$userdata{$student} = $$classlist{$student}; 8325: } 8326: if (ref($statushash) eq 'HASH') { 8327: $statushash->{$student}{'st'}{$section} = $status; 8328: } 8329: } 8330: } 8331: } 8332: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) { 8333: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 8334: my $now = time; 8335: my %displaystatus = ( previous => 'Expired', 8336: active => 'Active', 8337: future => 'Future', 8338: ); 8339: my %nothide; 8340: if ($hidepriv) { 8341: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum); 8342: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) { 8343: if ($user !~ /:/) { 8344: $nothide{join(':',split(/[\@]/,$user))}=1; 8345: } else { 8346: $nothide{$user} = 1; 8347: } 8348: } 8349: } 8350: foreach my $person (sort(keys(%coursepersonnel))) { 8351: my $match = 0; 8352: my $secmatch = 0; 8353: my $status; 8354: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/); 8355: $user =~ s/:$//; 8356: my ($end,$start) = split(/:/,$coursepersonnel{$person}); 8357: if ($end == -1 || $start == -1) { 8358: next; 8359: } 8360: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) || 8361: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) { 8362: my ($uname,$udom) = split(/:/,$user); 8363: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) { 8364: if (grep(/^all$/,@{$sections})) { 8365: $secmatch = 1; 8366: } elsif ($usec eq '') { 8367: if (grep(/^none$/,@{$sections})) { 8368: $secmatch = 1; 8369: } 8370: } else { 8371: if (grep(/^\Q$usec\E$/,@{$sections})) { 8372: $secmatch = 1; 8373: } 8374: } 8375: if (!$secmatch) { 8376: next; 8377: } 8378: } 8379: if ($usec eq '') { 8380: $usec = 'none'; 8381: } 8382: if ($uname ne '' && $udom ne '') { 8383: if ($hidepriv) { 8384: if ((&Apache::lonnet::privileged($uname,$udom)) && 8385: (!$nothide{$uname.':'.$udom})) { 8386: next; 8387: } 8388: } 8389: if ($end > 0 && $end < $now) { 8390: $status = 'previous'; 8391: } elsif ($start > $now) { 8392: $status = 'future'; 8393: } else { 8394: $status = 'active'; 8395: } 8396: foreach my $type (keys(%{$types})) { 8397: if ($status eq $type) { 8398: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) { 8399: push(@{$$users{$role}{$user}},$type); 8400: } 8401: $match = 1; 8402: } 8403: } 8404: if (($match) && (ref($userdata) eq 'HASH')) { 8405: if (!exists($$userdata{$uname.':'.$udom})) { 8406: &get_user_info($udom,$uname,\%idx,$userdata); 8407: } 8408: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) { 8409: push(@{$seclists{$uname.':'.$udom}},$usec); 8410: } 8411: if (ref($statushash) eq 'HASH') { 8412: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status}; 8413: } 8414: } 8415: } 8416: } 8417: } 8418: if (grep(/^ow$/,@{$roles})) { 8419: if ((defined($cdom)) && (defined($cnum))) { 8420: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum); 8421: if ( defined($csettings{'internal.courseowner'}) ) { 8422: my $owner = $csettings{'internal.courseowner'}; 8423: next if ($owner eq ''); 8424: my ($ownername,$ownerdom); 8425: if ($owner =~ /^([^:]+):([^:]+)$/) { 8426: $ownername = $1; 8427: $ownerdom = $2; 8428: } else { 8429: $ownername = $owner; 8430: $ownerdom = $cdom; 8431: $owner = $ownername.':'.$ownerdom; 8432: } 8433: @{$$users{'ow'}{$owner}} = 'any'; 8434: if (defined($userdata) && 8435: !exists($$userdata{$owner})) { 8436: &get_user_info($ownerdom,$ownername,\%idx,$userdata); 8437: if (!grep(/^none$/,@{$seclists{$owner}})) { 8438: push(@{$seclists{$owner}},'none'); 8439: } 8440: if (ref($statushash) eq 'HASH') { 8441: $statushash->{$owner}{'ow'}{'none'} = 'Any'; 8442: } 8443: } 8444: } 8445: } 8446: } 8447: foreach my $user (keys(%seclists)) { 8448: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}}); 8449: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}}); 8450: } 8451: } 8452: return; 8453: } 8454: 8455: sub get_user_info { 8456: my ($udom,$uname,$idx,$userdata) = @_; 8457: $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 8458: &plainname($uname,$udom,'lastname'); 8459: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname; 8460: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom; 8461: my %idhash = &Apache::lonnet::idrget($udom,($uname)); 8462: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 8463: return; 8464: } 8465: 8466: ############################################### 8467: 8468: =pod 8469: 8470: =item * &get_user_quota() 8471: 8472: Retrieves quota assigned for storage of portfolio files for a user 8473: 8474: Incoming parameters: 8475: 1. user's username 8476: 2. user's domain 8477: 8478: Returns: 8479: 1. Disk quota (in Mb) assigned to student. 8480: 2. (Optional) Type of setting: custom or default 8481: (individually assigned or default for user's 8482: institutional status). 8483: 3. (Optional) - User's institutional status (e.g., faculty, staff 8484: or student - types as defined in localenroll::inst_usertypes 8485: for user's domain, which determines default quota for user. 8486: 4. (Optional) - Default quota which would apply to the user. 8487: 8488: If a value has been stored in the user's environment, 8489: it will return that, otherwise it returns the maximal default 8490: defined for the user's instituional status(es) in the domain. 8491: 8492: =cut 8493: 8494: ############################################### 8495: 8496: 8497: sub get_user_quota { 8498: my ($uname,$udom) = @_; 8499: my ($quota,$quotatype,$settingstatus,$defquota); 8500: if (!defined($udom)) { 8501: $udom = $env{'user.domain'}; 8502: } 8503: if (!defined($uname)) { 8504: $uname = $env{'user.name'}; 8505: } 8506: if (($udom eq '' || $uname eq '') || 8507: ($udom eq 'public') && ($uname eq 'public')) { 8508: $quota = 0; 8509: $quotatype = 'default'; 8510: $defquota = 0; 8511: } else { 8512: my $inststatus; 8513: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) { 8514: $quota = $env{'environment.portfolioquota'}; 8515: $inststatus = $env{'environment.inststatus'}; 8516: } else { 8517: my %userenv = 8518: &Apache::lonnet::get('environment',['portfolioquota', 8519: 'inststatus'],$udom,$uname); 8520: my ($tmp) = keys(%userenv); 8521: if ($tmp !~ /^(con_lost|error|no_such_host)/i) { 8522: $quota = $userenv{'portfolioquota'}; 8523: $inststatus = $userenv{'inststatus'}; 8524: } else { 8525: undef(%userenv); 8526: } 8527: } 8528: ($defquota,$settingstatus) = &default_quota($udom,$inststatus); 8529: if ($quota eq '') { 8530: $quota = $defquota; 8531: $quotatype = 'default'; 8532: } else { 8533: $quotatype = 'custom'; 8534: } 8535: } 8536: if (wantarray) { 8537: return ($quota,$quotatype,$settingstatus,$defquota); 8538: } else { 8539: return $quota; 8540: } 8541: } 8542: 8543: ############################################### 8544: 8545: =pod 8546: 8547: =item * &default_quota() 8548: 8549: Retrieves default quota assigned for storage of user portfolio files, 8550: given an (optional) user's institutional status. 8551: 8552: Incoming parameters: 8553: 1. domain 8554: 2. (Optional) institutional status(es). This is a : separated list of 8555: status types (e.g., faculty, staff, student etc.) 8556: which apply to the user for whom the default is being retrieved. 8557: If the institutional status string in undefined, the domain 8558: default quota will be returned. 8559: 8560: Returns: 8561: 1. Default disk quota (in Mb) for user portfolios in the domain. 8562: 2. (Optional) institutional type which determined the value of the 8563: default quota. 8564: 8565: If a value has been stored in the domain's configuration db, 8566: it will return that, otherwise it returns 20 (for backwards 8567: compatibility with domains which have not set up a configuration 8568: db file; the original statically defined portfolio quota was 20 Mb). 8569: 8570: If the user's status includes multiple types (e.g., staff and student), 8571: the largest default quota which applies to the user determines the 8572: default quota returned. 8573: 8574: =back 8575: 8576: =cut 8577: 8578: ############################################### 8579: 8580: 8581: sub default_quota { 8582: my ($udom,$inststatus) = @_; 8583: my ($defquota,$settingstatus); 8584: my %quotahash = &Apache::lonnet::get_dom('configuration', 8585: ['quotas'],$udom); 8586: if (ref($quotahash{'quotas'}) eq 'HASH') { 8587: if ($inststatus ne '') { 8588: my @statuses = map { &unescape($_); } split(/:/,$inststatus); 8589: foreach my $item (@statuses) { 8590: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') { 8591: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') { 8592: if ($defquota eq '') { 8593: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item}; 8594: $settingstatus = $item; 8595: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) { 8596: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item}; 8597: $settingstatus = $item; 8598: } 8599: } 8600: } else { 8601: if ($quotahash{'quotas'}{$item} ne '') { 8602: if ($defquota eq '') { 8603: $defquota = $quotahash{'quotas'}{$item}; 8604: $settingstatus = $item; 8605: } elsif ($quotahash{'quotas'}{$item} > $defquota) { 8606: $defquota = $quotahash{'quotas'}{$item}; 8607: $settingstatus = $item; 8608: } 8609: } 8610: } 8611: } 8612: } 8613: if ($defquota eq '') { 8614: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') { 8615: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'}; 8616: } else { 8617: $defquota = $quotahash{'quotas'}{'default'}; 8618: } 8619: $settingstatus = 'default'; 8620: } 8621: } else { 8622: $settingstatus = 'default'; 8623: $defquota = 20; 8624: } 8625: if (wantarray) { 8626: return ($defquota,$settingstatus); 8627: } else { 8628: return $defquota; 8629: } 8630: } 8631: 8632: sub get_secgrprole_info { 8633: my ($cdom,$cnum,$needroles,$type) = @_; 8634: my %sections_count = &get_sections($cdom,$cnum); 8635: my @sections = (sort {$a <=> $b} keys(%sections_count)); 8636: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum); 8637: my @groups = sort(keys(%curr_groups)); 8638: my $allroles = []; 8639: my $rolehash; 8640: my $accesshash = { 8641: active => 'Currently has access', 8642: future => 'Will have future access', 8643: previous => 'Previously had access', 8644: }; 8645: if ($needroles) { 8646: $rolehash = {'all' => 'all'}; 8647: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum); 8648: if (&Apache::lonnet::error(%user_roles)) { 8649: undef(%user_roles); 8650: } 8651: foreach my $item (keys(%user_roles)) { 8652: my ($role)=split(/\:/,$item,2); 8653: if ($role eq 'cr') { next; } 8654: if ($role =~ /^cr/) { 8655: $$rolehash{$role} = (split('/',$role))[3]; 8656: } else { 8657: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type); 8658: } 8659: } 8660: foreach my $key (sort(keys(%{$rolehash}))) { 8661: push(@{$allroles},$key); 8662: } 8663: push (@{$allroles},'st'); 8664: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type); 8665: } 8666: return (\@sections,\@groups,$allroles,$rolehash,$accesshash); 8667: } 8668: 8669: sub user_picker { 8670: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_; 8671: my $currdom = $dom; 8672: my %curr_selected = ( 8673: srchin => 'dom', 8674: srchby => 'lastname', 8675: ); 8676: my $srchterm; 8677: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) { 8678: if ($srch->{'srchby'} ne '') { 8679: $curr_selected{'srchby'} = $srch->{'srchby'}; 8680: } 8681: if ($srch->{'srchin'} ne '') { 8682: $curr_selected{'srchin'} = $srch->{'srchin'}; 8683: } 8684: if ($srch->{'srchtype'} ne '') { 8685: $curr_selected{'srchtype'} = $srch->{'srchtype'}; 8686: } 8687: if ($srch->{'srchdomain'} ne '') { 8688: $currdom = $srch->{'srchdomain'}; 8689: } 8690: $srchterm = $srch->{'srchterm'}; 8691: } 8692: my %lt=&Apache::lonlocal::texthash( 8693: 'usr' => 'Search criteria', 8694: 'doma' => 'Domain/institution to search', 8695: 'uname' => 'username', 8696: 'lastname' => 'last name', 8697: 'lastfirst' => 'last name, first name', 8698: 'crs' => 'in this course', 8699: 'dom' => 'in selected LON-CAPA domain', 8700: 'alc' => 'all LON-CAPA', 8701: 'instd' => 'in institutional directory for selected domain', 8702: 'exact' => 'is', 8703: 'contains' => 'contains', 8704: 'begins' => 'begins with', 8705: 'youm' => "You must include some text to search for.", 8706: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.", 8707: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.", 8708: 'yomc' => "You must choose a domain when using an institutional directory search.", 8709: 'ymcd' => "You must choose a domain when using a domain search.", 8710: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.", 8711: 'whse' => "When searching by last,first you must include at least one character in the first name.", 8712: 'thfo' => "The following need to be corrected before the search can be run:", 8713: ); 8714: my $domform = &select_dom_form($currdom,'srchdomain',1,1); 8715: my $srchinsel = ' <select name="srchin">'; 8716: 8717: my @srchins = ('crs','dom','alc','instd'); 8718: 8719: foreach my $option (@srchins) { 8720: # FIXME 'alc' option unavailable until 8721: # loncreateuser::print_user_query_page() 8722: # has been completed. 8723: next if ($option eq 'alc'); 8724: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs')); 8725: next if ($option eq 'crs' && !$env{'request.course.id'}); 8726: if ($curr_selected{'srchin'} eq $option) { 8727: $srchinsel .= ' 8728: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 8729: } else { 8730: $srchinsel .= ' 8731: <option value="'.$option.'">'.$lt{$option}.'</option>'; 8732: } 8733: } 8734: $srchinsel .= "\n </select>\n"; 8735: 8736: my $srchbysel = ' <select name="srchby">'; 8737: foreach my $option ('lastname','lastfirst','uname') { 8738: if ($curr_selected{'srchby'} eq $option) { 8739: $srchbysel .= ' 8740: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 8741: } else { 8742: $srchbysel .= ' 8743: <option value="'.$option.'">'.$lt{$option}.'</option>'; 8744: } 8745: } 8746: $srchbysel .= "\n </select>\n"; 8747: 8748: my $srchtypesel = ' <select name="srchtype">'; 8749: foreach my $option ('begins','contains','exact') { 8750: if ($curr_selected{'srchtype'} eq $option) { 8751: $srchtypesel .= ' 8752: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>'; 8753: } else { 8754: $srchtypesel .= ' 8755: <option value="'.$option.'">'.$lt{$option}.'</option>'; 8756: } 8757: } 8758: $srchtypesel .= "\n </select>\n"; 8759: 8760: my ($newuserscript,$new_user_create); 8761: my $context_dom = $env{'request.role.domain'}; 8762: if ($context eq 'requestcrs') { 8763: if ($env{'form.coursedom'} ne '') { 8764: $context_dom = $env{'form.coursedom'}; 8765: } 8766: } 8767: if ($forcenewuser) { 8768: if (ref($srch) eq 'HASH') { 8769: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) { 8770: if ($cancreate) { 8771: $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>'; 8772: } else { 8773: my $helplink = 'javascript:helpMenu('."'display'".')'; 8774: my %usertypetext = ( 8775: official => 'institutional', 8776: unofficial => 'non-institutional', 8777: ); 8778: $new_user_create = '<p class="LC_warning">' 8779: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.") 8780: .' ' 8781: .&mt('Please contact the [_1]helpdesk[_2] for assistance.' 8782: ,'<a href="'.$helplink.'">','</a>') 8783: .'</p><br />'; 8784: } 8785: } 8786: } 8787: 8788: $newuserscript = <<"ENDSCRIPT"; 8789: 8790: function setSearch(createnew,callingForm) { 8791: if (createnew == 1) { 8792: for (var i=0; i<callingForm.srchby.length; i++) { 8793: if (callingForm.srchby.options[i].value == 'uname') { 8794: callingForm.srchby.selectedIndex = i; 8795: } 8796: } 8797: for (var i=0; i<callingForm.srchin.length; i++) { 8798: if ( callingForm.srchin.options[i].value == 'dom') { 8799: callingForm.srchin.selectedIndex = i; 8800: } 8801: } 8802: for (var i=0; i<callingForm.srchtype.length; i++) { 8803: if (callingForm.srchtype.options[i].value == 'exact') { 8804: callingForm.srchtype.selectedIndex = i; 8805: } 8806: } 8807: for (var i=0; i<callingForm.srchdomain.length; i++) { 8808: if (callingForm.srchdomain.options[i].value == '$context_dom') { 8809: callingForm.srchdomain.selectedIndex = i; 8810: } 8811: } 8812: } 8813: } 8814: ENDSCRIPT 8815: 8816: } 8817: 8818: my $output = <<"END_BLOCK"; 8819: <script type="text/javascript"> 8820: // <![CDATA[ 8821: function validateEntry(callingForm) { 8822: 8823: var checkok = 1; 8824: var srchin; 8825: for (var i=0; i<callingForm.srchin.length; i++) { 8826: if ( callingForm.srchin[i].checked ) { 8827: srchin = callingForm.srchin[i].value; 8828: } 8829: } 8830: 8831: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value; 8832: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value; 8833: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value; 8834: var srchterm = callingForm.srchterm.value; 8835: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value; 8836: var msg = ""; 8837: 8838: if (srchterm == "") { 8839: checkok = 0; 8840: msg += "$lt{'youm'}\\n"; 8841: } 8842: 8843: if (srchtype== 'begins') { 8844: if (srchterm.length < 2) { 8845: checkok = 0; 8846: msg += "$lt{'thte'}\\n"; 8847: } 8848: } 8849: 8850: if (srchtype== 'contains') { 8851: if (srchterm.length < 3) { 8852: checkok = 0; 8853: msg += "$lt{'thet'}\\n"; 8854: } 8855: } 8856: if (srchin == 'instd') { 8857: if (srchdomain == '') { 8858: checkok = 0; 8859: msg += "$lt{'yomc'}\\n"; 8860: } 8861: } 8862: if (srchin == 'dom') { 8863: if (srchdomain == '') { 8864: checkok = 0; 8865: msg += "$lt{'ymcd'}\\n"; 8866: } 8867: } 8868: if (srchby == 'lastfirst') { 8869: if (srchterm.indexOf(",") == -1) { 8870: checkok = 0; 8871: msg += "$lt{'whus'}\\n"; 8872: } 8873: if (srchterm.indexOf(",") == srchterm.length -1) { 8874: checkok = 0; 8875: msg += "$lt{'whse'}\\n"; 8876: } 8877: } 8878: if (checkok == 0) { 8879: alert("$lt{'thfo'}\\n"+msg); 8880: return; 8881: } 8882: if (checkok == 1) { 8883: callingForm.submit(); 8884: } 8885: } 8886: 8887: $newuserscript 8888: 8889: // ]]> 8890: </script> 8891: 8892: $new_user_create 8893: 8894: END_BLOCK 8895: 8896: $output .= &Apache::lonhtmlcommon::start_pick_box(). 8897: &Apache::lonhtmlcommon::row_title($lt{'doma'}). 8898: $domform. 8899: &Apache::lonhtmlcommon::row_closure(). 8900: &Apache::lonhtmlcommon::row_title($lt{'usr'}). 8901: $srchbysel. 8902: $srchtypesel. 8903: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'. 8904: $srchinsel. 8905: &Apache::lonhtmlcommon::row_closure(1). 8906: &Apache::lonhtmlcommon::end_pick_box(). 8907: '<br />'; 8908: return $output; 8909: } 8910: 8911: sub user_rule_check { 8912: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_; 8913: my $response; 8914: if (ref($usershash) eq 'HASH') { 8915: foreach my $user (keys(%{$usershash})) { 8916: my ($uname,$udom) = split(/:/,$user); 8917: next if ($udom eq '' || $uname eq ''); 8918: my ($id,$newuser); 8919: if (ref($usershash->{$user}) eq 'HASH') { 8920: $newuser = $usershash->{$user}->{'newuser'}; 8921: $id = $usershash->{$user}->{'id'}; 8922: } 8923: my $inst_response; 8924: if (ref($checks) eq 'HASH') { 8925: if (defined($checks->{'username'})) { 8926: ($inst_response,%{$inst_results->{$user}}) = 8927: &Apache::lonnet::get_instuser($udom,$uname); 8928: } elsif (defined($checks->{'id'})) { 8929: ($inst_response,%{$inst_results->{$user}}) = 8930: &Apache::lonnet::get_instuser($udom,undef,$id); 8931: } 8932: } else { 8933: ($inst_response,%{$inst_results->{$user}}) = 8934: &Apache::lonnet::get_instuser($udom,$uname); 8935: return; 8936: } 8937: if (!$got_rules->{$udom}) { 8938: my %domconfig = &Apache::lonnet::get_dom('configuration', 8939: ['usercreation'],$udom); 8940: if (ref($domconfig{'usercreation'}) eq 'HASH') { 8941: foreach my $item ('username','id') { 8942: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') { 8943: $$curr_rules{$udom}{$item} = 8944: $domconfig{'usercreation'}{$item.'_rule'}; 8945: } 8946: } 8947: } 8948: $got_rules->{$udom} = 1; 8949: } 8950: foreach my $item (keys(%{$checks})) { 8951: if (ref($$curr_rules{$udom}) eq 'HASH') { 8952: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') { 8953: if (@{$$curr_rules{$udom}{$item}} > 0) { 8954: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item}); 8955: foreach my $rule (@{$$curr_rules{$udom}{$item}}) { 8956: if ($rule_check{$rule}) { 8957: $$rulematch{$user}{$item} = $rule; 8958: if ($inst_response eq 'ok') { 8959: if (ref($inst_results) eq 'HASH') { 8960: if (ref($inst_results->{$user}) eq 'HASH') { 8961: if (keys(%{$inst_results->{$user}}) == 0) { 8962: $$alerts{$item}{$udom}{$uname} = 1; 8963: } 8964: } 8965: } 8966: } 8967: last; 8968: } 8969: } 8970: } 8971: } 8972: } 8973: } 8974: } 8975: } 8976: return; 8977: } 8978: 8979: sub user_rule_formats { 8980: my ($domain,$domdesc,$curr_rules,$check) = @_; 8981: my %text = ( 8982: 'username' => 'Usernames', 8983: 'id' => 'IDs', 8984: ); 8985: my $output; 8986: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check); 8987: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) { 8988: if (@{$ruleorder} > 0) { 8989: $output = '<br />'. 8990: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:', 8991: '<span class="LC_cusr_emph">','</span>',$domdesc). 8992: ' <ul>'; 8993: foreach my $rule (@{$ruleorder}) { 8994: if (ref($curr_rules) eq 'ARRAY') { 8995: if (grep(/^\Q$rule\E$/,@{$curr_rules})) { 8996: if (ref($rules->{$rule}) eq 'HASH') { 8997: $output .= '<li>'.$rules->{$rule}{'name'}.': '. 8998: $rules->{$rule}{'desc'}.'</li>'; 8999: } 9000: } 9001: } 9002: } 9003: $output .= '</ul>'; 9004: } 9005: } 9006: return $output; 9007: } 9008: 9009: sub instrule_disallow_msg { 9010: my ($checkitem,$domdesc,$count,$mode) = @_; 9011: my $response; 9012: my %text = ( 9013: item => 'username', 9014: items => 'usernames', 9015: match => 'matches', 9016: do => 'does', 9017: action => 'a username', 9018: one => 'one', 9019: ); 9020: if ($count > 1) { 9021: $text{'item'} = 'usernames'; 9022: $text{'match'} ='match'; 9023: $text{'do'} = 'do'; 9024: $text{'action'} = 'usernames', 9025: $text{'one'} = 'ones'; 9026: } 9027: if ($checkitem eq 'id') { 9028: $text{'items'} = 'IDs'; 9029: $text{'item'} = 'ID'; 9030: $text{'action'} = 'an ID'; 9031: if ($count > 1) { 9032: $text{'item'} = 'IDs'; 9033: $text{'action'} = 'IDs'; 9034: } 9035: } 9036: $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 />'; 9037: if ($mode eq 'upload') { 9038: if ($checkitem eq 'username') { 9039: $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'}."); 9040: } elsif ($checkitem eq 'id') { 9041: $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."); 9042: } 9043: } elsif ($mode eq 'selfcreate') { 9044: if ($checkitem eq 'id') { 9045: $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."); 9046: } 9047: } else { 9048: if ($checkitem eq 'username') { 9049: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}."); 9050: } elsif ($checkitem eq 'id') { 9051: $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."); 9052: } 9053: } 9054: return $response; 9055: } 9056: 9057: sub personal_data_fieldtitles { 9058: my %fieldtitles = &Apache::lonlocal::texthash ( 9059: id => 'Student/Employee ID', 9060: permanentemail => 'E-mail address', 9061: lastname => 'Last Name', 9062: firstname => 'First Name', 9063: middlename => 'Middle Name', 9064: generation => 'Generation', 9065: gen => 'Generation', 9066: inststatus => 'Affiliation', 9067: ); 9068: return %fieldtitles; 9069: } 9070: 9071: sub sorted_inst_types { 9072: my ($dom) = @_; 9073: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom); 9074: my $othertitle = &mt('All users'); 9075: if ($env{'request.course.id'}) { 9076: $othertitle = &mt('Any users'); 9077: } 9078: my @types; 9079: if (ref($order) eq 'ARRAY') { 9080: @types = @{$order}; 9081: } 9082: if (@types == 0) { 9083: if (ref($usertypes) eq 'HASH') { 9084: @types = sort(keys(%{$usertypes})); 9085: } 9086: } 9087: if (keys(%{$usertypes}) > 0) { 9088: $othertitle = &mt('Other users'); 9089: } 9090: return ($othertitle,$usertypes,\@types); 9091: } 9092: 9093: sub get_institutional_codes { 9094: my ($settings,$allcourses,$LC_code) = @_; 9095: # Get complete list of course sections to update 9096: my @currsections = (); 9097: my @currxlists = (); 9098: my $coursecode = $$settings{'internal.coursecode'}; 9099: 9100: if ($$settings{'internal.sectionnums'} ne '') { 9101: @currsections = split(/,/,$$settings{'internal.sectionnums'}); 9102: } 9103: 9104: if ($$settings{'internal.crosslistings'} ne '') { 9105: @currxlists = split(/,/,$$settings{'internal.crosslistings'}); 9106: } 9107: 9108: if (@currxlists > 0) { 9109: foreach (@currxlists) { 9110: if (m/^([^:]+):(\w*)$/) { 9111: unless (grep/^$1$/,@{$allcourses}) { 9112: push @{$allcourses},$1; 9113: $$LC_code{$1} = $2; 9114: } 9115: } 9116: } 9117: } 9118: 9119: if (@currsections > 0) { 9120: foreach (@currsections) { 9121: if (m/^(\w+):(\w*)$/) { 9122: my $sec = $coursecode.$1; 9123: my $lc_sec = $2; 9124: unless (grep/^$sec$/,@{$allcourses}) { 9125: push @{$allcourses},$sec; 9126: $$LC_code{$sec} = $lc_sec; 9127: } 9128: } 9129: } 9130: } 9131: return; 9132: } 9133: 9134: sub get_standard_codeitems { 9135: return ('Year','Semester','Department','Number','Section'); 9136: } 9137: 9138: =pod 9139: 9140: =head1 Slot Helpers 9141: 9142: =over 4 9143: 9144: =item * sorted_slots() 9145: 9146: Sorts an array of slot names in order of an optional sort key, 9147: default sort is by slot start time (earliest first). 9148: 9149: Inputs: 9150: 9151: =over 4 9152: 9153: slotsarr - Reference to array of unsorted slot names. 9154: 9155: slots - Reference to hash of hash, where outer hash keys are slot names. 9156: 9157: sortkey - Name of key in inner hash to be sorted on (e.g., starttime). 9158: 9159: =back 9160: 9161: Returns: 9162: 9163: =over 4 9164: 9165: sorted - An array of slot names sorted by a specified sort key 9166: (default sort key is start time of the slot). 9167: 9168: =back 9169: 9170: =cut 9171: 9172: 9173: sub sorted_slots { 9174: my ($slotsarr,$slots,$sortkey) = @_; 9175: if ($sortkey eq '') { 9176: $sortkey = 'starttime'; 9177: } 9178: my @sorted; 9179: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) { 9180: @sorted = 9181: sort { 9182: if (ref($slots->{$a}) && ref($slots->{$b})) { 9183: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey} 9184: } 9185: if (ref($slots->{$a})) { return -1;} 9186: if (ref($slots->{$b})) { return 1;} 9187: return 0; 9188: } @{$slotsarr}; 9189: } 9190: return @sorted; 9191: } 9192: 9193: =pod 9194: 9195: =item * get_future_slots() 9196: 9197: Inputs: 9198: 9199: =over 4 9200: 9201: cnum - course number 9202: 9203: cdom - course domain 9204: 9205: now - current UNIX time 9206: 9207: symb - optional symb 9208: 9209: =back 9210: 9211: Returns: 9212: 9213: =over 4 9214: 9215: sorted_reservable - ref to array of student_schedulable slots currently 9216: reservable, ordered by end date of reservation period. 9217: 9218: reservable_now - ref to hash of student_schedulable slots currently 9219: reservable. 9220: 9221: Keys in inner hash are: 9222: (a) symb: either blank or symb to which slot use is restricted. 9223: (b) endreserve: end date of reservation period. 9224: 9225: sorted_future - ref to array of student_schedulable slots reservable in 9226: the future, ordered by start date of reservation period. 9227: 9228: future_reservable - ref to hash of student_schedulable slots reservable 9229: in the future. 9230: 9231: Keys in inner hash are: 9232: (a) symb: either blank or symb to which slot use is restricted. 9233: (b) startreserve: start date of reservation period. 9234: 9235: =back 9236: 9237: =cut 9238: 9239: sub get_future_slots { 9240: my ($cnum,$cdom,$now,$symb) = @_; 9241: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future); 9242: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom); 9243: foreach my $slot (keys(%slots)) { 9244: next unless($slots{$slot}->{'type'} eq 'schedulable_student'); 9245: if ($symb) { 9246: next if (($slots{$slot}->{'symb'} ne '') && 9247: ($slots{$slot}->{'symb'} ne $symb)); 9248: } 9249: if (($slots{$slot}->{'starttime'} > $now) && 9250: ($slots{$slot}->{'endtime'} > $now)) { 9251: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) { 9252: my $userallowed = 0; 9253: if ($slots{$slot}->{'allowedsections'}) { 9254: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'}); 9255: if (!defined($env{'request.role.sec'}) 9256: && grep(/^No section assigned$/,@allowed_sec)) { 9257: $userallowed=1; 9258: } else { 9259: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) { 9260: $userallowed=1; 9261: } 9262: } 9263: unless ($userallowed) { 9264: if (defined($env{'request.course.groups'})) { 9265: my @groups = split(/:/,$env{'request.course.groups'}); 9266: foreach my $group (@groups) { 9267: if (grep(/^\Q$group\E$/,@allowed_sec)) { 9268: $userallowed=1; 9269: last; 9270: } 9271: } 9272: } 9273: } 9274: } 9275: if ($slots{$slot}->{'allowedusers'}) { 9276: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'}); 9277: my $user = $env{'user.name'}.':'.$env{'user.domain'}; 9278: if (grep(/^\Q$user\E$/,@allowed_users)) { 9279: $userallowed = 1; 9280: } 9281: } 9282: next unless($userallowed); 9283: } 9284: my $startreserve = $slots{$slot}->{'startreserve'}; 9285: my $endreserve = $slots{$slot}->{'endreserve'}; 9286: my $symb = $slots{$slot}->{'symb'}; 9287: if (($startreserve < $now) && 9288: (!$endreserve || $endreserve > $now)) { 9289: my $lastres = $endreserve; 9290: if (!$lastres) { 9291: $lastres = $slots{$slot}->{'starttime'}; 9292: } 9293: $reservable_now{$slot} = { 9294: symb => $symb, 9295: endreserve => $lastres 9296: }; 9297: } elsif (($startreserve > $now) && 9298: (!$endreserve || $endreserve > $startreserve)) { 9299: $future_reservable{$slot} = { 9300: symb => $symb, 9301: startreserve => $startreserve 9302: }; 9303: } 9304: } 9305: } 9306: my @unsorted_reservable = keys(%reservable_now); 9307: if (@unsorted_reservable > 0) { 9308: @sorted_reservable = 9309: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve'); 9310: } 9311: my @unsorted_future = keys(%future_reservable); 9312: if (@unsorted_future > 0) { 9313: @sorted_future = 9314: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve'); 9315: } 9316: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable); 9317: } 9318: 9319: =pod 9320: 9321: =back 9322: 9323: =head1 HTTP Helpers 9324: 9325: =over 4 9326: 9327: =item * &get_unprocessed_cgi($query,$possible_names) 9328: 9329: Modify the %env hash to contain unprocessed CGI form parameters held in 9330: $query. The parameters listed in $possible_names (an array reference), 9331: will be set in $env{'form.name'} if they do not already exist. 9332: 9333: Typically called with $ENV{'QUERY_STRING'} as the first parameter. 9334: $possible_names is an ref to an array of form element names. As an example: 9335: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']); 9336: will result in $env{'form.uname'} and $env{'form.udom'} being set. 9337: 9338: =cut 9339: 9340: sub get_unprocessed_cgi { 9341: my ($query,$possible_names)= @_; 9342: # $Apache::lonxml::debug=1; 9343: foreach my $pair (split(/&/,$query)) { 9344: my ($name, $value) = split(/=/,$pair); 9345: $name = &unescape($name); 9346: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) { 9347: $value =~ tr/+/ /; 9348: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg; 9349: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) }; 9350: } 9351: } 9352: } 9353: 9354: =pod 9355: 9356: =item * &cacheheader() 9357: 9358: returns cache-controlling header code 9359: 9360: =cut 9361: 9362: sub cacheheader { 9363: unless ($env{'request.method'} eq 'GET') { return ''; } 9364: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime); 9365: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" /> 9366: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" /> 9367: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />'; 9368: return $output; 9369: } 9370: 9371: =pod 9372: 9373: =item * &no_cache($r) 9374: 9375: specifies header code to not have cache 9376: 9377: =cut 9378: 9379: sub no_cache { 9380: my ($r) = @_; 9381: if ($ENV{'REQUEST_METHOD'} ne 'GET' && 9382: $env{'request.method'} ne 'GET') { return ''; } 9383: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time)); 9384: $r->no_cache(1); 9385: $r->header_out("Expires" => $date); 9386: $r->header_out("Pragma" => "no-cache"); 9387: } 9388: 9389: sub content_type { 9390: my ($r,$type,$charset) = @_; 9391: if ($r) { 9392: # Note that printout.pl calls this with undef for $r. 9393: &no_cache($r); 9394: } 9395: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; } 9396: unless ($charset) { 9397: $charset=&Apache::lonlocal::current_encoding; 9398: } 9399: if ($charset) { $type.='; charset='.$charset; } 9400: if ($r) { 9401: $r->content_type($type); 9402: } else { 9403: print("Content-type: $type\n\n"); 9404: } 9405: } 9406: 9407: =pod 9408: 9409: =item * &add_to_env($name,$value) 9410: 9411: adds $name to the %env hash with value 9412: $value, if $name already exists, the entry is converted to an array 9413: reference and $value is added to the array. 9414: 9415: =cut 9416: 9417: sub add_to_env { 9418: my ($name,$value)=@_; 9419: if (defined($env{$name})) { 9420: if (ref($env{$name})) { 9421: #already have multiple values 9422: push(@{ $env{$name} },$value); 9423: } else { 9424: #first time seeing multiple values, convert hash entry to an arrayref 9425: my $first=$env{$name}; 9426: undef($env{$name}); 9427: push(@{ $env{$name} },$first,$value); 9428: } 9429: } else { 9430: $env{$name}=$value; 9431: } 9432: } 9433: 9434: =pod 9435: 9436: =item * &get_env_multiple($name) 9437: 9438: gets $name from the %env hash, it seemlessly handles the cases where multiple 9439: values may be defined and end up as an array ref. 9440: 9441: returns an array of values 9442: 9443: =cut 9444: 9445: sub get_env_multiple { 9446: my ($name) = @_; 9447: my @values; 9448: if (defined($env{$name})) { 9449: # exists is it an array 9450: if (ref($env{$name})) { 9451: @values=@{ $env{$name} }; 9452: } else { 9453: $values[0]=$env{$name}; 9454: } 9455: } 9456: return(@values); 9457: } 9458: 9459: sub ask_for_embedded_content { 9460: my ($actionurl,$state,$allfiles,$codebase,$args)=@_; 9461: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges, 9462: %currsubfile,%unused,$rem); 9463: my $counter = 0; 9464: my $numnew = 0; 9465: my $numremref = 0; 9466: my $numinvalid = 0; 9467: my $numpathchg = 0; 9468: my $numexisting = 0; 9469: my $numunused = 0; 9470: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum, 9471: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path); 9472: my $heading = &mt('Upload embedded files'); 9473: my $buttontext = &mt('Upload'); 9474: 9475: my $navmap; 9476: if ($env{'request.course.id'}) { 9477: $navmap = Apache::lonnavmaps::navmap->new(); 9478: } 9479: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 9480: my $current_path='/'; 9481: if ($env{'form.currentpath'}) { 9482: $current_path = $env{'form.currentpath'}; 9483: } 9484: if ($actionurl eq '/adm/coursegrp_portfolio') { 9485: $udom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 9486: $uname = $env{'course.'.$env{'request.course.id'}.'.num'}; 9487: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio'; 9488: } else { 9489: $udom = $env{'user.domain'}; 9490: $uname = $env{'user.name'}; 9491: $url = '/userfiles/portfolio'; 9492: } 9493: $toplevel = $url.'/'; 9494: $url .= $current_path; 9495: $getpropath = 1; 9496: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 9497: ($actionurl eq '/adm/imsimport')) { 9498: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$}); 9499: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/"; 9500: $toplevel = $url; 9501: if ($rest ne '') { 9502: $url .= $rest; 9503: } 9504: } elsif ($actionurl eq '/adm/coursedocs') { 9505: if (ref($args) eq 'HASH') { 9506: $url = $args->{'docs_url'}; 9507: $toplevel = $url; 9508: if ($args->{'context'} eq 'paste') { 9509: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/}); 9510: ($path) = 9511: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); 9512: $fileloc = &Apache::lonnet::filelocation('',$toplevel); 9513: $fileloc =~ s{^/}{}; 9514: } 9515: } 9516: } elsif ($actionurl eq '/adm/dependencies') { 9517: if ($env{'request.course.id'} ne '') { 9518: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'}; 9519: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'}; 9520: if (ref($args) eq 'HASH') { 9521: $url = $args->{'docs_url'}; 9522: $title = $args->{'docs_title'}; 9523: $toplevel = "/$url"; 9524: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$}); 9525: ($path) = 9526: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/}); 9527: $fileloc = &Apache::lonnet::filelocation('',$toplevel); 9528: $fileloc =~ s{^/}{}; 9529: ($filename) = ($fileloc =~ m{.+/([^/]+)$}); 9530: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)"); 9531: } 9532: } 9533: } 9534: my $now = time(); 9535: foreach my $embed_file (keys(%{$allfiles})) { 9536: my $absolutepath; 9537: if ($embed_file =~ m{^\w+://}) { 9538: $newfiles{$embed_file} = 1; 9539: $mapping{$embed_file} = $embed_file; 9540: } else { 9541: if ($embed_file =~ m{^/}) { 9542: $absolutepath = $embed_file; 9543: $embed_file =~ s{^(/+)}{}; 9544: } 9545: if ($embed_file =~ m{/}) { 9546: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$}); 9547: $path = &check_for_traversal($path,$url,$toplevel); 9548: my $item = $fname; 9549: if ($path ne '') { 9550: $item = $path.'/'.$fname; 9551: $subdependencies{$path}{$fname} = 1; 9552: } else { 9553: $dependencies{$item} = 1; 9554: } 9555: if ($absolutepath) { 9556: $mapping{$item} = $absolutepath; 9557: } else { 9558: $mapping{$item} = $embed_file; 9559: } 9560: } else { 9561: $dependencies{$embed_file} = 1; 9562: if ($absolutepath) { 9563: $mapping{$embed_file} = $absolutepath; 9564: } else { 9565: $mapping{$embed_file} = $embed_file; 9566: } 9567: } 9568: } 9569: } 9570: my $dirptr = 16384; 9571: foreach my $path (keys(%subdependencies)) { 9572: $currsubfile{$path} = {}; 9573: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 9574: my ($sublistref,$listerror) = 9575: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath); 9576: if (ref($sublistref) eq 'ARRAY') { 9577: foreach my $line (@{$sublistref}) { 9578: my ($file_name,$rest) = split(/\&/,$line,2); 9579: $currsubfile{$path}{$file_name} = 1; 9580: } 9581: } 9582: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 9583: if (opendir(my $dir,$url.'/'.$path)) { 9584: my @subdir_list = grep(!/^\./,readdir($dir)); 9585: map {$currsubfile{$path}{$_} = 1;} @subdir_list; 9586: } 9587: } elsif (($actionurl eq '/adm/dependencies') || 9588: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 9589: ($args->{'context'} eq 'paste'))) { 9590: if ($env{'request.course.id'} ne '') { 9591: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); 9592: if ($dir ne '') { 9593: my ($sublistref,$listerror) = 9594: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/'); 9595: if (ref($sublistref) eq 'ARRAY') { 9596: foreach my $line (@{$sublistref}) { 9597: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size, 9598: undef,$mtime)=split(/\&/,$line,12); 9599: unless (($testdir&$dirptr) || 9600: ($file_name =~ /^\.\.?$/)) { 9601: $currsubfile{$path}{$file_name} = [$size,$mtime]; 9602: } 9603: } 9604: } 9605: } 9606: } 9607: } 9608: foreach my $file (keys(%{$subdependencies{$path}})) { 9609: if (exists($currsubfile{$path}{$file})) { 9610: my $item = $path.'/'.$file; 9611: unless ($mapping{$item} eq $item) { 9612: $pathchanges{$item} = 1; 9613: } 9614: $existing{$item} = 1; 9615: $numexisting ++; 9616: } else { 9617: $newfiles{$path.'/'.$file} = 1; 9618: } 9619: } 9620: if ($actionurl eq '/adm/dependencies') { 9621: foreach my $path (keys(%currsubfile)) { 9622: if (ref($currsubfile{$path}) eq 'HASH') { 9623: foreach my $file (keys(%{$currsubfile{$path}})) { 9624: unless ($subdependencies{$path}{$file}) { 9625: next if (($rem ne '') && 9626: (($env{"httpref.$rem"."$path/$file"} ne '') || 9627: (ref($navmap) && 9628: (($navmap->getResourceByUrl($rem."$path/$file") ne '') || 9629: (($file =~ /^(.*\.s?html?)\.bak$/i) && 9630: ($navmap->getResourceByUrl($rem."$path/$1"))))))); 9631: $unused{$path.'/'.$file} = 1; 9632: } 9633: } 9634: } 9635: } 9636: } 9637: } 9638: my %currfile; 9639: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 9640: my ($dirlistref,$listerror) = 9641: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath); 9642: if (ref($dirlistref) eq 'ARRAY') { 9643: foreach my $line (@{$dirlistref}) { 9644: my ($file_name,$rest) = split(/\&/,$line,2); 9645: $currfile{$file_name} = 1; 9646: } 9647: } 9648: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 9649: if (opendir(my $dir,$url)) { 9650: my @dir_list = grep(!/^\./,readdir($dir)); 9651: map {$currfile{$_} = 1;} @dir_list; 9652: } 9653: } elsif (($actionurl eq '/adm/dependencies') || 9654: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 9655: ($args->{'context'} eq 'paste'))) { 9656: if ($env{'request.course.id'} ne '') { 9657: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$}); 9658: if ($dir ne '') { 9659: my ($dirlistref,$listerror) = 9660: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/'); 9661: if (ref($dirlistref) eq 'ARRAY') { 9662: foreach my $line (@{$dirlistref}) { 9663: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef, 9664: $size,undef,$mtime)=split(/\&/,$line,12); 9665: unless (($testdir&$dirptr) || 9666: ($file_name =~ /^\.\.?$/)) { 9667: $currfile{$file_name} = [$size,$mtime]; 9668: } 9669: } 9670: } 9671: } 9672: } 9673: } 9674: foreach my $file (keys(%dependencies)) { 9675: if (exists($currfile{$file})) { 9676: unless ($mapping{$file} eq $file) { 9677: $pathchanges{$file} = 1; 9678: } 9679: $existing{$file} = 1; 9680: $numexisting ++; 9681: } else { 9682: $newfiles{$file} = 1; 9683: } 9684: } 9685: foreach my $file (keys(%currfile)) { 9686: unless (($file eq $filename) || 9687: ($file eq $filename.'.bak') || 9688: ($dependencies{$file})) { 9689: if ($actionurl eq '/adm/dependencies') { 9690: next if (($rem ne '') && 9691: (($env{"httpref.$rem".$file} ne '') || 9692: (ref($navmap) && 9693: (($navmap->getResourceByUrl($rem.$file) ne '') || 9694: (($file =~ /^(.*\.s?html?)\.bak$/i) && 9695: ($navmap->getResourceByUrl($rem.$1))))))); 9696: } 9697: $unused{$file} = 1; 9698: } 9699: } 9700: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') && 9701: ($args->{'context'} eq 'paste')) { 9702: $counter = scalar(keys(%existing)); 9703: $numpathchg = scalar(keys(%pathchanges)); 9704: return ($output,$counter,$numpathchg,\%existing); 9705: } 9706: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) { 9707: if ($actionurl eq '/adm/dependencies') { 9708: next if ($embed_file =~ m{^\w+://}); 9709: } 9710: $upload_output .= &start_data_table_row(). 9711: '<td><img src="'.&icon($embed_file).'" /> '. 9712: '<span class="LC_filename">'.$embed_file.'</span>'; 9713: unless ($mapping{$embed_file} eq $embed_file) { 9714: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>'; 9715: } 9716: $upload_output .= '</td><td>'; 9717: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 9718: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>'; 9719: $numremref++; 9720: } elsif ($args->{'error_on_invalid_names'} 9721: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) { 9722: $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>'; 9723: $numinvalid++; 9724: } else { 9725: $upload_output .= &embedded_file_element('upload_embedded',$counter, 9726: $embed_file,\%mapping, 9727: $allfiles,$codebase,'upload'); 9728: $counter ++; 9729: $numnew ++; 9730: } 9731: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n"; 9732: } 9733: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) { 9734: if ($actionurl eq '/adm/dependencies') { 9735: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file); 9736: $modify_output .= &start_data_table_row(). 9737: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'. 9738: '<img src="'.&icon($embed_file).'" border="0" />'. 9739: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'. 9740: '<td>'.$size.'</td>'. 9741: '<td>'.$mtime.'</td>'. 9742: '<td><label><input type="checkbox" name="mod_upload_dep" '. 9743: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'. 9744: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'. 9745: '<div id="moduploaddep_'.$counter.'" style="display:none;">'. 9746: &embedded_file_element('upload_embedded',$counter, 9747: $embed_file,\%mapping, 9748: $allfiles,$codebase,'modify'). 9749: '</div></td>'. 9750: &end_data_table_row()."\n"; 9751: $counter ++; 9752: } else { 9753: $upload_output .= &start_data_table_row(). 9754: '<td><span class="LC_filename">'.$embed_file.'</span></td>'; 9755: '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'. 9756: &Apache::loncommon::end_data_table_row()."\n"; 9757: } 9758: } 9759: my $delidx = $counter; 9760: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) { 9761: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile); 9762: $delete_output .= &start_data_table_row(). 9763: '<td><img src="'.&icon($oldfile).'" />'. 9764: ' <span class="LC_filename">'.$oldfile.'</span></td>'. 9765: '<td>'.$size.'</td>'. 9766: '<td>'.$mtime.'</td>'. 9767: '<td><label><input type="checkbox" name="del_upload_dep" '. 9768: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'. 9769: &embedded_file_element('upload_embedded',$delidx, 9770: $oldfile,\%mapping,$allfiles, 9771: $codebase,'delete').'</td>'. 9772: &end_data_table_row()."\n"; 9773: $numunused ++; 9774: $delidx ++; 9775: } 9776: if ($upload_output) { 9777: $upload_output = &start_data_table(). 9778: $upload_output. 9779: &end_data_table()."\n"; 9780: } 9781: if ($modify_output) { 9782: $modify_output = &start_data_table(). 9783: &start_data_table_header_row(). 9784: '<th>'.&mt('File').'</th>'. 9785: '<th>'.&mt('Size (KB)').'</th>'. 9786: '<th>'.&mt('Modified').'</th>'. 9787: '<th>'.&mt('Upload replacement?').'</th>'. 9788: &end_data_table_header_row(). 9789: $modify_output. 9790: &end_data_table()."\n"; 9791: } 9792: if ($delete_output) { 9793: $delete_output = &start_data_table(). 9794: &start_data_table_header_row(). 9795: '<th>'.&mt('File').'</th>'. 9796: '<th>'.&mt('Size (KB)').'</th>'. 9797: '<th>'.&mt('Modified').'</th>'. 9798: '<th>'.&mt('Delete?').'</th>'. 9799: &end_data_table_header_row(). 9800: $delete_output. 9801: &end_data_table()."\n"; 9802: } 9803: my $applies = 0; 9804: if ($numremref) { 9805: $applies ++; 9806: } 9807: if ($numinvalid) { 9808: $applies ++; 9809: } 9810: if ($numexisting) { 9811: $applies ++; 9812: } 9813: if ($counter || $numunused) { 9814: $output = '<form name="upload_embedded" action="'.$actionurl.'"'. 9815: ' method="post" enctype="multipart/form-data">'."\n". 9816: $state.'<h3>'.$heading.'</h3>'; 9817: if ($actionurl eq '/adm/dependencies') { 9818: if ($numnew) { 9819: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'. 9820: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n". 9821: $upload_output.'<br />'."\n"; 9822: } 9823: if ($numexisting) { 9824: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'. 9825: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n". 9826: $modify_output.'<br />'."\n"; 9827: $buttontext = &mt('Save changes'); 9828: } 9829: if ($numunused) { 9830: $output .= '<h4>'.&mt('Unused files').'</h4>'. 9831: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n". 9832: $delete_output.'<br />'."\n"; 9833: $buttontext = &mt('Save changes'); 9834: } 9835: } else { 9836: $output .= $upload_output.'<br />'."\n"; 9837: } 9838: $output .= '<input type ="hidden" name="number_embedded_items" value="'. 9839: $counter.'" />'."\n"; 9840: if ($actionurl eq '/adm/dependencies') { 9841: $output .= '<input type ="hidden" name="number_newemb_items" value="'. 9842: $numnew.'" />'."\n"; 9843: } elsif ($actionurl eq '') { 9844: $output .= '<input type="hidden" name="phase" value="three" />'; 9845: } 9846: } elsif ($applies) { 9847: $output = '<b>'.&mt('Referenced files').'</b>:<br />'; 9848: if ($applies > 1) { 9849: $output .= 9850: &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>'; 9851: if ($numremref) { 9852: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n"; 9853: } 9854: if ($numinvalid) { 9855: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n"; 9856: } 9857: if ($numexisting) { 9858: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n"; 9859: } 9860: $output .= '</ul><br />'; 9861: } elsif ($numremref) { 9862: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>'; 9863: } elsif ($numinvalid) { 9864: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>'; 9865: } elsif ($numexisting) { 9866: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>'; 9867: } 9868: $output .= $upload_output.'<br />'; 9869: } 9870: my ($pathchange_output,$chgcount); 9871: $chgcount = $counter; 9872: if (keys(%pathchanges) > 0) { 9873: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) { 9874: if ($counter) { 9875: $output .= &embedded_file_element('pathchange',$chgcount, 9876: $embed_file,\%mapping, 9877: $allfiles,$codebase,'change'); 9878: } else { 9879: $pathchange_output .= 9880: &start_data_table_row(). 9881: '<td><input type ="checkbox" name="namechange" value="'. 9882: $chgcount.'" checked="checked" /></td>'. 9883: '<td>'.$mapping{$embed_file}.'</td>'. 9884: '<td>'.$embed_file. 9885: &embedded_file_element('pathchange',$numpathchg,$embed_file, 9886: \%mapping,$allfiles,$codebase,'change'). 9887: '</td>'.&end_data_table_row(); 9888: } 9889: $numpathchg ++; 9890: $chgcount ++; 9891: } 9892: } 9893: if ($counter) { 9894: if ($numpathchg) { 9895: $output .= '<input type ="hidden" name="number_pathchange_items" value="'. 9896: $numpathchg.'" />'."\n"; 9897: } 9898: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 9899: ($actionurl eq '/adm/imsimport')) { 9900: $output .= '<input type="hidden" name="phase" value="three" />'."\n"; 9901: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') { 9902: $output .= '<input type="hidden" name="action" value="upload_embedded" />'; 9903: } elsif ($actionurl eq '/adm/dependencies') { 9904: $output .= '<input type="hidden" name="action" value="process_changes" />'; 9905: } 9906: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n"; 9907: } elsif ($numpathchg) { 9908: my %pathchange = (); 9909: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output); 9910: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 9911: $output .= '<p>'.&mt('or').'</p>'; 9912: } 9913: } 9914: return ($output,$counter,$numpathchg); 9915: } 9916: 9917: sub embedded_file_element { 9918: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_; 9919: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') && 9920: (ref($codebase) eq 'HASH')); 9921: my $output; 9922: if (($context eq 'upload_embedded') && ($type ne 'delete')) { 9923: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n"; 9924: } 9925: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'. 9926: &escape($embed_file).'" />'; 9927: unless (($context eq 'upload_embedded') && 9928: ($mapping->{$embed_file} eq $embed_file)) { 9929: $output .=' 9930: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />'; 9931: } 9932: my $attrib; 9933: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') { 9934: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}})); 9935: } 9936: $output .= 9937: "\n\t\t". 9938: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'. 9939: $attrib.'" />'; 9940: if (exists($codebase->{$mapping->{$embed_file}})) { 9941: $output .= 9942: "\n\t\t". 9943: '<input name="codebase_'.$num.'" type="hidden" value="'. 9944: &escape($codebase->{$mapping->{$embed_file}}).'" />'; 9945: } 9946: return $output; 9947: } 9948: 9949: sub get_dependency_details { 9950: my ($currfile,$currsubfile,$embed_file) = @_; 9951: my ($size,$mtime,$showsize,$showmtime); 9952: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) { 9953: if ($embed_file =~ m{/}) { 9954: my ($path,$fname) = split(/\//,$embed_file); 9955: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') { 9956: ($size,$mtime) = @{$currsubfile->{$path}{$fname}}; 9957: } 9958: } else { 9959: if (ref($currfile->{$embed_file}) eq 'ARRAY') { 9960: ($size,$mtime) = @{$currfile->{$embed_file}}; 9961: } 9962: } 9963: $showsize = $size/1024.0; 9964: $showsize = sprintf("%.1f",$showsize); 9965: if ($mtime > 0) { 9966: $showmtime = &Apache::lonlocal::locallocaltime($mtime); 9967: } 9968: } 9969: return ($showsize,$showmtime); 9970: } 9971: 9972: sub ask_embedded_js { 9973: return <<"END"; 9974: <script type="text/javascript""> 9975: // <![CDATA[ 9976: function toggleBrowse(counter) { 9977: var chkboxid = document.getElementById('mod_upload_dep_'+counter); 9978: var fileid = document.getElementById('embedded_item_'+counter); 9979: var uploaddivid = document.getElementById('moduploaddep_'+counter); 9980: if (chkboxid.checked == true) { 9981: uploaddivid.style.display='block'; 9982: } else { 9983: uploaddivid.style.display='none'; 9984: fileid.value = ''; 9985: } 9986: } 9987: // ]]> 9988: </script> 9989: 9990: END 9991: } 9992: 9993: sub upload_embedded { 9994: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota, 9995: $current_disk_usage,$hiddenstate,$actionurl) = @_; 9996: my (%pathchange,$output,$modifyform,$footer,$returnflag); 9997: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) { 9998: next if (!exists($env{'form.embedded_item_'.$i.'.filename'})); 9999: my $orig_uploaded_filename = 10000: $env{'form.embedded_item_'.$i.'.filename'}; 10001: foreach my $type ('orig','ref','attrib','codebase') { 10002: if ($env{'form.embedded_'.$type.'_'.$i} ne '') { 10003: $env{'form.embedded_'.$type.'_'.$i} = 10004: &unescape($env{'form.embedded_'.$type.'_'.$i}); 10005: } 10006: } 10007: my ($path,$fname) = 10008: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)}); 10009: # no path, whole string is fname 10010: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} }; 10011: $fname = &Apache::lonnet::clean_filename($fname); 10012: # See if there is anything left 10013: next if ($fname eq ''); 10014: 10015: # Check if file already exists as a file or directory. 10016: my ($state,$msg); 10017: if ($context eq 'portfolio') { 10018: my $port_path = $dirpath; 10019: if ($group ne '') { 10020: $port_path = "groups/$group/$port_path"; 10021: } 10022: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path, 10023: $fname,$group,'embedded_item_'.$i, 10024: $dir_root,$port_path,$disk_quota, 10025: $current_disk_usage,$uname,$udom); 10026: if ($state eq 'will_exceed_quota' 10027: || $state eq 'file_locked') { 10028: $output .= $msg; 10029: next; 10030: } 10031: } elsif (($context eq 'author') || ($context eq 'testbank')) { 10032: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i); 10033: if ($state eq 'exists') { 10034: $output .= $msg; 10035: next; 10036: } 10037: } 10038: # Check if extension is valid 10039: if (($fname =~ /\.(\w+)$/) && 10040: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) { 10041: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />'; 10042: next; 10043: } elsif (($fname =~ /\.(\w+)$/) && 10044: (!defined(&Apache::loncommon::fileembstyle($1)))) { 10045: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />'; 10046: next; 10047: } elsif ($fname=~/\.(\d+)\.(\w+)$/) { 10048: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />'; 10049: next; 10050: } 10051: $env{'form.embedded_item_'.$i.'.filename'}=$fname; 10052: if ($context eq 'portfolio') { 10053: my $result; 10054: if ($state eq 'existingfile') { 10055: $result= 10056: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile', 10057: $dirpath.$env{'form.currentpath'}.$path); 10058: } else { 10059: $result= 10060: &Apache::lonnet::userfileupload('embedded_item_'.$i,'', 10061: $dirpath. 10062: $env{'form.currentpath'}.$path); 10063: if ($result !~ m|^/uploaded/|) { 10064: $output .= '<span class="LC_error">' 10065: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].' 10066: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}) 10067: .'</span><br />'; 10068: next; 10069: } else { 10070: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10071: $path.$fname.'</span>').'<br />'; 10072: } 10073: } 10074: } elsif ($context eq 'coursedoc') { 10075: my $result = 10076: &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc', 10077: $dirpath.'/'.$path); 10078: if ($result !~ m|^/uploaded/|) { 10079: $output .= '<span class="LC_error">' 10080: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].' 10081: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i}) 10082: .'</span><br />'; 10083: next; 10084: } else { 10085: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10086: $path.$fname.'</span>').'<br />'; 10087: } 10088: } else { 10089: # Save the file 10090: my $target = $env{'form.embedded_item_'.$i}; 10091: my $fullpath = $dir_root.$dirpath.'/'.$path; 10092: my $dest = $fullpath.$fname; 10093: my $url = $url_root.$dirpath.'/'.$path.$fname; 10094: my @parts=split(/\//,"$dirpath/$path"); 10095: my $count; 10096: my $filepath = $dir_root; 10097: foreach my $subdir (@parts) { 10098: $filepath .= "/$subdir"; 10099: if (!-e $filepath) { 10100: mkdir($filepath,0770); 10101: } 10102: } 10103: my $fh; 10104: if (!open($fh,'>'.$dest)) { 10105: &Apache::lonnet::logthis('Failed to create '.$dest); 10106: $output .= '<span class="LC_error">'. 10107: &mt('An error occurred while trying to upload [_1] for embedded element [_2].', 10108: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}). 10109: '</span><br />'; 10110: } else { 10111: if (!print $fh $env{'form.embedded_item_'.$i}) { 10112: &Apache::lonnet::logthis('Failed to write to '.$dest); 10113: $output .= '<span class="LC_error">'. 10114: &mt('An error occurred while writing the file [_1] for embedded element [_2].', 10115: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}). 10116: '</span><br />'; 10117: } else { 10118: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'. 10119: $url.'</span>').'<br />'; 10120: unless ($context eq 'testbank') { 10121: $footer .= &mt('View embedded file: [_1]', 10122: '<a href="'.$url.'">'.$fname.'</a>').'<br />'; 10123: } 10124: } 10125: close($fh); 10126: } 10127: } 10128: if ($env{'form.embedded_ref_'.$i}) { 10129: $pathchange{$i} = 1; 10130: } 10131: } 10132: if ($output) { 10133: $output = '<p>'.$output.'</p>'; 10134: } 10135: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange); 10136: $returnflag = 'ok'; 10137: my $numpathchgs = scalar(keys(%pathchange)); 10138: if ($numpathchgs > 0) { 10139: if ($context eq 'portfolio') { 10140: $output .= '<p>'.&mt('or').'</p>'; 10141: } elsif ($context eq 'testbank') { 10142: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).', 10143: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>'; 10144: $returnflag = 'modify_orightml'; 10145: } 10146: } 10147: return ($output.$footer,$returnflag,$numpathchgs); 10148: } 10149: 10150: sub modify_html_form { 10151: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_; 10152: my $end = 0; 10153: my $modifyform; 10154: if ($context eq 'upload_embedded') { 10155: return unless (ref($pathchange) eq 'HASH'); 10156: if ($env{'form.number_embedded_items'}) { 10157: $end += $env{'form.number_embedded_items'}; 10158: } 10159: if ($env{'form.number_pathchange_items'}) { 10160: $end += $env{'form.number_pathchange_items'}; 10161: } 10162: if ($end) { 10163: for (my $i=0; $i<$end; $i++) { 10164: if ($i < $env{'form.number_embedded_items'}) { 10165: next unless($pathchange->{$i}); 10166: } 10167: $modifyform .= 10168: &start_data_table_row(). 10169: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '. 10170: 'checked="checked" /></td>'. 10171: '<td>'.$env{'form.embedded_ref_'.$i}. 10172: '<input type="hidden" name="embedded_ref_'.$i.'" value="'. 10173: &escape($env{'form.embedded_ref_'.$i}).'" />'. 10174: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'. 10175: &escape($env{'form.embedded_codebase_'.$i}).'" />'. 10176: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'. 10177: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'. 10178: '<td>'.$env{'form.embedded_orig_'.$i}. 10179: '<input type="hidden" name="embedded_orig_'.$i.'" value="'. 10180: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'. 10181: &end_data_table_row(); 10182: } 10183: } 10184: } else { 10185: $modifyform = $pathchgtable; 10186: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) { 10187: $hiddenstate .= '<input type="hidden" name="phase" value="four" />'; 10188: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 10189: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />'; 10190: } 10191: } 10192: if ($modifyform) { 10193: if ($actionurl eq '/adm/dependencies') { 10194: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />'; 10195: } 10196: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n". 10197: '<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". 10198: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n". 10199: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n". 10200: '</ol></p>'."\n".'<p>'. 10201: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n". 10202: '<form method="post" name="refchanger" action="'.$actionurl.'">'. 10203: &start_data_table()."\n". 10204: &start_data_table_header_row(). 10205: '<th>'.&mt('Change?').'</th>'. 10206: '<th>'.&mt('Current reference').'</th>'. 10207: '<th>'.&mt('Required reference').'</th>'. 10208: &end_data_table_header_row()."\n". 10209: $modifyform. 10210: &end_data_table().'<br />'."\n".$hiddenstate. 10211: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'. 10212: '</form>'."\n"; 10213: } 10214: return; 10215: } 10216: 10217: sub modify_html_refs { 10218: my ($context,$dirpath,$uname,$udom,$dir_root) = @_; 10219: my $container; 10220: if ($context eq 'portfolio') { 10221: $container = $env{'form.container'}; 10222: } elsif ($context eq 'coursedoc') { 10223: $container = $env{'form.primaryurl'}; 10224: } elsif ($context eq 'manage_dependencies') { 10225: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'}); 10226: $container = "/$container"; 10227: } else { 10228: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'}; 10229: } 10230: my (%allfiles,%codebase,$output,$content); 10231: my @changes = &get_env_multiple('form.namechange'); 10232: unless (@changes > 0) { 10233: if (wantarray) { 10234: return ('',0,0); 10235: } else { 10236: return; 10237: } 10238: } 10239: if (($context eq 'portfolio') || ($context eq 'coursedoc') || 10240: ($context eq 'manage_dependencies')) { 10241: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) { 10242: if (wantarray) { 10243: return ('',0,0); 10244: } else { 10245: return; 10246: } 10247: } 10248: $content = &Apache::lonnet::getfile($container); 10249: if ($content eq '-1') { 10250: if (wantarray) { 10251: return ('',0,0); 10252: } else { 10253: return; 10254: } 10255: } 10256: } else { 10257: unless ($container =~ /^\Q$dir_root\E/) { 10258: if (wantarray) { 10259: return ('',0,0); 10260: } else { 10261: return; 10262: } 10263: } 10264: if (open(my $fh,"<$container")) { 10265: $content = join('', <$fh>); 10266: close($fh); 10267: } else { 10268: if (wantarray) { 10269: return ('',0,0); 10270: } else { 10271: return; 10272: } 10273: } 10274: } 10275: my ($count,$codebasecount) = (0,0); 10276: my $mm = new File::MMagic; 10277: my $mime_type = $mm->checktype_contents($content); 10278: if ($mime_type eq 'text/html') { 10279: my $parse_result = 10280: &Apache::lonnet::extract_embedded_items($container,\%allfiles, 10281: \%codebase,\$content); 10282: if ($parse_result eq 'ok') { 10283: foreach my $i (@changes) { 10284: my $orig = &unescape($env{'form.embedded_orig_'.$i}); 10285: my $ref = &unescape($env{'form.embedded_ref_'.$i}); 10286: if ($allfiles{$ref}) { 10287: my $newname = $orig; 10288: my ($attrib_regexp,$codebase); 10289: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i}); 10290: if ($attrib_regexp =~ /:/) { 10291: $attrib_regexp =~ s/\:/|/g; 10292: } 10293: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) { 10294: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi); 10295: $count += $numchg; 10296: } 10297: if ($env{'form.embedded_codebase_'.$i} ne '') { 10298: $codebase = &unescape($env{'form.embedded_codebase_'.$i}); 10299: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs 10300: $codebasecount ++; 10301: } 10302: } 10303: } 10304: if ($count || $codebasecount) { 10305: my $saveresult; 10306: if (($context eq 'portfolio') || ($context eq 'coursedoc') || 10307: ($context eq 'manage_dependencies')) { 10308: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult); 10309: if ($url eq $container) { 10310: my ($fname) = ($container =~ m{/([^/]+)$}); 10311: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].', 10312: $count,'<span class="LC_filename">'. 10313: $fname.'</span>').'</p>'; 10314: } else { 10315: $output = '<p class="LC_error">'. 10316: &mt('Error: update failed for: [_1].', 10317: '<span class="LC_filename">'. 10318: $container.'</span>').'</p>'; 10319: } 10320: } else { 10321: if (open(my $fh,">$container")) { 10322: print $fh $content; 10323: close($fh); 10324: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].', 10325: $count,'<span class="LC_filename">'. 10326: $container.'</span>').'</p>'; 10327: } else { 10328: $output = '<p class="LC_error">'. 10329: &mt('Error: could not update [_1].', 10330: '<span class="LC_filename">'. 10331: $container.'</span>').'</p>'; 10332: } 10333: } 10334: } 10335: } else { 10336: &logthis('Failed to parse '.$container. 10337: ' to modify references: '.$parse_result); 10338: } 10339: } 10340: if (wantarray) { 10341: return ($output,$count,$codebasecount); 10342: } else { 10343: return $output; 10344: } 10345: } 10346: 10347: sub check_for_existing { 10348: my ($path,$fname,$element) = @_; 10349: my ($state,$msg); 10350: if (-d $path.'/'.$fname) { 10351: $state = 'exists'; 10352: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path); 10353: } elsif (-e $path.'/'.$fname) { 10354: $state = 'exists'; 10355: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path); 10356: } 10357: if ($state eq 'exists') { 10358: $msg = '<span class="LC_error">'.$msg.'</span><br />'; 10359: } 10360: return ($state,$msg); 10361: } 10362: 10363: sub check_for_upload { 10364: my ($path,$fname,$group,$element,$portfolio_root,$port_path, 10365: $disk_quota,$current_disk_usage,$uname,$udom) = @_; 10366: my $filesize = length($env{'form.'.$element}); 10367: if (!$filesize) { 10368: my $msg = '<span class="LC_error">'. 10369: &mt('Unable to upload [_1]. (size = [_2] bytes)', 10370: '<span class="LC_filename">'.$fname.'</span>', 10371: $filesize).'<br />'. 10372: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'. 10373: '</span>'; 10374: return ('zero_bytes',$msg); 10375: } 10376: $filesize = $filesize/1000; #express in k (1024?) 10377: my $getpropath = 1; 10378: my ($dirlistref,$listerror) = 10379: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath); 10380: my $found_file = 0; 10381: my $locked_file = 0; 10382: my @lockers; 10383: my $navmap; 10384: if ($env{'request.course.id'}) { 10385: $navmap = Apache::lonnavmaps::navmap->new(); 10386: } 10387: if (ref($dirlistref) eq 'ARRAY') { 10388: foreach my $line (@{$dirlistref}) { 10389: my ($file_name,$rest)=split(/\&/,$line,2); 10390: if ($file_name eq $fname){ 10391: $file_name = $path.$file_name; 10392: if ($group ne '') { 10393: $file_name = $group.$file_name; 10394: } 10395: $found_file = 1; 10396: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') { 10397: foreach my $lock (@lockers) { 10398: if (ref($lock) eq 'ARRAY') { 10399: my ($symb,$crsid) = @{$lock}; 10400: if ($crsid eq $env{'request.course.id'}) { 10401: if (ref($navmap)) { 10402: my $res = $navmap->getBySymb($symb); 10403: foreach my $part (@{$res->parts()}) { 10404: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part); 10405: unless (($slot_status == $res->RESERVED) || 10406: ($slot_status == $res->RESERVED_LOCATION)) { 10407: $locked_file = 1; 10408: } 10409: } 10410: } else { 10411: $locked_file = 1; 10412: } 10413: } else { 10414: $locked_file = 1; 10415: } 10416: } 10417: } 10418: } else { 10419: my @info = split(/\&/,$rest); 10420: my $currsize = $info[6]/1000; 10421: if ($currsize < $filesize) { 10422: my $extra = $filesize - $currsize; 10423: if (($current_disk_usage + $extra) > $disk_quota) { 10424: my $msg = '<span class="LC_error">'. 10425: &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.', 10426: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'. 10427: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.', 10428: $disk_quota,$current_disk_usage); 10429: return ('will_exceed_quota',$msg); 10430: } 10431: } 10432: } 10433: } 10434: } 10435: } 10436: if (($current_disk_usage + $filesize) > $disk_quota){ 10437: my $msg = '<span class="LC_error">'. 10438: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'. 10439: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage); 10440: return ('will_exceed_quota',$msg); 10441: } elsif ($found_file) { 10442: if ($locked_file) { 10443: my $msg = '<span class="LC_error">'; 10444: $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>'); 10445: $msg .= '</span><br />'; 10446: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>'); 10447: return ('file_locked',$msg); 10448: } else { 10449: my $msg = '<span class="LC_error">'; 10450: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'}); 10451: $msg .= '</span>'; 10452: return ('existingfile',$msg); 10453: } 10454: } 10455: } 10456: 10457: sub check_for_traversal { 10458: my ($path,$url,$toplevel) = @_; 10459: my @parts=split(/\//,$path); 10460: my $cleanpath; 10461: my $fullpath = $url; 10462: for (my $i=0;$i<@parts;$i++) { 10463: next if ($parts[$i] eq '.'); 10464: if ($parts[$i] eq '..') { 10465: $fullpath =~ s{([^/]+/)$}{}; 10466: } else { 10467: $fullpath .= $parts[$i].'/'; 10468: } 10469: } 10470: if ($fullpath =~ /^\Q$url\E(.*)$/) { 10471: $cleanpath = $1; 10472: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) { 10473: my $curr_toprel = $1; 10474: my @parts = split(/\//,$curr_toprel); 10475: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/); 10476: my @urlparts = split(/\//,$url_toprel); 10477: my $doubledots; 10478: my $startdiff = -1; 10479: for (my $i=0; $i<@urlparts; $i++) { 10480: if ($startdiff == -1) { 10481: unless ($urlparts[$i] eq $parts[$i]) { 10482: $startdiff = $i; 10483: $doubledots .= '../'; 10484: } 10485: } else { 10486: $doubledots .= '../'; 10487: } 10488: } 10489: if ($startdiff > -1) { 10490: $cleanpath = $doubledots; 10491: for (my $i=$startdiff; $i<@parts; $i++) { 10492: $cleanpath .= $parts[$i].'/'; 10493: } 10494: } 10495: } 10496: $cleanpath =~ s{(/)$}{}; 10497: return $cleanpath; 10498: } 10499: 10500: sub is_archive_file { 10501: my ($mimetype) = @_; 10502: if (($mimetype eq 'application/octet-stream') || 10503: ($mimetype eq 'application/x-stuffit') || 10504: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) { 10505: return 1; 10506: } 10507: return; 10508: } 10509: 10510: sub decompress_form { 10511: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_; 10512: my %lt = &Apache::lonlocal::texthash ( 10513: this => 'This file is an archive file.', 10514: camt => 'This file is a Camtasia archive file.', 10515: itsc => 'Its contents are as follows:', 10516: youm => 'You may wish to extract its contents.', 10517: extr => 'Extract contents', 10518: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.', 10519: proa => 'Process automatically?', 10520: yes => 'Yes', 10521: no => 'No', 10522: fold => 'Title for folder containing movie', 10523: movi => 'Title for page containing embedded movie', 10524: ); 10525: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl); 10526: my ($is_camtasia,$topdir,%toplevel,@paths); 10527: my $info = &list_archive_contents($fileloc,\@paths); 10528: if (@paths) { 10529: foreach my $path (@paths) { 10530: $path =~ s{^/}{}; 10531: if ($path =~ m{^([^/]+)/$}) { 10532: $topdir = $1; 10533: } 10534: if ($path =~ m{^([^/]+)/}) { 10535: $toplevel{$1} = $path; 10536: } else { 10537: $toplevel{$path} = $path; 10538: } 10539: } 10540: } 10541: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) { 10542: my @camtasia = ("$topdir/","$topdir/index.html", 10543: "$topdir/media/", 10544: "$topdir/media/$topdir.mp4", 10545: "$topdir/media/FirstFrame.png", 10546: "$topdir/media/player.swf", 10547: "$topdir/media/swfobject.js", 10548: "$topdir/media/expressInstall.swf"); 10549: my @diffs = &compare_arrays(\@paths,\@camtasia); 10550: if (@diffs == 0) { 10551: $is_camtasia = 1; 10552: } 10553: } 10554: my $output; 10555: if ($is_camtasia) { 10556: $output = <<"ENDCAM"; 10557: <script type="text/javascript" language="Javascript"> 10558: // <![CDATA[ 10559: 10560: function camtasiaToggle() { 10561: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) { 10562: if (document.uploaded_decompress.autoextract_camtasia[i].checked) { 10563: if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) { 10564: 10565: document.getElementById('camtasia_titles').style.display='block'; 10566: } else { 10567: document.getElementById('camtasia_titles').style.display='none'; 10568: } 10569: } 10570: } 10571: return; 10572: } 10573: 10574: // ]]> 10575: </script> 10576: <p>$lt{'camt'}</p> 10577: ENDCAM 10578: } else { 10579: $output = '<p>'.$lt{'this'}; 10580: if ($info eq '') { 10581: $output .= ' '.$lt{'youm'}.'</p>'."\n"; 10582: } else { 10583: $output .= ' '.$lt{'itsc'}.'</p>'."\n". 10584: '<div><pre>'.$info.'</pre></div>'; 10585: } 10586: } 10587: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n"; 10588: my $duplicates; 10589: my $num = 0; 10590: if (ref($dirlist) eq 'ARRAY') { 10591: foreach my $item (@{$dirlist}) { 10592: if (ref($item) eq 'ARRAY') { 10593: if (exists($toplevel{$item->[0]})) { 10594: $duplicates .= 10595: &start_data_table_row(). 10596: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '. 10597: 'value="0" checked="checked" />'.&mt('No').'</label>'. 10598: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '. 10599: 'value="1" />'.&mt('Yes').'</label>'. 10600: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n". 10601: '<td>'.$item->[0].'</td>'; 10602: if ($item->[2]) { 10603: $duplicates .= '<td>'.&mt('Directory').'</td>'; 10604: } else { 10605: $duplicates .= '<td>'.&mt('File').'</td>'; 10606: } 10607: $duplicates .= '<td>'.$item->[3].'</td>'. 10608: '<td>'. 10609: &Apache::lonlocal::locallocaltime($item->[4]). 10610: '</td>'. 10611: &end_data_table_row(); 10612: $num ++; 10613: } 10614: } 10615: } 10616: } 10617: my $itemcount; 10618: if (@paths > 0) { 10619: $itemcount = scalar(@paths); 10620: } else { 10621: $itemcount = 1; 10622: } 10623: if ($is_camtasia) { 10624: $output .= $lt{'auto'}.'<br />'. 10625: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'. 10626: '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'. 10627: $lt{'yes'}.'</label> <label>'. 10628: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'. 10629: $lt{'no'}.'</label></span><br />'. 10630: '<div id="camtasia_titles" style="display:block">'. 10631: &Apache::lonhtmlcommon::start_pick_box(). 10632: &Apache::lonhtmlcommon::row_title($lt{'fold'}). 10633: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n". 10634: &Apache::lonhtmlcommon::row_closure(). 10635: &Apache::lonhtmlcommon::row_title($lt{'movi'}). 10636: '<input type="textbox" name="camtasia_moviename" value="" />'."\n". 10637: &Apache::lonhtmlcommon::row_closure(1). 10638: &Apache::lonhtmlcommon::end_pick_box(). 10639: '</div>'; 10640: } 10641: $output .= 10642: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'. 10643: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'. 10644: "\n"; 10645: if ($duplicates ne '') { 10646: $output .= '<p><span class="LC_warning">'. 10647: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'. 10648: &start_data_table(). 10649: &start_data_table_header_row(). 10650: '<th>'.&mt('Overwrite?').'</th>'. 10651: '<th>'.&mt('Name').'</th>'. 10652: '<th>'.&mt('Type').'</th>'. 10653: '<th>'.&mt('Size').'</th>'. 10654: '<th>'.&mt('Last modified').'</th>'. 10655: &end_data_table_header_row(). 10656: $duplicates. 10657: &end_data_table(). 10658: '</p>'; 10659: } 10660: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n"; 10661: if (ref($hiddenelements) eq 'HASH') { 10662: foreach my $hidden (sort(keys(%{$hiddenelements}))) { 10663: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n"; 10664: } 10665: } 10666: $output .= <<"END"; 10667: <br /> 10668: <input type="submit" name="decompress" value="$lt{'extr'}" /> 10669: </form> 10670: $noextract 10671: END 10672: return $output; 10673: } 10674: 10675: sub decompression_utility { 10676: my ($program) = @_; 10677: my @utilities = ('tar','gunzip','bunzip2','unzip'); 10678: my $location; 10679: if (grep(/^\Q$program\E$/,@utilities)) { 10680: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/', 10681: '/usr/sbin/') { 10682: if (-x $dir.$program) { 10683: $location = $dir.$program; 10684: last; 10685: } 10686: } 10687: } 10688: return $location; 10689: } 10690: 10691: sub list_archive_contents { 10692: my ($file,$pathsref) = @_; 10693: my (@cmd,$output); 10694: my $needsregexp; 10695: if ($file =~ /\.zip$/) { 10696: @cmd = (&decompression_utility('unzip'),"-l"); 10697: $needsregexp = 1; 10698: } elsif (($file =~ m/\.tar\.gz$/) || 10699: ($file =~ /\.tgz$/)) { 10700: @cmd = (&decompression_utility('tar'),"-ztf"); 10701: } elsif ($file =~ /\.tar\.bz2$/) { 10702: @cmd = (&decompression_utility('tar'),"-jtf"); 10703: } elsif ($file =~ m|\.tar$|) { 10704: @cmd = (&decompression_utility('tar'),"-tf"); 10705: } 10706: if (@cmd) { 10707: undef($!); 10708: undef($@); 10709: if (open(my $fh,"-|", @cmd, $file)) { 10710: while (my $line = <$fh>) { 10711: $output .= $line; 10712: chomp($line); 10713: my $item; 10714: if ($needsregexp) { 10715: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 10716: } else { 10717: $item = $line; 10718: } 10719: if ($item ne '') { 10720: unless (grep(/^\Q$item\E$/,@{$pathsref})) { 10721: push(@{$pathsref},$item); 10722: } 10723: } 10724: } 10725: close($fh); 10726: } 10727: } 10728: return $output; 10729: } 10730: 10731: sub decompress_uploaded_file { 10732: my ($file,$dir) = @_; 10733: &Apache::lonnet::appenv({'cgi.file' => $file}); 10734: &Apache::lonnet::appenv({'cgi.dir' => $dir}); 10735: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl'); 10736: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$}); 10737: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'}; 10738: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1); 10739: my $decompressed = $env{'cgi.decompressed'}; 10740: &Apache::lonnet::delenv('cgi.file'); 10741: &Apache::lonnet::delenv('cgi.dir'); 10742: &Apache::lonnet::delenv('cgi.decompressed'); 10743: return ($decompressed,$result); 10744: } 10745: 10746: sub process_decompression { 10747: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_; 10748: my ($dir,$error,$warning,$output); 10749: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) { 10750: $error = &mt('File name not a supported archive file type.'). 10751: '<br />'.&mt('File name should end with one of: [_1].', 10752: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz'); 10753: } else { 10754: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom); 10755: if ($docuhome eq 'no_host') { 10756: $error = &mt('Could not determine home server for course.'); 10757: } else { 10758: my @ids=&Apache::lonnet::current_machine_ids(); 10759: my $currdir = "$dir_root/$destination"; 10760: if (grep(/^\Q$docuhome\E$/,@ids)) { 10761: $dir = &LONCAPA::propath($docudom,$docuname). 10762: "$dir_root/$destination"; 10763: } else { 10764: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}. 10765: "$dir_root/$docudom/$docuname/$destination"; 10766: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') { 10767: $error = &mt('Archive file not found.'); 10768: } 10769: } 10770: my (@to_overwrite,@to_skip); 10771: if ($env{'form.archive_overwrite_total'} > 0) { 10772: my $total = $env{'form.archive_overwrite_total'}; 10773: for (my $i=0; $i<$total; $i++) { 10774: if ($env{'form.archive_overwrite_'.$i} == 1) { 10775: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i}); 10776: } elsif ($env{'form.archive_overwrite_'.$i} == 0) { 10777: push(@to_skip,$env{'form.archive_overwrite_name_'.$i}); 10778: } 10779: } 10780: } 10781: my $numskip = scalar(@to_skip); 10782: if (($numskip > 0) && 10783: ($numskip == $env{'form.archive_itemcount'})) { 10784: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.'); 10785: } elsif ($dir eq '') { 10786: $error = &mt('Directory containing archive file unavailable.'); 10787: } elsif (!$error) { 10788: my ($decompressed,$display); 10789: if ($numskip > 0) { 10790: my $tempdir = time.'_'.$$.int(rand(10000)); 10791: mkdir("$dir/$tempdir",0755); 10792: system("mv $dir/$file $dir/$tempdir/$file"); 10793: ($decompressed,$display) = 10794: &decompress_uploaded_file($file,"$dir/$tempdir"); 10795: foreach my $item (@to_skip) { 10796: if (($item ne '') && ($item !~ /\.\./)) { 10797: if (-f "$dir/$tempdir/$item") { 10798: unlink("$dir/$tempdir/$item"); 10799: } elsif (-d "$dir/$tempdir/$item") { 10800: system("rm -rf $dir/$tempdir/$item"); 10801: } 10802: } 10803: } 10804: system("mv $dir/$tempdir/* $dir"); 10805: rmdir("$dir/$tempdir"); 10806: } else { 10807: ($decompressed,$display) = 10808: &decompress_uploaded_file($file,$dir); 10809: } 10810: if ($decompressed eq 'ok') { 10811: $output = '<p class="LC_info">'. 10812: &mt('Files extracted successfully from archive.'). 10813: '</p>'."\n"; 10814: my ($warning,$result,@contents); 10815: my ($newdirlistref,$newlisterror) = 10816: &Apache::lonnet::dirlist($currdir,$docudom, 10817: $docuname,1); 10818: my (%is_dir,%changes,@newitems); 10819: my $dirptr = 16384; 10820: if (ref($newdirlistref) eq 'ARRAY') { 10821: foreach my $dir_line (@{$newdirlistref}) { 10822: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5); 10823: unless (($item =~ /^\.+$/) || ($item eq $file) || 10824: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) { 10825: push(@newitems,$item); 10826: if ($dirptr&$testdir) { 10827: $is_dir{$item} = 1; 10828: } 10829: $changes{$item} = 1; 10830: } 10831: } 10832: } 10833: if (keys(%changes) > 0) { 10834: foreach my $item (sort(@newitems)) { 10835: if ($changes{$item}) { 10836: push(@contents,$item); 10837: } 10838: } 10839: } 10840: if (@contents > 0) { 10841: my $wantform; 10842: unless ($env{'form.autoextract_camtasia'}) { 10843: $wantform = 1; 10844: } 10845: my (%children,%parent,%dirorder,%titles); 10846: my ($count,$datatable) = &get_extracted($docudom,$docuname, 10847: $currdir,\%is_dir, 10848: \%children,\%parent, 10849: \@contents,\%dirorder, 10850: \%titles,$wantform); 10851: if ($datatable ne '') { 10852: $output .= &archive_options_form('decompressed',$datatable, 10853: $count,$hiddenelem); 10854: my $startcount = 6; 10855: $output .= &archive_javascript($startcount,$count, 10856: \%titles,\%children); 10857: } 10858: if ($env{'form.autoextract_camtasia'}) { 10859: my %displayed; 10860: my $total = 1; 10861: $env{'form.archive_directory'} = []; 10862: foreach my $i (sort { $a <=> $b } keys(%dirorder)) { 10863: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}}); 10864: $path =~ s{/$}{}; 10865: my $item; 10866: if ($path ne '') { 10867: $item = "$path/$titles{$i}"; 10868: } else { 10869: $item = $titles{$i}; 10870: } 10871: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item"; 10872: if ($item eq $contents[0]) { 10873: push(@{$env{'form.archive_directory'}},$i); 10874: $env{'form.archive_'.$i} = 'display'; 10875: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'}; 10876: $displayed{'folder'} = $i; 10877: } elsif ($item eq "$contents[0]/index.html") { 10878: $env{'form.archive_'.$i} = 'display'; 10879: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'}; 10880: $displayed{'web'} = $i; 10881: } else { 10882: if ($item eq "$contents[0]/media") { 10883: push(@{$env{'form.archive_directory'}},$i); 10884: } 10885: $env{'form.archive_'.$i} = 'dependency'; 10886: } 10887: $total ++; 10888: } 10889: for (my $i=1; $i<$total; $i++) { 10890: next if ($i == $displayed{'web'}); 10891: next if ($i == $displayed{'folder'}); 10892: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'}; 10893: } 10894: $env{'form.phase'} = 'decompress_cleanup'; 10895: $env{'form.archivedelete'} = 1; 10896: $env{'form.archive_count'} = $total-1; 10897: $output .= 10898: &process_extracted_files('coursedocs',$docudom, 10899: $docuname,$destination, 10900: $dir_root,$hiddenelem); 10901: } 10902: } else { 10903: $warning = &mt('No new items extracted from archive file.'); 10904: } 10905: } else { 10906: $output = $display; 10907: $error = &mt('An error occurred during extraction from the archive file.'); 10908: } 10909: } 10910: } 10911: } 10912: if ($error) { 10913: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'. 10914: $error.'</p>'."\n"; 10915: } 10916: if ($warning) { 10917: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n"; 10918: } 10919: return $output; 10920: } 10921: 10922: sub get_extracted { 10923: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder, 10924: $titles,$wantform) = @_; 10925: my $count = 0; 10926: my $depth = 0; 10927: my $datatable; 10928: my @hierarchy; 10929: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') && 10930: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') && 10931: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH')); 10932: foreach my $item (@{$contents}) { 10933: $count ++; 10934: @{$dirorder->{$count}} = @hierarchy; 10935: $titles->{$count} = $item; 10936: &archive_hierarchy($depth,$count,$parent,$children); 10937: if ($wantform) { 10938: $datatable .= &archive_row($is_dir->{$item},$item, 10939: $currdir,$depth,$count); 10940: } 10941: if ($is_dir->{$item}) { 10942: $depth ++; 10943: push(@hierarchy,$count); 10944: $parent->{$depth} = $count; 10945: $datatable .= 10946: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname, 10947: \$depth,\$count,\@hierarchy,$dirorder, 10948: $children,$parent,$titles,$wantform); 10949: $depth --; 10950: pop(@hierarchy); 10951: } 10952: } 10953: return ($count,$datatable); 10954: } 10955: 10956: sub recurse_extracted_archive { 10957: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder, 10958: $children,$parent,$titles,$wantform) = @_; 10959: my $result=''; 10960: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') && 10961: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') && 10962: (ref($dirorder) eq 'HASH')) { 10963: return $result; 10964: } 10965: my $dirptr = 16384; 10966: my ($newdirlistref,$newlisterror) = 10967: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1); 10968: if (ref($newdirlistref) eq 'ARRAY') { 10969: foreach my $dir_line (@{$newdirlistref}) { 10970: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5); 10971: unless ($item =~ /^\.+$/) { 10972: $$count ++; 10973: @{$dirorder->{$$count}} = @{$hierarchy}; 10974: $titles->{$$count} = $item; 10975: &archive_hierarchy($$depth,$$count,$parent,$children); 10976: 10977: my $is_dir; 10978: if ($dirptr&$testdir) { 10979: $is_dir = 1; 10980: } 10981: if ($wantform) { 10982: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count); 10983: } 10984: if ($is_dir) { 10985: $$depth ++; 10986: push(@{$hierarchy},$$count); 10987: $parent->{$$depth} = $$count; 10988: $result .= 10989: &recurse_extracted_archive("$currdir/$item",$docudom, 10990: $docuname,$depth,$count, 10991: $hierarchy,$dirorder,$children, 10992: $parent,$titles,$wantform); 10993: $$depth --; 10994: pop(@{$hierarchy}); 10995: } 10996: } 10997: } 10998: } 10999: return $result; 11000: } 11001: 11002: sub archive_hierarchy { 11003: my ($depth,$count,$parent,$children) =@_; 11004: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) { 11005: if (exists($parent->{$depth})) { 11006: $children->{$parent->{$depth}} .= $count.':'; 11007: } 11008: } 11009: return; 11010: } 11011: 11012: sub archive_row { 11013: my ($is_dir,$item,$currdir,$depth,$count) = @_; 11014: my ($name) = ($item =~ m{([^/]+)$}); 11015: my %choices = &Apache::lonlocal::texthash ( 11016: 'display' => 'Add as file', 11017: 'dependency' => 'Include as dependency', 11018: 'discard' => 'Discard', 11019: ); 11020: if ($is_dir) { 11021: $choices{'display'} = &mt('Add as folder'); 11022: } 11023: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n"; 11024: my $offset = 0; 11025: foreach my $action ('display','dependency','discard') { 11026: $offset ++; 11027: if ($action ne 'display') { 11028: $offset ++; 11029: } 11030: $output .= '<td><span class="LC_nobreak">'. 11031: '<label><input type="radio" name="archive_'.$count. 11032: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"'; 11033: my $text = $choices{$action}; 11034: if ($is_dir) { 11035: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"'; 11036: if ($action eq 'display') { 11037: $text = &mt('Add as folder'); 11038: } 11039: } else { 11040: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"'; 11041: 11042: } 11043: $output .= ' /> '.$choices{$action}.'</label></span>'; 11044: if ($action eq 'dependency') { 11045: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n". 11046: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '. 11047: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n". 11048: '<option value=""></option>'."\n". 11049: '</select>'."\n". 11050: '</div>'; 11051: } elsif ($action eq 'display') { 11052: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n". 11053: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n". 11054: '</div>'; 11055: } 11056: $output .= '</td>'; 11057: } 11058: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'. 11059: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2); 11060: for (my $i=0; $i<$depth; $i++) { 11061: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n"; 11062: } 11063: if ($is_dir) { 11064: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n". 11065: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n"; 11066: } else { 11067: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n"; 11068: } 11069: $output .= ' '.$name.'</td>'."\n". 11070: &end_data_table_row(); 11071: return $output; 11072: } 11073: 11074: sub archive_options_form { 11075: my ($form,$display,$count,$hiddenelem) = @_; 11076: my %lt = &Apache::lonlocal::texthash( 11077: perm => 'Permanently remove archive file?', 11078: hows => 'How should each extracted item be incorporated in the course?', 11079: cont => 'Content actions for all', 11080: addf => 'Add as folder/file', 11081: incd => 'Include as dependency for a displayed file', 11082: disc => 'Discard', 11083: no => 'No', 11084: yes => 'Yes', 11085: save => 'Save', 11086: ); 11087: my $output = <<"END"; 11088: <form name="$form" method="post" action=""> 11089: <p><span class="LC_nobreak">$lt{'perm'} 11090: <label> 11091: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'} 11092: </label> 11093: 11094: <label> 11095: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label> 11096: </span> 11097: </p> 11098: <input type="hidden" name="phase" value="decompress_cleanup" /> 11099: <br />$lt{'hows'} 11100: <div class="LC_columnSection"> 11101: <fieldset> 11102: <legend>$lt{'cont'}</legend> 11103: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 11104: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" /> 11105: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" /> 11106: </fieldset> 11107: </div> 11108: END 11109: return $output. 11110: &start_data_table()."\n". 11111: $display."\n". 11112: &end_data_table()."\n". 11113: '<input type="hidden" name="archive_count" value="'.$count.'" />'. 11114: $hiddenelem. 11115: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'. 11116: '</form>'; 11117: } 11118: 11119: sub archive_javascript { 11120: my ($startcount,$numitems,$titles,$children) = @_; 11121: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH')); 11122: my $maintitle = $env{'form.comment'}; 11123: my $scripttag = <<START; 11124: <script type="text/javascript"> 11125: // <![CDATA[ 11126: 11127: function checkAll(form,prefix) { 11128: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$"); 11129: for (var i=0; i < form.elements.length; i++) { 11130: var id = form.elements[i].id; 11131: if ((id != '') && (id != undefined)) { 11132: if (idstr.test(id)) { 11133: if (form.elements[i].type == 'radio') { 11134: form.elements[i].checked = true; 11135: var nostart = i-$startcount; 11136: var offset = nostart%7; 11137: var count = (nostart-offset)/7; 11138: dependencyCheck(form,count,offset); 11139: } 11140: } 11141: } 11142: } 11143: } 11144: 11145: function propagateCheck(form,count) { 11146: if (count > 0) { 11147: var startelement = $startcount + ((count-1) * 7); 11148: for (var j=1; j<6; j++) { 11149: if ((j != 2) && (j != 4)) { 11150: var item = startelement + j; 11151: if (form.elements[item].type == 'radio') { 11152: if (form.elements[item].checked) { 11153: containerCheck(form,count,j); 11154: break; 11155: } 11156: } 11157: } 11158: } 11159: } 11160: } 11161: 11162: numitems = $numitems 11163: var titles = new Array(numitems); 11164: var parents = new Array(numitems); 11165: for (var i=0; i<numitems; i++) { 11166: parents[i] = new Array; 11167: } 11168: var maintitle = '$maintitle'; 11169: 11170: START 11171: 11172: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) { 11173: my @contents = split(/:/,$children->{$container}); 11174: for (my $i=0; $i<@contents; $i ++) { 11175: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n"; 11176: } 11177: } 11178: 11179: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) { 11180: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n"; 11181: } 11182: 11183: $scripttag .= <<END; 11184: 11185: function containerCheck(form,count,offset) { 11186: if (count > 0) { 11187: dependencyCheck(form,count,offset); 11188: var item = (offset+$startcount)+7*(count-1); 11189: form.elements[item].checked = true; 11190: if(Object.prototype.toString.call(parents[count]) === '[object Array]') { 11191: if (parents[count].length > 0) { 11192: for (var j=0; j<parents[count].length; j++) { 11193: containerCheck(form,parents[count][j],offset); 11194: } 11195: } 11196: } 11197: } 11198: } 11199: 11200: function dependencyCheck(form,count,offset) { 11201: if (count > 0) { 11202: var chosen = (offset+$startcount)+7*(count-1); 11203: var depitem = $startcount + ((count-1) * 7) + 4; 11204: var currtype = form.elements[depitem].type; 11205: if (form.elements[chosen].value == 'dependency') { 11206: document.getElementById('arc_depon_'+count).style.display='block'; 11207: form.elements[depitem].options.length = 0; 11208: form.elements[depitem].options[0] = new Option('Select','',true,true); 11209: for (var i=1; i<=numitems; i++) { 11210: if (i == count) { 11211: continue; 11212: } 11213: var startelement = $startcount + (i-1) * 7; 11214: for (var j=1; j<6; j++) { 11215: if ((j != 2) && (j!= 4)) { 11216: var item = startelement + j; 11217: if (form.elements[item].type == 'radio') { 11218: if (form.elements[item].checked) { 11219: if (form.elements[item].value == 'display') { 11220: var n = form.elements[depitem].options.length; 11221: form.elements[depitem].options[n] = new Option(titles[i],i,false,false); 11222: } 11223: } 11224: } 11225: } 11226: } 11227: } 11228: } else { 11229: document.getElementById('arc_depon_'+count).style.display='none'; 11230: form.elements[depitem].options.length = 0; 11231: form.elements[depitem].options[0] = new Option('Select','',true,true); 11232: } 11233: titleCheck(form,count,offset); 11234: } 11235: } 11236: 11237: function propagateSelect(form,count,offset) { 11238: if (count > 0) { 11239: var item = (1+offset+$startcount)+7*(count-1); 11240: var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 11241: if (Object.prototype.toString.call(parents[count]) === '[object Array]') { 11242: if (parents[count].length > 0) { 11243: for (var j=0; j<parents[count].length; j++) { 11244: containerSelect(form,parents[count][j],offset,picked); 11245: } 11246: } 11247: } 11248: } 11249: } 11250: 11251: function containerSelect(form,count,offset,picked) { 11252: if (count > 0) { 11253: var item = (offset+$startcount)+7*(count-1); 11254: if (form.elements[item].type == 'radio') { 11255: if (form.elements[item].value == 'dependency') { 11256: if (form.elements[item+1].type == 'select-one') { 11257: for (var i=0; i<form.elements[item+1].options.length; i++) { 11258: if (form.elements[item+1].options[i].value == picked) { 11259: form.elements[item+1].selectedIndex = i; 11260: break; 11261: } 11262: } 11263: } 11264: if (Object.prototype.toString.call(parents[count]) === '[object Array]') { 11265: if (parents[count].length > 0) { 11266: for (var j=0; j<parents[count].length; j++) { 11267: containerSelect(form,parents[count][j],offset,picked); 11268: } 11269: } 11270: } 11271: } 11272: } 11273: } 11274: } 11275: 11276: function titleCheck(form,count,offset) { 11277: if (count > 0) { 11278: var chosen = (offset+$startcount)+7*(count-1); 11279: var depitem = $startcount + ((count-1) * 7) + 2; 11280: var currtype = form.elements[depitem].type; 11281: if (form.elements[chosen].value == 'display') { 11282: document.getElementById('arc_title_'+count).style.display='block'; 11283: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) { 11284: document.getElementById('archive_title_'+count).value=maintitle; 11285: } 11286: } else { 11287: document.getElementById('arc_title_'+count).style.display='none'; 11288: if (currtype == 'text') { 11289: document.getElementById('archive_title_'+count).value=''; 11290: } 11291: } 11292: } 11293: return; 11294: } 11295: 11296: // ]]> 11297: </script> 11298: END 11299: return $scripttag; 11300: } 11301: 11302: sub process_extracted_files { 11303: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_; 11304: my $numitems = $env{'form.archive_count'}; 11305: return unless ($numitems); 11306: my @ids=&Apache::lonnet::current_machine_ids(); 11307: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir, 11308: %folders,%containers,%mapinner,%prompttofetch); 11309: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom); 11310: if (grep(/^\Q$docuhome\E$/,@ids)) { 11311: $prefix = &LONCAPA::propath($docudom,$docuname); 11312: $pathtocheck = "$dir_root/$destination"; 11313: $dir = $dir_root; 11314: $ishome = 1; 11315: } else { 11316: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'}; 11317: $pathtocheck = "$dir_root/$docudom/$docuname/$destination"; 11318: $dir = "$dir_root/$docudom/$docuname"; 11319: } 11320: my $currdir = "$dir_root/$destination"; 11321: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/}); 11322: if ($env{'form.folderpath'}) { 11323: my @items = split('&',$env{'form.folderpath'}); 11324: $folders{'0'} = $items[-2]; 11325: if ($env{'form.folderpath'} =~ /\:1$/) { 11326: $containers{'0'}='page'; 11327: } else { 11328: $containers{'0'}='sequence'; 11329: } 11330: } 11331: my @archdirs = &get_env_multiple('form.archive_directory'); 11332: if ($numitems) { 11333: for (my $i=1; $i<=$numitems; $i++) { 11334: my $path = $env{'form.archive_content_'.$i}; 11335: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) { 11336: my $item = $1; 11337: $toplevelitems{$item} = $i; 11338: if (grep(/^\Q$i\E$/,@archdirs)) { 11339: $is_dir{$item} = 1; 11340: } 11341: } 11342: } 11343: } 11344: my ($output,%children,%parent,%titles,%dirorder,$result); 11345: if (keys(%toplevelitems) > 0) { 11346: my @contents = sort(keys(%toplevelitems)); 11347: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children, 11348: \%parent,\@contents,\%dirorder,\%titles); 11349: } 11350: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid); 11351: if ($numitems) { 11352: for (my $i=1; $i<=$numitems; $i++) { 11353: next if ($env{'form.archive_'.$i} eq 'dependency'); 11354: my $path = $env{'form.archive_content_'.$i}; 11355: if ($path =~ /^\Q$pathtocheck\E/) { 11356: if ($env{'form.archive_'.$i} eq 'discard') { 11357: if ($prefix ne '' && $path ne '') { 11358: if (-e $prefix.$path) { 11359: if ((@archdirs > 0) && 11360: (grep(/^\Q$i\E$/,@archdirs))) { 11361: $todeletedir{$prefix.$path} = 1; 11362: } else { 11363: $todelete{$prefix.$path} = 1; 11364: } 11365: } 11366: } 11367: } elsif ($env{'form.archive_'.$i} eq 'display') { 11368: my ($docstitle,$title,$url,$outer); 11369: ($title) = ($path =~ m{/([^/]+)$}); 11370: $docstitle = $env{'form.archive_title_'.$i}; 11371: if ($docstitle eq '') { 11372: $docstitle = $title; 11373: } 11374: $outer = 0; 11375: if (ref($dirorder{$i}) eq 'ARRAY') { 11376: if (@{$dirorder{$i}} > 0) { 11377: foreach my $item (reverse(@{$dirorder{$i}})) { 11378: if ($env{'form.archive_'.$item} eq 'display') { 11379: $outer = $item; 11380: last; 11381: } 11382: } 11383: } 11384: } 11385: my ($errtext,$fatal) = 11386: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname. 11387: '/'.$folders{$outer}.'.'. 11388: $containers{$outer}); 11389: next if ($fatal); 11390: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) { 11391: if ($context eq 'coursedocs') { 11392: $mapinner{$i} = time; 11393: $folders{$i} = 'default_'.$mapinner{$i}; 11394: $containers{$i} = 'sequence'; 11395: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'. 11396: $folders{$i}.'.'.$containers{$i}; 11397: my $newidx = &LONCAPA::map::getresidx(); 11398: $LONCAPA::map::resources[$newidx]= 11399: $docstitle.':'.$url.':false:normal:res'; 11400: push(@LONCAPA::map::order,$newidx); 11401: my ($outtext,$errtext) = 11402: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'. 11403: $docuname.'/'.$folders{$outer}. 11404: '.'.$containers{$outer},1,1); 11405: $newseqid{$i} = $newidx; 11406: unless ($errtext) { 11407: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n"; 11408: } 11409: } 11410: } else { 11411: if ($context eq 'coursedocs') { 11412: my $newidx=&LONCAPA::map::getresidx(); 11413: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'. 11414: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'. 11415: $title; 11416: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") { 11417: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755); 11418: } 11419: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") { 11420: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx"); 11421: } 11422: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") { 11423: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title"); 11424: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx"; 11425: unless ($ishome) { 11426: my $fetch = "$newdest{$i}/$title"; 11427: $fetch =~ s/^\Q$prefix$dir\E//; 11428: $prompttofetch{$fetch} = 1; 11429: } 11430: } 11431: $LONCAPA::map::resources[$newidx]= 11432: $docstitle.':'.$url.':false:normal:res'; 11433: push(@LONCAPA::map::order, $newidx); 11434: my ($outtext,$errtext)= 11435: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'. 11436: $docuname.'/'.$folders{$outer}. 11437: '.'.$containers{$outer},1,1); 11438: unless ($errtext) { 11439: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") { 11440: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n"; 11441: } 11442: } 11443: } 11444: } 11445: } 11446: } else { 11447: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 11448: } 11449: } 11450: for (my $i=1; $i<=$numitems; $i++) { 11451: next unless ($env{'form.archive_'.$i} eq 'dependency'); 11452: my $path = $env{'form.archive_content_'.$i}; 11453: if ($path =~ /^\Q$pathtocheck\E/) { 11454: my ($title) = ($path =~ m{/([^/]+)$}); 11455: $referrer{$i} = $env{'form.archive_dependent_on_'.$i}; 11456: if ($env{'form.archive_'.$referrer{$i}} eq 'display') { 11457: if (ref($dirorder{$i}) eq 'ARRAY') { 11458: my ($itemidx,$fullpath,$relpath); 11459: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') { 11460: my $container = $dirorder{$referrer{$i}}->[-1]; 11461: for (my $j=0; $j<@{$dirorder{$i}}; $j++) { 11462: if ($dirorder{$i}->[$j] eq $container) { 11463: $itemidx = $j; 11464: } 11465: } 11466: } 11467: if ($itemidx eq '') { 11468: $itemidx = 0; 11469: } 11470: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) { 11471: if ($mapinner{$referrer{$i}}) { 11472: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}"; 11473: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { 11474: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { 11475: unless (defined($newseqid{$dirorder{$i}->[$j]})) { 11476: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; 11477: $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; 11478: if (!-e $fullpath) { 11479: mkdir($fullpath,0755); 11480: } 11481: } 11482: } else { 11483: last; 11484: } 11485: } 11486: } 11487: } elsif ($newdest{$referrer{$i}}) { 11488: $fullpath = $newdest{$referrer{$i}}; 11489: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) { 11490: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') { 11491: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]}; 11492: last; 11493: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) { 11494: unless (defined($newseqid{$dirorder{$i}->[$j]})) { 11495: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]}; 11496: $relpath .= '/'.$titles{$dirorder{$i}->[$j]}; 11497: if (!-e $fullpath) { 11498: mkdir($fullpath,0755); 11499: } 11500: } 11501: } else { 11502: last; 11503: } 11504: } 11505: } 11506: if ($fullpath ne '') { 11507: if (-e "$prefix$path") { 11508: system("mv $prefix$path $fullpath/$title"); 11509: } 11510: if (-e "$fullpath/$title") { 11511: my $showpath; 11512: if ($relpath ne '') { 11513: $showpath = "$relpath/$title"; 11514: } else { 11515: $showpath = "/$title"; 11516: } 11517: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n"; 11518: } 11519: unless ($ishome) { 11520: my $fetch = "$fullpath/$title"; 11521: $fetch =~ s/^\Q$prefix$dir\E//; 11522: $prompttofetch{$fetch} = 1; 11523: } 11524: } 11525: } 11526: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') { 11527: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.', 11528: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />'; 11529: } 11530: } else { 11531: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 11532: } 11533: } 11534: if (keys(%todelete)) { 11535: foreach my $key (keys(%todelete)) { 11536: unlink($key); 11537: } 11538: } 11539: if (keys(%todeletedir)) { 11540: foreach my $key (keys(%todeletedir)) { 11541: rmdir($key); 11542: } 11543: } 11544: foreach my $dir (sort(keys(%is_dir))) { 11545: if (($pathtocheck ne '') && ($dir ne '')) { 11546: &cleanup_empty_dirs($prefix."$pathtocheck/$dir"); 11547: } 11548: } 11549: if ($result ne '') { 11550: $output .= '<ul>'."\n". 11551: $result."\n". 11552: '</ul>'; 11553: } 11554: unless ($ishome) { 11555: my $replicationfail; 11556: foreach my $item (keys(%prompttofetch)) { 11557: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome); 11558: unless ($fetchresult eq 'ok') { 11559: $replicationfail .= '<li>'.$item.'</li>'."\n"; 11560: } 11561: } 11562: if ($replicationfail) { 11563: $output .= '<p class="LC_error">'. 11564: &mt('Course home server failed to retrieve:').'<ul>'. 11565: $replicationfail. 11566: '</ul></p>'; 11567: } 11568: } 11569: } else { 11570: $warning = &mt('No items found in archive.'); 11571: } 11572: if ($error) { 11573: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'. 11574: $error.'</p>'."\n"; 11575: } 11576: if ($warning) { 11577: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n"; 11578: } 11579: return $output; 11580: } 11581: 11582: sub cleanup_empty_dirs { 11583: my ($path) = @_; 11584: if (($path ne '') && (-d $path)) { 11585: if (opendir(my $dirh,$path)) { 11586: my @dircontents = grep(!/^\./,readdir($dirh)); 11587: my $numitems = 0; 11588: foreach my $item (@dircontents) { 11589: if (-d "$path/$item") { 11590: &recurse_dirs("$path/$item"); 11591: if (-e "$path/$item") { 11592: $numitems ++; 11593: } 11594: } else { 11595: $numitems ++; 11596: } 11597: } 11598: if ($numitems == 0) { 11599: rmdir($path); 11600: } 11601: closedir($dirh); 11602: } 11603: } 11604: return; 11605: } 11606: 11607: =pod 11608: 11609: =item &get_folder_hierarchy() 11610: 11611: Provides hierarchy of names of folders/sub-folders containing the current 11612: item, 11613: 11614: Inputs: 3 11615: - $navmap - navmaps object 11616: 11617: - $map - url for map (either the trigger itself, or map containing 11618: the resource, which is the trigger). 11619: 11620: - $showitem - 1 => show title for map itself; 0 => do not show. 11621: 11622: Outputs: 1 @pathitems - array of folder/subfolder names. 11623: 11624: =cut 11625: 11626: sub get_folder_hierarchy { 11627: my ($navmap,$map,$showitem) = @_; 11628: my @pathitems; 11629: if (ref($navmap)) { 11630: my $mapres = $navmap->getResourceByUrl($map); 11631: if (ref($mapres)) { 11632: my $pcslist = $mapres->map_hierarchy(); 11633: if ($pcslist ne '') { 11634: my @pcs = split(/,/,$pcslist); 11635: foreach my $pc (@pcs) { 11636: if ($pc == 1) { 11637: push(@pathitems,&mt('Main Course Documents')); 11638: } else { 11639: my $res = $navmap->getByMapPc($pc); 11640: if (ref($res)) { 11641: my $title = $res->compTitle(); 11642: $title =~ s/\W+/_/g; 11643: if ($title ne '') { 11644: push(@pathitems,$title); 11645: } 11646: } 11647: } 11648: } 11649: } 11650: if ($showitem) { 11651: if ($mapres->{ID} eq '0.0') { 11652: push(@pathitems,&mt('Main Course Documents')); 11653: } else { 11654: my $maptitle = $mapres->compTitle(); 11655: $maptitle =~ s/\W+/_/g; 11656: if ($maptitle ne '') { 11657: push(@pathitems,$maptitle); 11658: } 11659: } 11660: } 11661: } 11662: } 11663: return @pathitems; 11664: } 11665: 11666: =pod 11667: 11668: =item * &get_turnedin_filepath() 11669: 11670: Determines path in a user's portfolio file for storage of files uploaded 11671: to a specific essayresponse or dropbox item. 11672: 11673: Inputs: 3 required + 1 optional. 11674: $symb is symb for resource, $uname and $udom are for current user (required). 11675: $caller is optional (can be "submission", if routine is called when storing 11676: an upoaded file when "Submit Answer" button was pressed). 11677: 11678: Returns array containing $path and $multiresp. 11679: $path is path in portfolio. $multiresp is 1 if this resource contains more 11680: than one file upload item. Callers of routine should append partid as a 11681: subdirectory to $path in cases where $multiresp is 1. 11682: 11683: Called by: homework/essayresponse.pm and homework/structuretags.pm 11684: 11685: =cut 11686: 11687: sub get_turnedin_filepath { 11688: my ($symb,$uname,$udom,$caller) = @_; 11689: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb); 11690: my $turnindir; 11691: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir'); 11692: $turnindir = $userhash{'turnindir'}; 11693: my ($path,$multiresp); 11694: if ($turnindir eq '') { 11695: if ($caller eq 'submission') { 11696: $turnindir = &mt('turned in'); 11697: $turnindir =~ s/\W+/_/g; 11698: my %newhash = ( 11699: 'turnindir' => $turnindir, 11700: ); 11701: &Apache::lonnet::put('environment',\%newhash,$udom,$uname); 11702: } 11703: } 11704: if ($turnindir ne '') { 11705: $path = '/'.$turnindir.'/'; 11706: my ($multipart,$turnin,@pathitems); 11707: my $navmap = Apache::lonnavmaps::navmap->new(); 11708: if (defined($navmap)) { 11709: my $mapres = $navmap->getResourceByUrl($map); 11710: if (ref($mapres)) { 11711: my $pcslist = $mapres->map_hierarchy(); 11712: if ($pcslist ne '') { 11713: foreach my $pc (split(/,/,$pcslist)) { 11714: my $res = $navmap->getByMapPc($pc); 11715: if (ref($res)) { 11716: my $title = $res->compTitle(); 11717: $title =~ s/\W+/_/g; 11718: if ($title ne '') { 11719: push(@pathitems,$title); 11720: } 11721: } 11722: } 11723: } 11724: my $maptitle = $mapres->compTitle(); 11725: $maptitle =~ s/\W+/_/g; 11726: if ($maptitle ne '') { 11727: push(@pathitems,$maptitle); 11728: } 11729: unless ($env{'request.state'} eq 'construct') { 11730: my $res = $navmap->getBySymb($symb); 11731: if (ref($res)) { 11732: my $partlist = $res->parts(); 11733: my $totaluploads = 0; 11734: if (ref($partlist) eq 'ARRAY') { 11735: foreach my $part (@{$partlist}) { 11736: my @types = $res->responseType($part); 11737: my @ids = $res->responseIds($part); 11738: for (my $i=0; $i < scalar(@ids); $i++) { 11739: if ($types[$i] eq 'essay') { 11740: my $partid = $part.'_'.$ids[$i]; 11741: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') { 11742: $totaluploads ++; 11743: } 11744: } 11745: } 11746: } 11747: if ($totaluploads > 1) { 11748: $multiresp = 1; 11749: } 11750: } 11751: } 11752: } 11753: } else { 11754: return; 11755: } 11756: } else { 11757: return; 11758: } 11759: my $restitle=&Apache::lonnet::gettitle($symb); 11760: $restitle =~ s/\W+/_/g; 11761: if ($restitle eq '') { 11762: $restitle = ($resurl =~ m{/[^/]+$}); 11763: if ($restitle eq '') { 11764: $restitle = time; 11765: } 11766: } 11767: push(@pathitems,$restitle); 11768: $path .= join('/',@pathitems); 11769: } 11770: return ($path,$multiresp); 11771: } 11772: 11773: =pod 11774: 11775: =back 11776: 11777: =head1 CSV Upload/Handling functions 11778: 11779: =over 4 11780: 11781: =item * &upfile_store($r) 11782: 11783: Store uploaded file, $r should be the HTTP Request object, 11784: needs $env{'form.upfile'} 11785: returns $datatoken to be put into hidden field 11786: 11787: =cut 11788: 11789: sub upfile_store { 11790: my $r=shift; 11791: $env{'form.upfile'}=~s/\r/\n/gs; 11792: $env{'form.upfile'}=~s/\f/\n/gs; 11793: $env{'form.upfile'}=~s/\n+/\n/gs; 11794: $env{'form.upfile'}=~s/\n+$//gs; 11795: 11796: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}. 11797: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$; 11798: { 11799: my $datafile = $r->dir_config('lonDaemons'). 11800: '/tmp/'.$datatoken.'.tmp'; 11801: if ( open(my $fh,">$datafile") ) { 11802: print $fh $env{'form.upfile'}; 11803: close($fh); 11804: } 11805: } 11806: return $datatoken; 11807: } 11808: 11809: =pod 11810: 11811: =item * &load_tmp_file($r) 11812: 11813: Load uploaded file from tmp, $r should be the HTTP Request object, 11814: needs $env{'form.datatoken'}, 11815: sets $env{'form.upfile'} to the contents of the file 11816: 11817: =cut 11818: 11819: sub load_tmp_file { 11820: my $r=shift; 11821: my @studentdata=(); 11822: { 11823: my $studentfile = $r->dir_config('lonDaemons'). 11824: '/tmp/'.$env{'form.datatoken'}.'.tmp'; 11825: if ( open(my $fh,"<$studentfile") ) { 11826: @studentdata=<$fh>; 11827: close($fh); 11828: } 11829: } 11830: $env{'form.upfile'}=join('',@studentdata); 11831: } 11832: 11833: =pod 11834: 11835: =item * &upfile_record_sep() 11836: 11837: Separate uploaded file into records 11838: returns array of records, 11839: needs $env{'form.upfile'} and $env{'form.upfiletype'} 11840: 11841: =cut 11842: 11843: sub upfile_record_sep { 11844: if ($env{'form.upfiletype'} eq 'xml') { 11845: } else { 11846: my @records; 11847: foreach my $line (split(/\n/,$env{'form.upfile'})) { 11848: if ($line=~/^\s*$/) { next; } 11849: push(@records,$line); 11850: } 11851: return @records; 11852: } 11853: } 11854: 11855: =pod 11856: 11857: =item * &record_sep($record) 11858: 11859: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'} 11860: 11861: =cut 11862: 11863: sub takeleft { 11864: my $index=shift; 11865: return substr('0000'.$index,-4,4); 11866: } 11867: 11868: sub record_sep { 11869: my $record=shift; 11870: my %components=(); 11871: if ($env{'form.upfiletype'} eq 'xml') { 11872: } elsif ($env{'form.upfiletype'} eq 'space') { 11873: my $i=0; 11874: foreach my $field (split(/\s+/,$record)) { 11875: $field=~s/^(\"|\')//; 11876: $field=~s/(\"|\')$//; 11877: $components{&takeleft($i)}=$field; 11878: $i++; 11879: } 11880: } elsif ($env{'form.upfiletype'} eq 'tab') { 11881: my $i=0; 11882: foreach my $field (split(/\t/,$record)) { 11883: $field=~s/^(\"|\')//; 11884: $field=~s/(\"|\')$//; 11885: $components{&takeleft($i)}=$field; 11886: $i++; 11887: } 11888: } else { 11889: my $separator=','; 11890: if ($env{'form.upfiletype'} eq 'semisv') { 11891: $separator=';'; 11892: } 11893: my $i=0; 11894: # the character we are looking for to indicate the end of a quote or a record 11895: my $looking_for=$separator; 11896: # do not add the characters to the fields 11897: my $ignore=0; 11898: # we just encountered a separator (or the beginning of the record) 11899: my $just_found_separator=1; 11900: # store the field we are working on here 11901: my $field=''; 11902: # work our way through all characters in record 11903: foreach my $character ($record=~/(.)/g) { 11904: if ($character eq $looking_for) { 11905: if ($character ne $separator) { 11906: # Found the end of a quote, again looking for separator 11907: $looking_for=$separator; 11908: $ignore=1; 11909: } else { 11910: # Found a separator, store away what we got 11911: $components{&takeleft($i)}=$field; 11912: $i++; 11913: $just_found_separator=1; 11914: $ignore=0; 11915: $field=''; 11916: } 11917: next; 11918: } 11919: # single or double quotation marks after a separator indicate beginning of a quote 11920: # we are now looking for the end of the quote and need to ignore separators 11921: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) { 11922: $looking_for=$character; 11923: next; 11924: } 11925: # ignore would be true after we reached the end of a quote 11926: if ($ignore) { next; } 11927: if (($just_found_separator) && ($character=~/\s/)) { next; } 11928: $field.=$character; 11929: $just_found_separator=0; 11930: } 11931: # catch the very last entry, since we never encountered the separator 11932: $components{&takeleft($i)}=$field; 11933: } 11934: return %components; 11935: } 11936: 11937: ###################################################### 11938: ###################################################### 11939: 11940: =pod 11941: 11942: =item * &upfile_select_html() 11943: 11944: Return HTML code to select a file from the users machine and specify 11945: the file type. 11946: 11947: =cut 11948: 11949: ###################################################### 11950: ###################################################### 11951: sub upfile_select_html { 11952: my %Types = ( 11953: csv => &mt('CSV (comma separated values, spreadsheet)'), 11954: semisv => &mt('Semicolon separated values'), 11955: space => &mt('Space separated'), 11956: tab => &mt('Tabulator separated'), 11957: # xml => &mt('HTML/XML'), 11958: ); 11959: my $Str = '<input type="file" name="upfile" size="50" />'. 11960: '<br />'.&mt('Type').': <select name="upfiletype">'; 11961: foreach my $type (sort(keys(%Types))) { 11962: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n"; 11963: } 11964: $Str .= "</select>\n"; 11965: return $Str; 11966: } 11967: 11968: sub get_samples { 11969: my ($records,$toget) = @_; 11970: my @samples=({}); 11971: my $got=0; 11972: foreach my $rec (@$records) { 11973: my %temp = &record_sep($rec); 11974: if (! grep(/\S/, values(%temp))) { next; } 11975: if (%temp) { 11976: $samples[$got]=\%temp; 11977: $got++; 11978: if ($got == $toget) { last; } 11979: } 11980: } 11981: return \@samples; 11982: } 11983: 11984: ###################################################### 11985: ###################################################### 11986: 11987: =pod 11988: 11989: =item * &csv_print_samples($r,$records) 11990: 11991: Prints a table of sample values from each column uploaded $r is an 11992: Apache Request ref, $records is an arrayref from 11993: &Apache::loncommon::upfile_record_sep 11994: 11995: =cut 11996: 11997: ###################################################### 11998: ###################################################### 11999: sub csv_print_samples { 12000: my ($r,$records) = @_; 12001: my $samples = &get_samples($records,5); 12002: 12003: $r->print(&mt('Samples').'<br />'.&start_data_table(). 12004: &start_data_table_header_row()); 12005: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12006: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); } 12007: $r->print(&end_data_table_header_row()); 12008: foreach my $hash (@$samples) { 12009: $r->print(&start_data_table_row()); 12010: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12011: $r->print('<td>'); 12012: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); } 12013: $r->print('</td>'); 12014: } 12015: $r->print(&end_data_table_row()); 12016: } 12017: $r->print(&end_data_table().'<br />'."\n"); 12018: } 12019: 12020: ###################################################### 12021: ###################################################### 12022: 12023: =pod 12024: 12025: =item * &csv_print_select_table($r,$records,$d) 12026: 12027: Prints a table to create associations between values and table columns. 12028: 12029: $r is an Apache Request ref, 12030: $records is an arrayref from &Apache::loncommon::upfile_record_sep, 12031: $d is an array of 2 element arrays (internal name, displayed name,defaultcol) 12032: 12033: =cut 12034: 12035: ###################################################### 12036: ###################################################### 12037: sub csv_print_select_table { 12038: my ($r,$records,$d) = @_; 12039: my $i=0; 12040: my $samples = &get_samples($records,1); 12041: $r->print(&mt('Associate columns with student attributes.')."\n". 12042: &start_data_table().&start_data_table_header_row(). 12043: '<th>'.&mt('Attribute').'</th>'. 12044: '<th>'.&mt('Column').'</th>'. 12045: &end_data_table_header_row()."\n"); 12046: foreach my $array_ref (@$d) { 12047: my ($value,$display,$defaultcol)=@{ $array_ref }; 12048: $r->print(&start_data_table_row().'<td>'.$display.'</td>'); 12049: 12050: $r->print('<td><select name="f'.$i.'"'. 12051: ' onchange="javascript:flip(this.form,'.$i.');">'); 12052: $r->print('<option value="none"></option>'); 12053: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 12054: $r->print('<option value="'.$sample.'"'. 12055: ($sample eq $defaultcol ? ' selected="selected" ' : ''). 12056: '>'.&mt('Column [_1]',($sample+1)).'</option>'); 12057: } 12058: $r->print('</select></td>'.&end_data_table_row()."\n"); 12059: $i++; 12060: } 12061: $r->print(&end_data_table()); 12062: $i--; 12063: return $i; 12064: } 12065: 12066: ###################################################### 12067: ###################################################### 12068: 12069: =pod 12070: 12071: =item * &csv_samples_select_table($r,$records,$d) 12072: 12073: Prints a table of sample values from the upload and can make associate samples to internal names. 12074: 12075: $r is an Apache Request ref, 12076: $records is an arrayref from &Apache::loncommon::upfile_record_sep, 12077: $d is an array of 2 element arrays (internal name, displayed name) 12078: 12079: =cut 12080: 12081: ###################################################### 12082: ###################################################### 12083: sub csv_samples_select_table { 12084: my ($r,$records,$d) = @_; 12085: my $i=0; 12086: # 12087: my $max_samples = 5; 12088: my $samples = &get_samples($records,$max_samples); 12089: $r->print(&start_data_table(). 12090: &start_data_table_header_row().'<th>'. 12091: &mt('Field').'</th><th>'.&mt('Samples').'</th>'. 12092: &end_data_table_header_row()); 12093: 12094: foreach my $key (sort(keys(%{ $samples->[0] }))) { 12095: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'. 12096: ' onchange="javascript:flip(this.form,'.$i.');">'); 12097: foreach my $option (@$d) { 12098: my ($value,$display,$defaultcol)=@{ $option }; 12099: $r->print('<option value="'.$value.'"'. 12100: ($i eq $defaultcol ? ' selected="selected" ':'').'>'. 12101: $display.'</option>'); 12102: } 12103: $r->print('</select></td><td>'); 12104: foreach my $line (0..($max_samples-1)) { 12105: if (defined($samples->[$line]{$key})) { 12106: $r->print($samples->[$line]{$key}."<br />\n"); 12107: } 12108: } 12109: $r->print('</td>'.&end_data_table_row()); 12110: $i++; 12111: } 12112: $r->print(&end_data_table()); 12113: $i--; 12114: return($i); 12115: } 12116: 12117: ###################################################### 12118: ###################################################### 12119: 12120: =pod 12121: 12122: =item * &clean_excel_name($name) 12123: 12124: Returns a replacement for $name which does not contain any illegal characters. 12125: 12126: =cut 12127: 12128: ###################################################### 12129: ###################################################### 12130: sub clean_excel_name { 12131: my ($name) = @_; 12132: $name =~ s/[:\*\?\/\\]//g; 12133: if (length($name) > 31) { 12134: $name = substr($name,0,31); 12135: } 12136: return $name; 12137: } 12138: 12139: =pod 12140: 12141: =item * &check_if_partid_hidden($id,$symb,$udom,$uname) 12142: 12143: Returns either 1 or undef 12144: 12145: 1 if the part is to be hidden, undef if it is to be shown 12146: 12147: Arguments are: 12148: 12149: $id the id of the part to be checked 12150: $symb, optional the symb of the resource to check 12151: $udom, optional the domain of the user to check for 12152: $uname, optional the username of the user to check for 12153: 12154: =cut 12155: 12156: sub check_if_partid_hidden { 12157: my ($id,$symb,$udom,$uname) = @_; 12158: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts', 12159: $symb,$udom,$uname); 12160: my $truth=1; 12161: #if the string starts with !, then the list is the list to show not hide 12162: if ($hiddenparts=~s/^\s*!//) { $truth=undef; } 12163: my @hiddenlist=split(/,/,$hiddenparts); 12164: foreach my $checkid (@hiddenlist) { 12165: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; } 12166: } 12167: return !$truth; 12168: } 12169: 12170: 12171: ############################################################ 12172: ############################################################ 12173: 12174: =pod 12175: 12176: =back 12177: 12178: =head1 cgi-bin script and graphing routines 12179: 12180: =over 4 12181: 12182: =item * &get_cgi_id() 12183: 12184: Inputs: none 12185: 12186: Returns an id which can be used to pass environment variables 12187: to various cgi-bin scripts. These environment variables will 12188: be removed from the users environment after a given time by 12189: the routine &Apache::lonnet::transfer_profile_to_env. 12190: 12191: =cut 12192: 12193: ############################################################ 12194: ############################################################ 12195: my $uniq=0; 12196: sub get_cgi_id { 12197: $uniq=($uniq+1)%100000; 12198: return (time.'_'.$$.'_'.$uniq); 12199: } 12200: 12201: ############################################################ 12202: ############################################################ 12203: 12204: =pod 12205: 12206: =item * &DrawBarGraph() 12207: 12208: Facilitates the plotting of data in a (stacked) bar graph. 12209: Puts plot definition data into the users environment in order for 12210: graph.png to plot it. Returns an <img> tag for the plot. 12211: The bars on the plot are labeled '1','2',...,'n'. 12212: 12213: Inputs: 12214: 12215: =over 4 12216: 12217: =item $Title: string, the title of the plot 12218: 12219: =item $xlabel: string, text describing the X-axis of the plot 12220: 12221: =item $ylabel: string, text describing the Y-axis of the plot 12222: 12223: =item $Max: scalar, the maximum Y value to use in the plot 12224: If $Max is < any data point, the graph will not be rendered. 12225: 12226: =item $colors: array ref holding the colors to be used for the data sets when 12227: they are plotted. If undefined, default values will be used. 12228: 12229: =item $labels: array ref holding the labels to use on the x-axis for the bars. 12230: 12231: =item @Values: An array of array references. Each array reference holds data 12232: to be plotted in a stacked bar chart. 12233: 12234: =item If the final element of @Values is a hash reference the key/value 12235: pairs will be added to the graph definition. 12236: 12237: =back 12238: 12239: Returns: 12240: 12241: An <img> tag which references graph.png and the appropriate identifying 12242: information for the plot. 12243: 12244: =cut 12245: 12246: ############################################################ 12247: ############################################################ 12248: sub DrawBarGraph { 12249: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_; 12250: # 12251: if (! defined($colors)) { 12252: $colors = ['#33ff00', 12253: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933', 12254: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66', 12255: ]; 12256: } 12257: my $extra_settings = {}; 12258: if (ref($Values[-1]) eq 'HASH') { 12259: $extra_settings = pop(@Values); 12260: } 12261: # 12262: my $identifier = &get_cgi_id(); 12263: my $id = 'cgi.'.$identifier; 12264: if (! @Values || ref($Values[0]) ne 'ARRAY') { 12265: return ''; 12266: } 12267: # 12268: my @Labels; 12269: if (defined($labels)) { 12270: @Labels = @$labels; 12271: } else { 12272: for (my $i=0;$i<@{$Values[0]};$i++) { 12273: push (@Labels,$i+1); 12274: } 12275: } 12276: # 12277: my $NumBars = scalar(@{$Values[0]}); 12278: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); } 12279: my %ValuesHash; 12280: my $NumSets=1; 12281: foreach my $array (@Values) { 12282: next if (! ref($array)); 12283: $ValuesHash{$id.'.data.'.$NumSets++} = 12284: join(',',@$array); 12285: } 12286: # 12287: my ($height,$width,$xskip,$bar_width) = (200,120,1,15); 12288: if ($NumBars < 3) { 12289: $width = 120+$NumBars*32; 12290: $xskip = 1; 12291: $bar_width = 30; 12292: } elsif ($NumBars < 5) { 12293: $width = 120+$NumBars*20; 12294: $xskip = 1; 12295: $bar_width = 20; 12296: } elsif ($NumBars < 10) { 12297: $width = 120+$NumBars*15; 12298: $xskip = 1; 12299: $bar_width = 15; 12300: } elsif ($NumBars <= 25) { 12301: $width = 120+$NumBars*11; 12302: $xskip = 5; 12303: $bar_width = 8; 12304: } elsif ($NumBars <= 50) { 12305: $width = 120+$NumBars*8; 12306: $xskip = 5; 12307: $bar_width = 4; 12308: } else { 12309: $width = 120+$NumBars*8; 12310: $xskip = 5; 12311: $bar_width = 4; 12312: } 12313: # 12314: $Max = 1 if ($Max < 1); 12315: if ( int($Max) < $Max ) { 12316: $Max++; 12317: $Max = int($Max); 12318: } 12319: $Title = '' if (! defined($Title)); 12320: $xlabel = '' if (! defined($xlabel)); 12321: $ylabel = '' if (! defined($ylabel)); 12322: $ValuesHash{$id.'.title'} = &escape($Title); 12323: $ValuesHash{$id.'.xlabel'} = &escape($xlabel); 12324: $ValuesHash{$id.'.ylabel'} = &escape($ylabel); 12325: $ValuesHash{$id.'.y_max_value'} = $Max; 12326: $ValuesHash{$id.'.NumBars'} = $NumBars; 12327: $ValuesHash{$id.'.NumSets'} = $NumSets; 12328: $ValuesHash{$id.'.PlotType'} = 'bar'; 12329: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 12330: $ValuesHash{$id.'.height'} = $height; 12331: $ValuesHash{$id.'.width'} = $width; 12332: $ValuesHash{$id.'.xskip'} = $xskip; 12333: $ValuesHash{$id.'.bar_width'} = $bar_width; 12334: $ValuesHash{$id.'.labels'} = join(',',@Labels); 12335: # 12336: # Deal with other parameters 12337: while (my ($key,$value) = each(%$extra_settings)) { 12338: $ValuesHash{$id.'.'.$key} = $value; 12339: } 12340: # 12341: &Apache::lonnet::appenv(\%ValuesHash); 12342: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 12343: } 12344: 12345: ############################################################ 12346: ############################################################ 12347: 12348: =pod 12349: 12350: =item * &DrawXYGraph() 12351: 12352: Facilitates the plotting of data in an XY graph. 12353: Puts plot definition data into the users environment in order for 12354: graph.png to plot it. Returns an <img> tag for the plot. 12355: 12356: Inputs: 12357: 12358: =over 4 12359: 12360: =item $Title: string, the title of the plot 12361: 12362: =item $xlabel: string, text describing the X-axis of the plot 12363: 12364: =item $ylabel: string, text describing the Y-axis of the plot 12365: 12366: =item $Max: scalar, the maximum Y value to use in the plot 12367: If $Max is < any data point, the graph will not be rendered. 12368: 12369: =item $colors: Array ref containing the hex color codes for the data to be 12370: plotted in. If undefined, default values will be used. 12371: 12372: =item $Xlabels: Array ref containing the labels to be used for the X-axis. 12373: 12374: =item $Ydata: Array ref containing Array refs. 12375: Each of the contained arrays will be plotted as a separate curve. 12376: 12377: =item %Values: hash indicating or overriding any default values which are 12378: passed to graph.png. 12379: Possible values are: width, xskip, x_ticks, x_tick_offset, among others. 12380: 12381: =back 12382: 12383: Returns: 12384: 12385: An <img> tag which references graph.png and the appropriate identifying 12386: information for the plot. 12387: 12388: =cut 12389: 12390: ############################################################ 12391: ############################################################ 12392: sub DrawXYGraph { 12393: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_; 12394: # 12395: # Create the identifier for the graph 12396: my $identifier = &get_cgi_id(); 12397: my $id = 'cgi.'.$identifier; 12398: # 12399: $Title = '' if (! defined($Title)); 12400: $xlabel = '' if (! defined($xlabel)); 12401: $ylabel = '' if (! defined($ylabel)); 12402: my %ValuesHash = 12403: ( 12404: $id.'.title' => &escape($Title), 12405: $id.'.xlabel' => &escape($xlabel), 12406: $id.'.ylabel' => &escape($ylabel), 12407: $id.'.y_max_value'=> $Max, 12408: $id.'.labels' => join(',',@$Xlabels), 12409: $id.'.PlotType' => 'XY', 12410: ); 12411: # 12412: if (defined($colors) && ref($colors) eq 'ARRAY') { 12413: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 12414: } 12415: # 12416: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') { 12417: return ''; 12418: } 12419: my $NumSets=1; 12420: foreach my $array (@{$Ydata}){ 12421: next if (! ref($array)); 12422: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array); 12423: } 12424: $ValuesHash{$id.'.NumSets'} = $NumSets-1; 12425: # 12426: # Deal with other parameters 12427: while (my ($key,$value) = each(%Values)) { 12428: $ValuesHash{$id.'.'.$key} = $value; 12429: } 12430: # 12431: &Apache::lonnet::appenv(\%ValuesHash); 12432: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 12433: } 12434: 12435: ############################################################ 12436: ############################################################ 12437: 12438: =pod 12439: 12440: =item * &DrawXYYGraph() 12441: 12442: Facilitates the plotting of data in an XY graph with two Y axes. 12443: Puts plot definition data into the users environment in order for 12444: graph.png to plot it. Returns an <img> tag for the plot. 12445: 12446: Inputs: 12447: 12448: =over 4 12449: 12450: =item $Title: string, the title of the plot 12451: 12452: =item $xlabel: string, text describing the X-axis of the plot 12453: 12454: =item $ylabel: string, text describing the Y-axis of the plot 12455: 12456: =item $colors: Array ref containing the hex color codes for the data to be 12457: plotted in. If undefined, default values will be used. 12458: 12459: =item $Xlabels: Array ref containing the labels to be used for the X-axis. 12460: 12461: =item $Ydata1: The first data set 12462: 12463: =item $Min1: The minimum value of the left Y-axis 12464: 12465: =item $Max1: The maximum value of the left Y-axis 12466: 12467: =item $Ydata2: The second data set 12468: 12469: =item $Min2: The minimum value of the right Y-axis 12470: 12471: =item $Max2: The maximum value of the left Y-axis 12472: 12473: =item %Values: hash indicating or overriding any default values which are 12474: passed to graph.png. 12475: Possible values are: width, xskip, x_ticks, x_tick_offset, among others. 12476: 12477: =back 12478: 12479: Returns: 12480: 12481: An <img> tag which references graph.png and the appropriate identifying 12482: information for the plot. 12483: 12484: =cut 12485: 12486: ############################################################ 12487: ############################################################ 12488: sub DrawXYYGraph { 12489: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1, 12490: $Ydata2,$Min2,$Max2,%Values)=@_; 12491: # 12492: # Create the identifier for the graph 12493: my $identifier = &get_cgi_id(); 12494: my $id = 'cgi.'.$identifier; 12495: # 12496: $Title = '' if (! defined($Title)); 12497: $xlabel = '' if (! defined($xlabel)); 12498: $ylabel = '' if (! defined($ylabel)); 12499: my %ValuesHash = 12500: ( 12501: $id.'.title' => &escape($Title), 12502: $id.'.xlabel' => &escape($xlabel), 12503: $id.'.ylabel' => &escape($ylabel), 12504: $id.'.labels' => join(',',@$Xlabels), 12505: $id.'.PlotType' => 'XY', 12506: $id.'.NumSets' => 2, 12507: $id.'.two_axes' => 1, 12508: $id.'.y1_max_value' => $Max1, 12509: $id.'.y1_min_value' => $Min1, 12510: $id.'.y2_max_value' => $Max2, 12511: $id.'.y2_min_value' => $Min2, 12512: ); 12513: # 12514: if (defined($colors) && ref($colors) eq 'ARRAY') { 12515: $ValuesHash{$id.'.Colors'} = join(',',@{$colors}); 12516: } 12517: # 12518: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' || 12519: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){ 12520: return ''; 12521: } 12522: my $NumSets=1; 12523: foreach my $array ($Ydata1,$Ydata2){ 12524: next if (! ref($array)); 12525: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array); 12526: } 12527: # 12528: # Deal with other parameters 12529: while (my ($key,$value) = each(%Values)) { 12530: $ValuesHash{$id.'.'.$key} = $value; 12531: } 12532: # 12533: &Apache::lonnet::appenv(\%ValuesHash); 12534: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />'; 12535: } 12536: 12537: ############################################################ 12538: ############################################################ 12539: 12540: =pod 12541: 12542: =back 12543: 12544: =head1 Statistics helper routines? 12545: 12546: Bad place for them but what the hell. 12547: 12548: =over 4 12549: 12550: =item * &chartlink() 12551: 12552: Returns a link to the chart for a specific student. 12553: 12554: Inputs: 12555: 12556: =over 4 12557: 12558: =item $linktext: The text of the link 12559: 12560: =item $sname: The students username 12561: 12562: =item $sdomain: The students domain 12563: 12564: =back 12565: 12566: =back 12567: 12568: =cut 12569: 12570: ############################################################ 12571: ############################################################ 12572: sub chartlink { 12573: my ($linktext, $sname, $sdomain) = @_; 12574: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'. 12575: '&SelectedStudent='.&escape($sname.':'.$sdomain). 12576: '&chartoutputmode='.HTML::Entities::encode('html, with all links'). 12577: '">'.$linktext.'</a>'; 12578: } 12579: 12580: ####################################################### 12581: ####################################################### 12582: 12583: =pod 12584: 12585: =head1 Course Environment Routines 12586: 12587: =over 4 12588: 12589: =item * &restore_course_settings() 12590: 12591: =item * &store_course_settings() 12592: 12593: Restores/Store indicated form parameters from the course environment. 12594: Will not overwrite existing values of the form parameters. 12595: 12596: Inputs: 12597: a scalar describing the data (e.g. 'chart', 'problem_analysis') 12598: 12599: a hash ref describing the data to be stored. For example: 12600: 12601: %Save_Parameters = ('Status' => 'scalar', 12602: 'chartoutputmode' => 'scalar', 12603: 'chartoutputdata' => 'scalar', 12604: 'Section' => 'array', 12605: 'Group' => 'array', 12606: 'StudentData' => 'array', 12607: 'Maps' => 'array'); 12608: 12609: Returns: both routines return nothing 12610: 12611: =back 12612: 12613: =cut 12614: 12615: ####################################################### 12616: ####################################################### 12617: sub store_course_settings { 12618: return &store_settings($env{'request.course.id'},@_); 12619: } 12620: 12621: sub store_settings { 12622: # save to the environment 12623: # appenv the same items, just to be safe 12624: my $udom = $env{'user.domain'}; 12625: my $uname = $env{'user.name'}; 12626: my ($context,$prefix,$Settings) = @_; 12627: my %SaveHash; 12628: my %AppHash; 12629: while (my ($setting,$type) = each(%$Settings)) { 12630: my $basename = join('.','internal',$context,$prefix,$setting); 12631: my $envname = 'environment.'.$basename; 12632: if (exists($env{'form.'.$setting})) { 12633: # Save this value away 12634: if ($type eq 'scalar' && 12635: (! exists($env{$envname}) || 12636: $env{$envname} ne $env{'form.'.$setting})) { 12637: $SaveHash{$basename} = $env{'form.'.$setting}; 12638: $AppHash{$envname} = $env{'form.'.$setting}; 12639: } elsif ($type eq 'array') { 12640: my $stored_form; 12641: if (ref($env{'form.'.$setting})) { 12642: $stored_form = join(',', 12643: map { 12644: &escape($_); 12645: } sort(@{$env{'form.'.$setting}})); 12646: } else { 12647: $stored_form = 12648: &escape($env{'form.'.$setting}); 12649: } 12650: # Determine if the array contents are the same. 12651: if ($stored_form ne $env{$envname}) { 12652: $SaveHash{$basename} = $stored_form; 12653: $AppHash{$envname} = $stored_form; 12654: } 12655: } 12656: } 12657: } 12658: my $put_result = &Apache::lonnet::put('environment',\%SaveHash, 12659: $udom,$uname); 12660: if ($put_result !~ /^(ok|delayed)/) { 12661: &Apache::lonnet::logthis('unable to save form parameters, '. 12662: 'got error:'.$put_result); 12663: } 12664: # Make sure these settings stick around in this session, too 12665: &Apache::lonnet::appenv(\%AppHash); 12666: return; 12667: } 12668: 12669: sub restore_course_settings { 12670: return &restore_settings($env{'request.course.id'},@_); 12671: } 12672: 12673: sub restore_settings { 12674: my ($context,$prefix,$Settings) = @_; 12675: while (my ($setting,$type) = each(%$Settings)) { 12676: next if (exists($env{'form.'.$setting})); 12677: my $envname = 'environment.internal.'.$context.'.'.$prefix. 12678: '.'.$setting; 12679: if (exists($env{$envname})) { 12680: if ($type eq 'scalar') { 12681: $env{'form.'.$setting} = $env{$envname}; 12682: } elsif ($type eq 'array') { 12683: $env{'form.'.$setting} = [ 12684: map { 12685: &unescape($_); 12686: } split(',',$env{$envname}) 12687: ]; 12688: } 12689: } 12690: } 12691: } 12692: 12693: ####################################################### 12694: ####################################################### 12695: 12696: =pod 12697: 12698: =head1 Domain E-mail Routines 12699: 12700: =over 4 12701: 12702: =item * &build_recipient_list() 12703: 12704: Build recipient lists for five types of e-mail: 12705: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors 12706: (d) Help requests, (e) Course requests needing approval, generated by 12707: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and 12708: loncoursequeueadmin.pm respectively. 12709: 12710: Inputs: 12711: defmail (scalar - email address of default recipient), 12712: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 12713: defdom (domain for which to retrieve configuration settings), 12714: origmail (scalar - email address of recipient from loncapa.conf, 12715: i.e., predates configuration by DC via domainprefs.pm 12716: 12717: Returns: comma separated list of addresses to which to send e-mail. 12718: 12719: =back 12720: 12721: =cut 12722: 12723: ############################################################ 12724: ############################################################ 12725: sub build_recipient_list { 12726: my ($defmail,$mailing,$defdom,$origmail) = @_; 12727: my @recipients; 12728: my $otheremails; 12729: my %domconfig = 12730: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom); 12731: if (ref($domconfig{'contacts'}) eq 'HASH') { 12732: if (exists($domconfig{'contacts'}{$mailing})) { 12733: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') { 12734: my @contacts = ('adminemail','supportemail'); 12735: foreach my $item (@contacts) { 12736: if ($domconfig{'contacts'}{$mailing}{$item}) { 12737: my $addr = $domconfig{'contacts'}{$item}; 12738: if (!grep(/^\Q$addr\E$/,@recipients)) { 12739: push(@recipients,$addr); 12740: } 12741: } 12742: $otheremails = $domconfig{'contacts'}{$mailing}{'others'}; 12743: } 12744: } 12745: } elsif ($origmail ne '') { 12746: push(@recipients,$origmail); 12747: } 12748: } elsif ($origmail ne '') { 12749: push(@recipients,$origmail); 12750: } 12751: if (defined($defmail)) { 12752: if ($defmail ne '') { 12753: push(@recipients,$defmail); 12754: } 12755: } 12756: if ($otheremails) { 12757: my @others; 12758: if ($otheremails =~ /,/) { 12759: @others = split(/,/,$otheremails); 12760: } else { 12761: push(@others,$otheremails); 12762: } 12763: foreach my $addr (@others) { 12764: if (!grep(/^\Q$addr\E$/,@recipients)) { 12765: push(@recipients,$addr); 12766: } 12767: } 12768: } 12769: my $recipientlist = join(',',@recipients); 12770: return $recipientlist; 12771: } 12772: 12773: ############################################################ 12774: ############################################################ 12775: 12776: =pod 12777: 12778: =head1 Course Catalog Routines 12779: 12780: =over 4 12781: 12782: =item * &gather_categories() 12783: 12784: Converts category definitions - keys of categories hash stored in 12785: coursecategories in configuration.db on the primary library server in a 12786: domain - to an array. Also generates javascript and idx hash used to 12787: generate Domain Coordinator interface for editing Course Categories. 12788: 12789: Inputs: 12790: 12791: categories (reference to hash of category definitions). 12792: 12793: cats (reference to array of arrays/hashes which encapsulates hierarchy of 12794: categories and subcategories). 12795: 12796: idx (reference to hash of counters used in Domain Coordinator interface for 12797: editing Course Categories). 12798: 12799: jsarray (reference to array of categories used to create Javascript arrays for 12800: Domain Coordinator interface for editing Course Categories). 12801: 12802: Returns: nothing 12803: 12804: Side effects: populates cats, idx and jsarray. 12805: 12806: =cut 12807: 12808: sub gather_categories { 12809: my ($categories,$cats,$idx,$jsarray) = @_; 12810: my %counters; 12811: my $num = 0; 12812: foreach my $item (keys(%{$categories})) { 12813: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item); 12814: if ($container eq '' && $depth == 0) { 12815: $cats->[$depth][$categories->{$item}] = $cat; 12816: } else { 12817: $cats->[$depth]{$container}[$categories->{$item}] = $cat; 12818: } 12819: my ($escitem,$tail) = split(/:/,$item,2); 12820: if ($counters{$tail} eq '') { 12821: $counters{$tail} = $num; 12822: $num ++; 12823: } 12824: if (ref($idx) eq 'HASH') { 12825: $idx->{$item} = $counters{$tail}; 12826: } 12827: if (ref($jsarray) eq 'ARRAY') { 12828: push(@{$jsarray->[$counters{$tail}]},$item); 12829: } 12830: } 12831: return; 12832: } 12833: 12834: =pod 12835: 12836: =item * &extract_categories() 12837: 12838: Used to generate breadcrumb trails for course categories. 12839: 12840: Inputs: 12841: 12842: categories (reference to hash of category definitions). 12843: 12844: cats (reference to array of arrays/hashes which encapsulates hierarchy of 12845: categories and subcategories). 12846: 12847: trails (reference to array of breacrumb trails for each category). 12848: 12849: allitems (reference to hash - key is category key 12850: (format: escaped(name):escaped(parent category):depth in hierarchy). 12851: 12852: idx (reference to hash of counters used in Domain Coordinator interface for 12853: editing Course Categories). 12854: 12855: jsarray (reference to array of categories used to create Javascript arrays for 12856: Domain Coordinator interface for editing Course Categories). 12857: 12858: subcats (reference to hash of arrays containing all subcategories within each 12859: category, -recursive) 12860: 12861: Returns: nothing 12862: 12863: Side effects: populates trails and allitems hash references. 12864: 12865: =cut 12866: 12867: sub extract_categories { 12868: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_; 12869: if (ref($categories) eq 'HASH') { 12870: &gather_categories($categories,$cats,$idx,$jsarray); 12871: if (ref($cats->[0]) eq 'ARRAY') { 12872: for (my $i=0; $i<@{$cats->[0]}; $i++) { 12873: my $name = $cats->[0][$i]; 12874: my $item = &escape($name).'::0'; 12875: my $trailstr; 12876: if ($name eq 'instcode') { 12877: $trailstr = &mt('Official courses (with institutional codes)'); 12878: } elsif ($name eq 'communities') { 12879: $trailstr = &mt('Communities'); 12880: } else { 12881: $trailstr = $name; 12882: } 12883: if ($allitems->{$item} eq '') { 12884: push(@{$trails},$trailstr); 12885: $allitems->{$item} = scalar(@{$trails})-1; 12886: } 12887: my @parents = ($name); 12888: if (ref($cats->[1]{$name}) eq 'ARRAY') { 12889: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) { 12890: my $category = $cats->[1]{$name}[$j]; 12891: if (ref($subcats) eq 'HASH') { 12892: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1'); 12893: } 12894: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats); 12895: } 12896: } else { 12897: if (ref($subcats) eq 'HASH') { 12898: $subcats->{$item} = []; 12899: } 12900: } 12901: } 12902: } 12903: } 12904: return; 12905: } 12906: 12907: =pod 12908: 12909: =item *&recurse_categories() 12910: 12911: Recursively used to generate breadcrumb trails for course categories. 12912: 12913: Inputs: 12914: 12915: cats (reference to array of arrays/hashes which encapsulates hierarchy of 12916: categories and subcategories). 12917: 12918: depth (current depth in hierarchy of categories and sub-categories - 0 indexed). 12919: 12920: category (current course category, for which breadcrumb trail is being generated). 12921: 12922: trails (reference to array of breadcrumb trails for each category). 12923: 12924: allitems (reference to hash - key is category key 12925: (format: escaped(name):escaped(parent category):depth in hierarchy). 12926: 12927: parents (array containing containers directories for current category, 12928: back to top level). 12929: 12930: Returns: nothing 12931: 12932: Side effects: populates trails and allitems hash references 12933: 12934: =cut 12935: 12936: sub recurse_categories { 12937: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_; 12938: my $shallower = $depth - 1; 12939: if (ref($cats->[$depth]{$category}) eq 'ARRAY') { 12940: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) { 12941: my $name = $cats->[$depth]{$category}[$k]; 12942: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower; 12943: my $trailstr = join(' -> ',(@{$parents},$category)); 12944: if ($allitems->{$item} eq '') { 12945: push(@{$trails},$trailstr); 12946: $allitems->{$item} = scalar(@{$trails})-1; 12947: } 12948: my $deeper = $depth+1; 12949: push(@{$parents},$category); 12950: if (ref($subcats) eq 'HASH') { 12951: my $subcat = &escape($name).':'.$category.':'.$depth; 12952: for (my $j=@{$parents}; $j>=0; $j--) { 12953: my $higher; 12954: if ($j > 0) { 12955: $higher = &escape($parents->[$j]).':'. 12956: &escape($parents->[$j-1]).':'.$j; 12957: } else { 12958: $higher = &escape($parents->[$j]).'::'.$j; 12959: } 12960: push(@{$subcats->{$higher}},$subcat); 12961: } 12962: } 12963: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents, 12964: $subcats); 12965: pop(@{$parents}); 12966: } 12967: } else { 12968: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower; 12969: my $trailstr = join(' -> ',(@{$parents},$category)); 12970: if ($allitems->{$item} eq '') { 12971: push(@{$trails},$trailstr); 12972: $allitems->{$item} = scalar(@{$trails})-1; 12973: } 12974: } 12975: return; 12976: } 12977: 12978: =pod 12979: 12980: =item *&assign_categories_table() 12981: 12982: Create a datatable for display of hierarchical categories in a domain, 12983: with checkboxes to allow a course to be categorized. 12984: 12985: Inputs: 12986: 12987: cathash - reference to hash of categories defined for the domain (from 12988: configuration.db) 12989: 12990: currcat - scalar with an & separated list of categories assigned to a course. 12991: 12992: type - scalar contains course type (Course or Community). 12993: 12994: Returns: $output (markup to be displayed) 12995: 12996: =cut 12997: 12998: sub assign_categories_table { 12999: my ($cathash,$currcat,$type) = @_; 13000: my $output; 13001: if (ref($cathash) eq 'HASH') { 13002: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth); 13003: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray); 13004: $maxdepth = scalar(@cats); 13005: if (@cats > 0) { 13006: my $itemcount = 0; 13007: if (ref($cats[0]) eq 'ARRAY') { 13008: my @currcategories; 13009: if ($currcat ne '') { 13010: @currcategories = split('&',$currcat); 13011: } 13012: my $table; 13013: for (my $i=0; $i<@{$cats[0]}; $i++) { 13014: my $parent = $cats[0][$i]; 13015: next if ($parent eq 'instcode'); 13016: if ($type eq 'Community') { 13017: next unless ($parent eq 'communities'); 13018: } else { 13019: next if ($parent eq 'communities'); 13020: } 13021: my $css_class = $itemcount%2?' class="LC_odd_row"':''; 13022: my $item = &escape($parent).'::0'; 13023: my $checked = ''; 13024: if (@currcategories > 0) { 13025: if (grep(/^\Q$item\E$/,@currcategories)) { 13026: $checked = ' checked="checked"'; 13027: } 13028: } 13029: my $parent_title = $parent; 13030: if ($parent eq 'communities') { 13031: $parent_title = &mt('Communities'); 13032: } 13033: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'. 13034: '<input type="checkbox" name="usecategory" value="'. 13035: $item.'"'.$checked.' />'.$parent_title.'</span>'. 13036: '<input type="hidden" name="catname" value="'.$parent.'" /></td>'; 13037: my $depth = 1; 13038: push(@path,$parent); 13039: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories); 13040: pop(@path); 13041: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>'; 13042: $itemcount ++; 13043: } 13044: if ($itemcount) { 13045: $output = &Apache::loncommon::start_data_table(). 13046: $table. 13047: &Apache::loncommon::end_data_table(); 13048: } 13049: } 13050: } 13051: } 13052: return $output; 13053: } 13054: 13055: =pod 13056: 13057: =item *&assign_category_rows() 13058: 13059: Create a datatable row for display of nested categories in a domain, 13060: with checkboxes to allow a course to be categorized,called recursively. 13061: 13062: Inputs: 13063: 13064: itemcount - track row number for alternating colors 13065: 13066: cats - reference to array of arrays/hashes which encapsulates hierarchy of 13067: categories and subcategories. 13068: 13069: depth - current depth in hierarchy of categories and sub-categories - 0 indexed. 13070: 13071: parent - parent of current category item 13072: 13073: path - Array containing all categories back up through the hierarchy from the 13074: current category to the top level. 13075: 13076: currcategories - reference to array of current categories assigned to the course 13077: 13078: Returns: $output (markup to be displayed). 13079: 13080: =cut 13081: 13082: sub assign_category_rows { 13083: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_; 13084: my ($text,$name,$item,$chgstr); 13085: if (ref($cats) eq 'ARRAY') { 13086: my $maxdepth = scalar(@{$cats}); 13087: if (ref($cats->[$depth]) eq 'HASH') { 13088: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') { 13089: my $numchildren = @{$cats->[$depth]{$parent}}; 13090: my $css_class = $itemcount%2?' class="LC_odd_row"':''; 13091: $text .= '<td><table class="LC_datatable">'; 13092: for (my $j=0; $j<$numchildren; $j++) { 13093: $name = $cats->[$depth]{$parent}[$j]; 13094: $item = &escape($name).':'.&escape($parent).':'.$depth; 13095: my $deeper = $depth+1; 13096: my $checked = ''; 13097: if (ref($currcategories) eq 'ARRAY') { 13098: if (@{$currcategories} > 0) { 13099: if (grep(/^\Q$item\E$/,@{$currcategories})) { 13100: $checked = ' checked="checked"'; 13101: } 13102: } 13103: } 13104: $text .= '<tr><td><span class="LC_nobreak"><label>'. 13105: '<input type="checkbox" name="usecategory" value="'. 13106: $item.'"'.$checked.' />'.$name.'</label></span>'. 13107: '<input type="hidden" name="catname" value="'.$name.'" />'. 13108: '</td><td>'; 13109: if (ref($path) eq 'ARRAY') { 13110: push(@{$path},$name); 13111: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories); 13112: pop(@{$path}); 13113: } 13114: $text .= '</td></tr>'; 13115: } 13116: $text .= '</table></td>'; 13117: } 13118: } 13119: } 13120: return $text; 13121: } 13122: 13123: ############################################################ 13124: ############################################################ 13125: 13126: 13127: sub commit_customrole { 13128: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_; 13129: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url. 13130: ($start?', '.&mt('starting').' '.localtime($start):''). 13131: ($end?', ending '.localtime($end):'').': <b>'. 13132: &Apache::lonnet::assigncustomrole( 13133: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context). 13134: '</b><br />'; 13135: return $output; 13136: } 13137: 13138: sub commit_standardrole { 13139: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_; 13140: my ($output,$logmsg,$linefeed); 13141: if ($context eq 'auto') { 13142: $linefeed = "\n"; 13143: } else { 13144: $linefeed = "<br />\n"; 13145: } 13146: if ($three eq 'st') { 13147: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end, 13148: $one,$two,$sec,$context); 13149: if (($result =~ /^error/) || ($result eq 'not_in_class') || 13150: ($result eq 'unknown_course') || ($result eq 'refused')) { 13151: $output = $logmsg.' '.&mt('Error: ').$result."\n"; 13152: } else { 13153: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url. 13154: ($start?', '.&mt('starting').' '.localtime($start):''). 13155: ($end?', '.&mt('ending').' '.localtime($end):'').': '; 13156: if ($context eq 'auto') { 13157: $output .= $result.$linefeed.&mt('Add to classlist').': ok'; 13158: } else { 13159: $output .= '<b>'.$result.'</b>'.$linefeed. 13160: &mt('Add to classlist').': <b>ok</b>'; 13161: } 13162: $output .= $linefeed; 13163: } 13164: } else { 13165: $output = &mt('Assigning').' '.$three.' in '.$url. 13166: ($start?', '.&mt('starting').' '.localtime($start):''). 13167: ($end?', '.&mt('ending').' '.localtime($end):'').': '; 13168: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context); 13169: if ($context eq 'auto') { 13170: $output .= $result.$linefeed; 13171: } else { 13172: $output .= '<b>'.$result.'</b>'.$linefeed; 13173: } 13174: } 13175: return $output; 13176: } 13177: 13178: sub commit_studentrole { 13179: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_; 13180: my ($result,$linefeed,$oldsecurl,$newsecurl); 13181: if ($context eq 'auto') { 13182: $linefeed = "\n"; 13183: } else { 13184: $linefeed = '<br />'."\n"; 13185: } 13186: if (defined($one) && defined($two)) { 13187: my $cid=$one.'_'.$two; 13188: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid); 13189: my $secchange = 0; 13190: my $expire_role_result; 13191: my $modify_section_result; 13192: if ($oldsec ne '-1') { 13193: if ($oldsec ne $sec) { 13194: $secchange = 1; 13195: my $now = time; 13196: my $uurl='/'.$cid; 13197: $uurl=~s/\_/\//g; 13198: if ($oldsec) { 13199: $uurl.='/'.$oldsec; 13200: } 13201: $oldsecurl = $uurl; 13202: $expire_role_result = 13203: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context); 13204: if ($env{'request.course.sec'} ne '') { 13205: if ($expire_role_result eq 'refused') { 13206: my @roles = ('st'); 13207: my @statuses = ('previous'); 13208: my @roledoms = ($one); 13209: my $withsec = 1; 13210: my %roleshash = 13211: &Apache::lonnet::get_my_roles($uname,$udom,'userroles', 13212: \@statuses,\@roles,\@roledoms,$withsec); 13213: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) { 13214: my ($oldstart,$oldend) = 13215: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec}); 13216: if ($oldend > 0 && $oldend <= $now) { 13217: $expire_role_result = 'ok'; 13218: } 13219: } 13220: } 13221: } 13222: $result = $expire_role_result; 13223: } 13224: } 13225: if (($expire_role_result eq 'ok') || ($secchange == 0)) { 13226: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context); 13227: if ($modify_section_result =~ /^ok/) { 13228: if ($secchange == 1) { 13229: if ($sec eq '') { 13230: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed; 13231: } else { 13232: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed; 13233: } 13234: } elsif ($oldsec eq '-1') { 13235: if ($sec eq '') { 13236: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed; 13237: } else { 13238: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed; 13239: } 13240: } else { 13241: if ($sec eq '') { 13242: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed; 13243: } else { 13244: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed; 13245: } 13246: } 13247: } else { 13248: if ($secchange) { 13249: $$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; 13250: } else { 13251: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed; 13252: } 13253: } 13254: $result = $modify_section_result; 13255: } elsif ($secchange == 1) { 13256: if ($oldsec eq '') { 13257: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed; 13258: } else { 13259: $$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; 13260: } 13261: if ($expire_role_result eq 'refused') { 13262: my $newsecurl = '/'.$cid; 13263: $newsecurl =~ s/\_/\//g; 13264: if ($sec ne '') { 13265: $newsecurl.='/'.$sec; 13266: } 13267: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) { 13268: if ($sec eq '') { 13269: $$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; 13270: } else { 13271: $$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; 13272: } 13273: } 13274: } 13275: } 13276: } else { 13277: $$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; 13278: $result = "error: incomplete course id\n"; 13279: } 13280: return $result; 13281: } 13282: 13283: ############################################################ 13284: ############################################################ 13285: 13286: sub check_clone { 13287: my ($args,$linefeed) = @_; 13288: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'}; 13289: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid); 13290: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom); 13291: my $clonemsg; 13292: my $can_clone = 0; 13293: my $lctype = lc($args->{'crstype'}); 13294: if ($lctype ne 'community') { 13295: $lctype = 'course'; 13296: } 13297: if ($clonehome eq 'no_host') { 13298: if ($args->{'crstype'} eq 'Community') { 13299: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'}); 13300: } else { 13301: $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'}); 13302: } 13303: } else { 13304: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1}); 13305: if ($args->{'crstype'} eq 'Community') { 13306: if ($clonedesc{'type'} ne 'Community') { 13307: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'}); 13308: return ($can_clone, $clonemsg, $cloneid, $clonehome); 13309: } 13310: } 13311: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 13312: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) { 13313: $can_clone = 1; 13314: } else { 13315: my %clonehash = &Apache::lonnet::get('environment',['cloners'], 13316: $args->{'clonedomain'},$args->{'clonecourse'}); 13317: my @cloners = split(/,/,$clonehash{'cloners'}); 13318: if (grep(/^\*$/,@cloners)) { 13319: $can_clone = 1; 13320: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) { 13321: $can_clone = 1; 13322: } else { 13323: my $ccrole = 'cc'; 13324: if ($args->{'crstype'} eq 'Community') { 13325: $ccrole = 'co'; 13326: } 13327: my %roleshash = 13328: &Apache::lonnet::get_my_roles($args->{'ccuname'}, 13329: $args->{'ccdomain'}, 13330: 'userroles',['active'],[$ccrole], 13331: [$args->{'clonedomain'}]); 13332: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) { 13333: $can_clone = 1; 13334: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) { 13335: $can_clone = 1; 13336: } else { 13337: if ($args->{'crstype'} eq 'Community') { 13338: $clonemsg = &mt('No new community created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}); 13339: } else { 13340: $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}); 13341: } 13342: } 13343: } 13344: } 13345: } 13346: return ($can_clone, $clonemsg, $cloneid, $clonehome); 13347: } 13348: 13349: sub construct_course { 13350: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_; 13351: my $outcome; 13352: my $linefeed = '<br />'."\n"; 13353: if ($context eq 'auto') { 13354: $linefeed = "\n"; 13355: } 13356: 13357: # 13358: # Are we cloning? 13359: # 13360: my ($can_clone, $clonemsg, $cloneid, $clonehome); 13361: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) { 13362: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed); 13363: if ($context ne 'auto') { 13364: if ($clonemsg ne '') { 13365: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>'; 13366: } 13367: } 13368: $outcome .= $clonemsg.$linefeed; 13369: 13370: if (!$can_clone) { 13371: return (0,$outcome); 13372: } 13373: } 13374: 13375: # 13376: # Open course 13377: # 13378: my $crstype = lc($args->{'crstype'}); 13379: my %cenv=(); 13380: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'}, 13381: $args->{'cdescr'}, 13382: $args->{'curl'}, 13383: $args->{'course_home'}, 13384: $args->{'nonstandard'}, 13385: $args->{'crscode'}, 13386: $args->{'ccuname'}.':'. 13387: $args->{'ccdomain'}, 13388: $args->{'crstype'}, 13389: $cnum,$context,$category); 13390: 13391: # Note: The testing routines depend on this being output; see 13392: # Utils::Course. This needs to at least be output as a comment 13393: # if anyone ever decides to not show this, and Utils::Course::new 13394: # will need to be suitably modified. 13395: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed; 13396: if ($$courseid =~ /^error:/) { 13397: return (0,$outcome); 13398: } 13399: 13400: # 13401: # Check if created correctly 13402: # 13403: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid); 13404: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom); 13405: if ($crsuhome eq 'no_host') { 13406: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed; 13407: return (0,$outcome); 13408: } 13409: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed; 13410: 13411: # 13412: # Do the cloning 13413: # 13414: if ($can_clone && $cloneid) { 13415: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome); 13416: if ($context ne 'auto') { 13417: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>'; 13418: } 13419: $outcome .= $clonemsg.$linefeed; 13420: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum); 13421: # Copy all files 13422: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'}); 13423: # Restore URL 13424: $cenv{'url'}=$oldcenv{'url'}; 13425: # Restore title 13426: $cenv{'description'}=$oldcenv{'description'}; 13427: # Restore creation date, creator and creation context. 13428: $cenv{'internal.created'}=$oldcenv{'internal.created'}; 13429: $cenv{'internal.creator'}=$oldcenv{'internal.creator'}; 13430: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'}; 13431: # Mark as cloned 13432: $cenv{'clonedfrom'}=$cloneid; 13433: # Need to clone grading mode 13434: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum); 13435: $cenv{'grading'}=$newenv{'grading'}; 13436: # Do not clone these environment entries 13437: &Apache::lonnet::del('environment', 13438: ['default_enrollment_start_date', 13439: 'default_enrollment_end_date', 13440: 'question.email', 13441: 'policy.email', 13442: 'comment.email', 13443: 'pch.users.denied', 13444: 'plc.users.denied', 13445: 'hidefromcat', 13446: 'categories'], 13447: $$crsudom,$$crsunum); 13448: } 13449: 13450: # 13451: # Set environment (will override cloned, if existing) 13452: # 13453: my @sections = (); 13454: my @xlists = (); 13455: if ($args->{'crstype'}) { 13456: $cenv{'type'}=$args->{'crstype'}; 13457: } 13458: if ($args->{'crsid'}) { 13459: $cenv{'courseid'}=$args->{'crsid'}; 13460: } 13461: if ($args->{'crscode'}) { 13462: $cenv{'internal.coursecode'}=$args->{'crscode'}; 13463: } 13464: if ($args->{'crsquota'} ne '') { 13465: $cenv{'internal.coursequota'}=$args->{'crsquota'}; 13466: } else { 13467: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20; 13468: } 13469: if ($args->{'ccuname'}) { 13470: $cenv{'internal.courseowner'} = $args->{'ccuname'}. 13471: ':'.$args->{'ccdomain'}; 13472: } else { 13473: $cenv{'internal.courseowner'} = $args->{'curruser'}; 13474: } 13475: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner. 13476: if ($args->{'crssections'}) { 13477: $cenv{'internal.sectionnums'} = ''; 13478: if ($args->{'crssections'} =~ m/,/) { 13479: @sections = split/,/,$args->{'crssections'}; 13480: } else { 13481: $sections[0] = $args->{'crssections'}; 13482: } 13483: if (@sections > 0) { 13484: foreach my $item (@sections) { 13485: my ($sec,$gp) = split/:/,$item; 13486: my $class = $args->{'crscode'}.$sec; 13487: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'}); 13488: $cenv{'internal.sectionnums'} .= $item.','; 13489: unless ($addcheck eq 'ok') { 13490: push @badclasses, $class; 13491: } 13492: } 13493: $cenv{'internal.sectionnums'} =~ s/,$//; 13494: } 13495: } 13496: # do not hide course coordinator from staff listing, 13497: # even if privileged 13498: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 13499: # add crosslistings 13500: if ($args->{'crsxlist'}) { 13501: $cenv{'internal.crosslistings'}=''; 13502: if ($args->{'crsxlist'} =~ m/,/) { 13503: @xlists = split/,/,$args->{'crsxlist'}; 13504: } else { 13505: $xlists[0] = $args->{'crsxlist'}; 13506: } 13507: if (@xlists > 0) { 13508: foreach my $item (@xlists) { 13509: my ($xl,$gp) = split/:/,$item; 13510: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'}); 13511: $cenv{'internal.crosslistings'} .= $item.','; 13512: unless ($addcheck eq 'ok') { 13513: push @badclasses, $xl; 13514: } 13515: } 13516: $cenv{'internal.crosslistings'} =~ s/,$//; 13517: } 13518: } 13519: if ($args->{'autoadds'}) { 13520: $cenv{'internal.autoadds'}=$args->{'autoadds'}; 13521: } 13522: if ($args->{'autodrops'}) { 13523: $cenv{'internal.autodrops'}=$args->{'autodrops'}; 13524: } 13525: # check for notification of enrollment changes 13526: my @notified = (); 13527: if ($args->{'notify_owner'}) { 13528: if ($args->{'ccuname'} ne '') { 13529: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'}); 13530: } 13531: } 13532: if ($args->{'notify_dc'}) { 13533: if ($uname ne '') { 13534: push(@notified,$uname.':'.$udom); 13535: } 13536: } 13537: if (@notified > 0) { 13538: my $notifylist; 13539: if (@notified > 1) { 13540: $notifylist = join(',',@notified); 13541: } else { 13542: $notifylist = $notified[0]; 13543: } 13544: $cenv{'internal.notifylist'} = $notifylist; 13545: } 13546: if (@badclasses > 0) { 13547: my %lt=&Apache::lonlocal::texthash( 13548: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course', 13549: 'dnhr' => 'does not have rights to access enrollment in these classes', 13550: 'adby' => 'as determined by the policies of your institution on access to official classlists' 13551: ); 13552: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}. 13553: ' ('.$lt{'adby'}.')'; 13554: if ($context eq 'auto') { 13555: $outcome .= $badclass_msg.$linefeed; 13556: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n"; 13557: foreach my $item (@badclasses) { 13558: if ($context eq 'auto') { 13559: $outcome .= " - $item\n"; 13560: } else { 13561: $outcome .= "<li>$item</li>\n"; 13562: } 13563: } 13564: if ($context eq 'auto') { 13565: $outcome .= $linefeed; 13566: } else { 13567: $outcome .= "</ul><br /><br /></div>\n"; 13568: } 13569: } 13570: } 13571: if ($args->{'no_end_date'}) { 13572: $args->{'endaccess'} = 0; 13573: } 13574: $cenv{'internal.autostart'}=$args->{'enrollstart'}; 13575: $cenv{'internal.autoend'}=$args->{'enrollend'}; 13576: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'}; 13577: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'}; 13578: if ($args->{'showphotos'}) { 13579: $cenv{'internal.showphotos'}=$args->{'showphotos'}; 13580: } 13581: $cenv{'internal.authtype'} = $args->{'authtype'}; 13582: $cenv{'internal.autharg'} = $args->{'autharg'}; 13583: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) { 13584: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') { 13585: 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'); 13586: if ($context eq 'auto') { 13587: $outcome .= $krb_msg; 13588: } else { 13589: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>'; 13590: } 13591: $outcome .= $linefeed; 13592: } 13593: } 13594: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) { 13595: if ($args->{'setpolicy'}) { 13596: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 13597: } 13598: if ($args->{'setcontent'}) { 13599: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'}; 13600: } 13601: } 13602: if ($args->{'reshome'}) { 13603: $cenv{'reshome'}=$args->{'reshome'}.'/'; 13604: $cenv{'reshome'}=~s/\/+$/\//; 13605: } 13606: # 13607: # course has keyed access 13608: # 13609: if ($args->{'setkeys'}) { 13610: $cenv{'keyaccess'}='yes'; 13611: } 13612: # if specified, key authority is not course, but user 13613: # only active if keyaccess is yes 13614: if ($args->{'keyauth'}) { 13615: my ($user,$domain) = split(':',$args->{'keyauth'}); 13616: $user = &LONCAPA::clean_username($user); 13617: $domain = &LONCAPA::clean_username($domain); 13618: if ($user ne '' && $domain ne '') { 13619: $cenv{'keyauth'}=$user.':'.$domain; 13620: } 13621: } 13622: 13623: if ($args->{'disresdis'}) { 13624: $cenv{'pch.roles.denied'}='st'; 13625: } 13626: if ($args->{'disablechat'}) { 13627: $cenv{'plc.roles.denied'}='st'; 13628: } 13629: 13630: # Record we've not yet viewed the Course Initialization Helper for this 13631: # course 13632: $cenv{'course.helper.not.run'} = 1; 13633: # 13634: # Use new Randomseed 13635: # 13636: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();; 13637: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();; 13638: # 13639: # The encryption code and receipt prefix for this course 13640: # 13641: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999)); 13642: $cenv{'internal.encpref'}=100+int(9*rand(99)); 13643: # 13644: # By default, use standard grading 13645: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; } 13646: 13647: $outcome .= $linefeed.&mt('Setting environment').': '. 13648: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed; 13649: # 13650: # Open all assignments 13651: # 13652: if ($args->{'openall'}) { 13653: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate'; 13654: my %storecontent = ($storeunder => time, 13655: $storeunder.'.type' => 'date_start'); 13656: 13657: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput 13658: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed; 13659: } 13660: # 13661: # Set first page 13662: # 13663: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank') 13664: || ($cloneid)) { 13665: use LONCAPA::map; 13666: $outcome .= &mt('Setting first resource').': '; 13667: 13668: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence'; 13669: my ($errtext,$fatal)=&LONCAPA::map::mapread($map); 13670: 13671: $outcome .= ($fatal?$errtext:'read ok').' - '; 13672: my $title; my $url; 13673: if ($args->{'firstres'} eq 'syl') { 13674: $title=&mt('Syllabus'); 13675: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus'; 13676: } else { 13677: $title=&mt('Table of Contents'); 13678: $url='/adm/navmaps'; 13679: } 13680: 13681: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res'; 13682: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1); 13683: 13684: if ($errtext) { $fatal=2; } 13685: $outcome .= ($fatal?$errtext:'write ok').$linefeed; 13686: } 13687: 13688: return (1,$outcome); 13689: } 13690: 13691: ############################################################ 13692: ############################################################ 13693: 13694: #SD 13695: # only Community and Course, or anything else? 13696: sub course_type { 13697: my ($cid) = @_; 13698: if (!defined($cid)) { 13699: $cid = $env{'request.course.id'}; 13700: } 13701: if (defined($env{'course.'.$cid.'.type'})) { 13702: return $env{'course.'.$cid.'.type'}; 13703: } else { 13704: return 'Course'; 13705: } 13706: } 13707: 13708: sub group_term { 13709: my $crstype = &course_type(); 13710: my %names = ( 13711: 'Course' => 'group', 13712: 'Community' => 'group', 13713: ); 13714: return $names{$crstype}; 13715: } 13716: 13717: sub course_types { 13718: my @types = ('official','unofficial','community'); 13719: my %typename = ( 13720: official => 'Official course', 13721: unofficial => 'Unofficial course', 13722: community => 'Community', 13723: ); 13724: return (\@types,\%typename); 13725: } 13726: 13727: sub icon { 13728: my ($file)=@_; 13729: my $curfext = lc((split(/\./,$file))[-1]); 13730: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif'; 13731: my $embstyle = &Apache::loncommon::fileembstyle($curfext); 13732: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) { 13733: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'. 13734: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'. 13735: $curfext.".gif") { 13736: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'. 13737: $curfext.".gif"; 13738: } 13739: } 13740: return &lonhttpdurl($iconname); 13741: } 13742: 13743: sub lonhttpdurl { 13744: # 13745: # Had been used for "small fry" static images on separate port 8080. 13746: # Modify here if lightweight http functionality desired again. 13747: # Currently eliminated due to increasing firewall issues. 13748: # 13749: my ($url)=@_; 13750: return $url; 13751: } 13752: 13753: sub connection_aborted { 13754: my ($r)=@_; 13755: $r->print(" ");$r->rflush(); 13756: my $c = $r->connection; 13757: return $c->aborted(); 13758: } 13759: 13760: # Escapes strings that may have embedded 's that will be put into 13761: # strings as 'strings'. 13762: sub escape_single { 13763: my ($input) = @_; 13764: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)> 13765: $input =~ s/\'/\\\'/g; # Esacpe the 's.... 13766: return $input; 13767: } 13768: 13769: # Same as escape_single, but escape's "'s This 13770: # can be used for "strings" 13771: sub escape_double { 13772: my ($input) = @_; 13773: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)> 13774: $input =~ s/\"/\\\"/g; # Esacpe the "s.... 13775: return $input; 13776: } 13777: 13778: # Escapes the last element of a full URL. 13779: sub escape_url { 13780: my ($url) = @_; 13781: my @urlslices = split(/\//, $url,-1); 13782: my $lastitem = &escape(pop(@urlslices)); 13783: return join('/',@urlslices).'/'.$lastitem; 13784: } 13785: 13786: sub compare_arrays { 13787: my ($arrayref1,$arrayref2) = @_; 13788: my (@difference,%count); 13789: @difference = (); 13790: %count = (); 13791: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) { 13792: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; } 13793: foreach my $element (keys(%count)) { 13794: if ($count{$element} == 1) { 13795: push(@difference,$element); 13796: } 13797: } 13798: } 13799: return @difference; 13800: } 13801: 13802: # -------------------------------------------------------- Initialize user login 13803: sub init_user_environment { 13804: my ($r, $username, $domain, $authhost, $form, $args) = @_; 13805: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'}; 13806: 13807: my $public=($username eq 'public' && $domain eq 'public'); 13808: 13809: # See if old ID present, if so, remove 13810: 13811: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv); 13812: my $now=time; 13813: 13814: if ($public) { 13815: my $max_public=100; 13816: my $oldest; 13817: my $oldest_time=0; 13818: for(my $next=1;$next<=$max_public;$next++) { 13819: if (-e $lonids."/publicuser_$next.id") { 13820: my $mtime=(stat($lonids."/publicuser_$next.id"))[9]; 13821: if ($mtime<$oldest_time || !$oldest_time) { 13822: $oldest_time=$mtime; 13823: $oldest=$next; 13824: } 13825: } else { 13826: $cookie="publicuser_$next"; 13827: last; 13828: } 13829: } 13830: if (!$cookie) { $cookie="publicuser_$oldest"; } 13831: } else { 13832: # if this isn't a robot, kill any existing non-robot sessions 13833: if (!$args->{'robot'}) { 13834: opendir(DIR,$lonids); 13835: while ($filename=readdir(DIR)) { 13836: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) { 13837: unlink($lonids.'/'.$filename); 13838: } 13839: } 13840: closedir(DIR); 13841: } 13842: # Give them a new cookie 13843: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'} 13844: : $now.$$.int(rand(10000))); 13845: $cookie="$username\_$id\_$domain\_$authhost"; 13846: 13847: # Initialize roles 13848: 13849: ($userroles,$firstaccenv,$timerintenv) = 13850: &Apache::lonnet::rolesinit($domain,$username,$authhost); 13851: } 13852: # ------------------------------------ Check browser type and MathML capability 13853: 13854: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml, 13855: $clientunicode,$clientos) = &decode_user_agent($r); 13856: 13857: # ------------------------------------------------------------- Get environment 13858: 13859: my %userenv = &Apache::lonnet::dump('environment',$domain,$username); 13860: my ($tmp) = keys(%userenv); 13861: if ($tmp !~ /^(con_lost|error|no_such_host)/i) { 13862: } else { 13863: undef(%userenv); 13864: } 13865: if (($userenv{'interface'}) && (!$form->{'interface'})) { 13866: $form->{'interface'}=$userenv{'interface'}; 13867: } 13868: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; } 13869: 13870: # --------------- Do not trust query string to be put directly into environment 13871: foreach my $option ('interface','localpath','localres') { 13872: $form->{$option}=~s/[\n\r\=]//gs; 13873: } 13874: # --------------------------------------------------------- Write first profile 13875: 13876: { 13877: my %initial_env = 13878: ("user.name" => $username, 13879: "user.domain" => $domain, 13880: "user.home" => $authhost, 13881: "browser.type" => $clientbrowser, 13882: "browser.version" => $clientversion, 13883: "browser.mathml" => $clientmathml, 13884: "browser.unicode" => $clientunicode, 13885: "browser.os" => $clientos, 13886: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'}, 13887: "request.course.fn" => '', 13888: "request.course.uri" => '', 13889: "request.course.sec" => '', 13890: "request.role" => 'cm', 13891: "request.role.adv" => $env{'user.adv'}, 13892: "request.host" => $ENV{'REMOTE_ADDR'},); 13893: 13894: if ($form->{'localpath'}) { 13895: $initial_env{"browser.localpath"} = $form->{'localpath'}; 13896: $initial_env{"browser.localres"} = $form->{'localres'}; 13897: } 13898: 13899: if ($form->{'interface'}) { 13900: $form->{'interface'}=~s/\W//gs; 13901: $initial_env{"browser.interface"} = $form->{'interface'}; 13902: $env{'browser.interface'}=$form->{'interface'}; 13903: } 13904: 13905: my %is_adv = ( is_adv => $env{'user.adv'} ); 13906: my %domdef; 13907: unless ($domain eq 'public') { 13908: %domdef = &Apache::lonnet::get_domain_defaults($domain); 13909: } 13910: 13911: foreach my $tool ('aboutme','blog','webdav','portfolio') { 13912: $userenv{'availabletools.'.$tool} = 13913: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload', 13914: undef,\%userenv,\%domdef,\%is_adv); 13915: } 13916: 13917: foreach my $crstype ('official','unofficial','community') { 13918: $userenv{'canrequest.'.$crstype} = 13919: &Apache::lonnet::usertools_access($username,$domain,$crstype, 13920: 'reload','requestcourses', 13921: \%userenv,\%domdef,\%is_adv); 13922: } 13923: 13924: $userenv{'canrequest.author'} = 13925: &Apache::lonnet::usertools_access($username,$domain,'requestauthor', 13926: 'reload','requestauthor', 13927: \%userenv,\%domdef,\%is_adv); 13928: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'], 13929: $domain,$username); 13930: my $reqstatus = $reqauthor{'author_status'}; 13931: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 13932: if (ref($reqauthor{'author'}) eq 'HASH') { 13933: $userenv{'requestauthorqueued'} = $reqstatus.':'. 13934: $reqauthor{'author'}{'timestamp'}; 13935: } 13936: } 13937: 13938: $env{'user.environment'} = "$lonids/$cookie.id"; 13939: 13940: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id", 13941: &GDBM_WRCREAT(),0640)) { 13942: &_add_to_env(\%disk_env,\%initial_env); 13943: &_add_to_env(\%disk_env,\%userenv,'environment.'); 13944: &_add_to_env(\%disk_env,$userroles); 13945: if (ref($firstaccenv) eq 'HASH') { 13946: &_add_to_env(\%disk_env,$firstaccenv); 13947: } 13948: if (ref($timerintenv) eq 'HASH') { 13949: &_add_to_env(\%disk_env,$timerintenv); 13950: } 13951: if (ref($args->{'extra_env'})) { 13952: &_add_to_env(\%disk_env,$args->{'extra_env'}); 13953: } 13954: untie(%disk_env); 13955: } else { 13956: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ". 13957: 'Could not create environment storage in lonauth: '.$!.'</span>'); 13958: return 'error: '.$!; 13959: } 13960: } 13961: $env{'request.role'}='cm'; 13962: $env{'request.role.adv'}=$env{'user.adv'}; 13963: $env{'browser.type'}=$clientbrowser; 13964: 13965: return $cookie; 13966: 13967: } 13968: 13969: sub _add_to_env { 13970: my ($idf,$env_data,$prefix) = @_; 13971: if (ref($env_data) eq 'HASH') { 13972: while (my ($key,$value) = each(%$env_data)) { 13973: $idf->{$prefix.$key} = $value; 13974: $env{$prefix.$key} = $value; 13975: } 13976: } 13977: } 13978: 13979: # --- Get the symbolic name of a problem and the url 13980: sub get_symb { 13981: my ($request,$silent) = @_; 13982: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--; 13983: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url))); 13984: if ($symb eq '') { 13985: if (!$silent) { 13986: if (ref($request)) { 13987: $request->print("Unable to handle ambiguous references:$url:."); 13988: } 13989: return (); 13990: } 13991: } 13992: &Apache::lonenc::check_decrypt(\$symb); 13993: return ($symb); 13994: } 13995: 13996: # --------------------------------------------------------------Get annotation 13997: 13998: sub get_annotation { 13999: my ($symb,$enc) = @_; 14000: 14001: my $key = $symb; 14002: if (!$enc) { 14003: $key = 14004: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]); 14005: } 14006: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]); 14007: return $annotation{$key}; 14008: } 14009: 14010: sub clean_symb { 14011: my ($symb,$delete_enc) = @_; 14012: 14013: &Apache::lonenc::check_decrypt(\$symb); 14014: my $enc = $env{'request.enc'}; 14015: if ($delete_enc) { 14016: delete($env{'request.enc'}); 14017: } 14018: 14019: return ($symb,$enc); 14020: } 14021: 14022: sub build_release_hashes { 14023: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_; 14024: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') && 14025: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') && 14026: (ref($randomizetry) eq 'HASH')); 14027: foreach my $key (keys(%Apache::lonnet::needsrelease)) { 14028: my ($item,$name,$value) = split(/:/,$key); 14029: if ($item eq 'parameter') { 14030: if (ref($checkparms->{$name}) eq 'ARRAY') { 14031: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) { 14032: push(@{$checkparms->{$name}},$value); 14033: } 14034: } else { 14035: push(@{$checkparms->{$name}},$value); 14036: } 14037: } elsif ($item eq 'resourcetag') { 14038: if ($name eq 'responsetype') { 14039: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key} 14040: } 14041: } elsif ($item eq 'course') { 14042: if ($name eq 'crstype') { 14043: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key}; 14044: } 14045: } 14046: } 14047: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'}); 14048: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'}); 14049: return; 14050: } 14051: 14052: sub update_content_constraints { 14053: my ($cdom,$cnum,$chome,$cid) = @_; 14054: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired'); 14055: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'}); 14056: my %checkresponsetypes; 14057: foreach my $key (keys(%Apache::lonnet::needsrelease)) { 14058: my ($item,$name,$value) = split(/:/,$key); 14059: if ($item eq 'resourcetag') { 14060: if ($name eq 'responsetype') { 14061: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key} 14062: } 14063: } 14064: } 14065: my $navmap = Apache::lonnavmaps::navmap->new(); 14066: if (defined($navmap)) { 14067: my %allresponses; 14068: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) { 14069: my %responses = $res->responseTypes(); 14070: foreach my $key (keys(%responses)) { 14071: next unless(exists($checkresponsetypes{$key})); 14072: $allresponses{$key} += $responses{$key}; 14073: } 14074: } 14075: foreach my $key (keys(%allresponses)) { 14076: my ($major,$minor) = split(/\./,$checkresponsetypes{$key}); 14077: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) { 14078: ($reqdmajor,$reqdminor) = ($major,$minor); 14079: } 14080: } 14081: undef($navmap); 14082: } 14083: unless (($reqdmajor eq '') && ($reqdminor eq '')) { 14084: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid); 14085: } 14086: return; 14087: } 14088: 14089: sub parse_supplemental_title { 14090: my ($title) = @_; 14091: 14092: my ($foldertitle,$renametitle); 14093: if ($title =~ /&&&/) { 14094: $title = &HTML::Entites::decode($title); 14095: } 14096: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) { 14097: $renametitle=$4; 14098: my ($time,$uname,$udom) = ($1,$2,$3); 14099: $foldertitle=&Apache::lontexconvert::msgtexconverted($4); 14100: my $name = &plainname($uname,$udom); 14101: $name = &HTML::Entities::encode($name,'"<>&\''); 14102: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\''); 14103: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '. 14104: $name.': <br />'.$foldertitle; 14105: } 14106: if (wantarray) { 14107: return ($title,$foldertitle,$renametitle); 14108: } 14109: return $title; 14110: } 14111: 14112: sub symb_to_docspath { 14113: my ($symb) = @_; 14114: return unless ($symb); 14115: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb); 14116: if ($resurl=~/\.(sequence|page)$/) { 14117: $mapurl=$resurl; 14118: } elsif ($resurl eq 'adm/navmaps') { 14119: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'}; 14120: } 14121: my $mapresobj; 14122: my $navmap = Apache::lonnavmaps::navmap->new(); 14123: if (ref($navmap)) { 14124: $mapresobj = $navmap->getResourceByUrl($mapurl); 14125: } 14126: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1}; 14127: my $type=$2; 14128: my $path; 14129: if (ref($mapresobj)) { 14130: my $pcslist = $mapresobj->map_hierarchy(); 14131: if ($pcslist ne '') { 14132: foreach my $pc (split(/,/,$pcslist)) { 14133: next if ($pc <= 1); 14134: my $res = $navmap->getByMapPc($pc); 14135: if (ref($res)) { 14136: my $thisurl = $res->src(); 14137: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1}; 14138: my $thistitle = $res->title(); 14139: $path .= '&'. 14140: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'. 14141: &Apache::lonhtmlcommon::entity_encode($thistitle). 14142: ':'.$res->randompick(). 14143: ':'.$res->randomout(). 14144: ':'.$res->encrypted(). 14145: ':'.$res->randomorder(). 14146: ':'.$res->is_page(); 14147: } 14148: } 14149: } 14150: $path =~ s/^\&//; 14151: my $maptitle = $mapresobj->title(); 14152: if ($mapurl eq 'default') { 14153: $maptitle = 'Main Course Documents'; 14154: } 14155: $path .= (($path ne '')? '&' : ''). 14156: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. 14157: &Apache::lonhtmlcommon::entity_encode($maptitle). 14158: ':'.$mapresobj->randompick(). 14159: ':'.$mapresobj->randomout(). 14160: ':'.$mapresobj->encrypted(). 14161: ':'.$mapresobj->randomorder(). 14162: ':'.$mapresobj->is_page(); 14163: } else { 14164: my $maptitle = &Apache::lonnet::gettitle($mapurl); 14165: my $ispage = (($type eq 'page')? 1 : ''); 14166: if ($mapurl eq 'default') { 14167: $maptitle = 'Main Course Documents'; 14168: } 14169: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'. 14170: &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage; 14171: } 14172: unless ($mapurl eq 'default') { 14173: $path = 'default&'. 14174: &Apache::lonhtmlcommon::entity_encode('Main Course Documents'). 14175: ':::::&'.$path; 14176: } 14177: return $path; 14178: } 14179: 14180: sub captcha_display { 14181: my ($context,$lonhost) = @_; 14182: my ($output,$error); 14183: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); 14184: if ($captcha eq 'original') { 14185: $output = &create_captcha(); 14186: unless ($output) { 14187: $error = 'captcha'; 14188: } 14189: } elsif ($captcha eq 'recaptcha') { 14190: $output = &create_recaptcha($pubkey); 14191: unless ($output) { 14192: $error = 'recaptcha'; 14193: } 14194: } 14195: return ($output,$error); 14196: } 14197: 14198: sub captcha_response { 14199: my ($context,$lonhost) = @_; 14200: my ($captcha_chk,$captcha_error); 14201: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost); 14202: if ($captcha eq 'original') { 14203: ($captcha_chk,$captcha_error) = &check_captcha(); 14204: } elsif ($captcha eq 'recaptcha') { 14205: $captcha_chk = &check_recaptcha($privkey); 14206: } else { 14207: $captcha_chk = 1; 14208: } 14209: return ($captcha_chk,$captcha_error); 14210: } 14211: 14212: sub get_captcha_config { 14213: my ($context,$lonhost) = @_; 14214: my ($captcha,$pubkey,$privkey,$hashtocheck); 14215: my $hostname = &Apache::lonnet::hostname($lonhost); 14216: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname); 14217: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID); 14218: if ($context eq 'usercreation') { 14219: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom); 14220: if (ref($domconfig{$context}) eq 'HASH') { 14221: $hashtocheck = $domconfig{$context}{'cancreate'}; 14222: if (ref($hashtocheck) eq 'HASH') { 14223: if ($hashtocheck->{'captcha'} eq 'recaptcha') { 14224: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') { 14225: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'}; 14226: $privkey = $hashtocheck->{'recaptchakeys'}{'private'}; 14227: } 14228: if ($privkey && $pubkey) { 14229: $captcha = 'recaptcha'; 14230: } else { 14231: $captcha = 'original'; 14232: } 14233: } elsif ($hashtocheck->{'captcha'} ne 'notused') { 14234: $captcha = 'original'; 14235: } 14236: } 14237: } else { 14238: $captcha = 'captcha'; 14239: } 14240: } elsif ($context eq 'login') { 14241: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom); 14242: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') { 14243: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'}; 14244: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'}; 14245: if ($privkey && $pubkey) { 14246: $captcha = 'recaptcha'; 14247: } else { 14248: $captcha = 'original'; 14249: } 14250: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') { 14251: $captcha = 'original'; 14252: } 14253: } 14254: return ($captcha,$pubkey,$privkey); 14255: } 14256: 14257: sub create_captcha { 14258: my %captcha_params = &captcha_settings(); 14259: my ($output,$maxtries,$tries) = ('',10,0); 14260: while ($tries < $maxtries) { 14261: $tries ++; 14262: my $captcha = Authen::Captcha->new ( 14263: output_folder => $captcha_params{'output_dir'}, 14264: data_folder => $captcha_params{'db_dir'}, 14265: ); 14266: my $md5sum = $captcha->generate_code($captcha_params{'numchars'}); 14267: 14268: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') { 14269: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n". 14270: &mt('Type in the letters/numbers shown below').' '. 14271: '<input type="text" size="5" name="code" value="" /><br />'. 14272: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />'; 14273: last; 14274: } 14275: } 14276: return $output; 14277: } 14278: 14279: sub captcha_settings { 14280: my %captcha_params = ( 14281: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'}, 14282: www_output_dir => "/captchaspool", 14283: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'}, 14284: numchars => '5', 14285: ); 14286: return %captcha_params; 14287: } 14288: 14289: sub check_captcha { 14290: my ($captcha_chk,$captcha_error); 14291: my $code = $env{'form.code'}; 14292: my $md5sum = $env{'form.crypt'}; 14293: my %captcha_params = &captcha_settings(); 14294: my $captcha = Authen::Captcha->new( 14295: output_folder => $captcha_params{'output_dir'}, 14296: data_folder => $captcha_params{'db_dir'}, 14297: ); 14298: my $captcha_chk = $captcha->check_code($code,$md5sum); 14299: my %captcha_hash = ( 14300: 0 => 'Code not checked (file error)', 14301: -1 => 'Failed: code expired', 14302: -2 => 'Failed: invalid code (not in database)', 14303: -3 => 'Failed: invalid code (code does not match crypt)', 14304: ); 14305: if ($captcha_chk != 1) { 14306: $captcha_error = $captcha_hash{$captcha_chk} 14307: } 14308: return ($captcha_chk,$captcha_error); 14309: } 14310: 14311: sub create_recaptcha { 14312: my ($pubkey) = @_; 14313: my $captcha = Captcha::reCAPTCHA->new; 14314: return $captcha->get_options_setter({theme => 'white'})."\n". 14315: $captcha->get_html($pubkey). 14316: &mt('If either word is hard to read, [_1] will replace them.', 14317: '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />'). 14318: '<br /><br />'; 14319: } 14320: 14321: sub check_recaptcha { 14322: my ($privkey) = @_; 14323: my $captcha_chk; 14324: my $captcha = Captcha::reCAPTCHA->new; 14325: my $captcha_result = 14326: $captcha->check_answer( 14327: $privkey, 14328: $ENV{'REMOTE_ADDR'}, 14329: $env{'form.recaptcha_challenge_field'}, 14330: $env{'form.recaptcha_response_field'}, 14331: ); 14332: if ($captcha_result->{is_valid}) { 14333: $captcha_chk = 1; 14334: } 14335: return $captcha_chk; 14336: } 14337: 14338: =pod 14339: 14340: =back 14341: 14342: =cut 14343: 14344: 1; 14345: __END__; 14346: